From 4d3ed8660d477692e7a21dbb6aad62f0e8d3981f Mon Sep 17 00:00:00 2001 From: flarum-bot Date: Sun, 24 Nov 2024 09:32:16 +0000 Subject: [PATCH] Bundled output for commit 1e3699f968937504b39aaa743426fa4a1cdad32d Includes transpiled JS/TS, and Typescript declaration files (typings). [skip ci] --- js/dist/forum.js | 3 ++- js/dist/forum.js.LICENSE.txt | 15 +-------------- js/dist/forum.js.map | 2 +- js/dist/forum.replay.js | 2 +- js/dist/forum.replay.js.map | 2 +- js/dist/forum.tracing.js | 3 ++- js/dist/forum.tracing.js.LICENSE.txt | 1 + js/dist/forum.tracing.js.map | 2 +- js/dist/forum.tracing.replay.js | 2 +- js/dist/forum.tracing.replay.js.map | 2 +- 10 files changed, 12 insertions(+), 22 deletions(-) create mode 100644 js/dist/forum.tracing.js.LICENSE.txt diff --git a/js/dist/forum.js b/js/dist/forum.js index 5865eaa..1dd332c 100644 --- a/js/dist/forum.js +++ b/js/dist/forum.js @@ -1,2 +1,3 @@ -(()=>{var t={476:(t,e,n)=>{"use strict";function r(){return"undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&!!__SENTRY_BROWSER_BUNDLE__}function i(){return"npm"}n.d(e,{S:()=>i,n:()=>r})},538:(t,e,n)=>{"use strict";n.d(e,{KV:()=>i,l$:()=>o});var r=n(476);function i(){return!(0,r.n)()&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}function o(t,e){return t.require(e)}t=n.hmd(t)},910:(t,e,n)=>{"use strict";n.d(e,{ph:()=>f,yW:()=>c});var r=n(538),i=n(899);t=n.hmd(t);var o=(0,i.Rf)(),a={nowSeconds:function(){return Date.now()/1e3}},s=(0,r.KV)()?function(){try{return(0,r.l$)(t,"perf_hooks").performance}catch(t){return}}():function(){var t=o.performance;if(t&&t.now)return{now:function(){return t.now()},timeOrigin:Date.now()-t.now()}}(),u=void 0===s?a:{nowSeconds:function(){return(s.timeOrigin+s.now())/1e3}},c=a.nowSeconds.bind(a),f=u.nowSeconds.bind(u);!function(){var t=o.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,a=i{"use strict";function r(t){return t&&t.Math==Math?t:void 0}n.d(e,{Rf:()=>o,YO:()=>a,n2:()=>i});var i="object"==typeof globalThis&&r(globalThis)||"object"==typeof window&&r(window)||"object"==typeof self&&r(self)||"object"==typeof n.g&&r(n.g)||function(){return this}()||{};function o(){return i}function a(t,e,n){var r=n||i,o=r.__SENTRY__=r.__SENTRY__||{};return o[t]||(o[t]=e())}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var o=e[r]={id:r,loaded:!1,exports:{}};return t[r](o,o.exports,n),o.loaded=!0,o.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.hmd=t=>((t=Object.create(t)).children||(t.children=[]),Object.defineProperty(t,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+t.id)}}),t),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=Object.prototype.toString;function o(t){switch(i.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return h(t,Error)}}function a(t,e){return i.call(t)==="[object "+e+"]"}function s(t){return a(t,"ErrorEvent")}function u(t){return a(t,"DOMError")}function c(t){return a(t,"String")}function f(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function l(t){return a(t,"Object")}function d(t){return"undefined"!=typeof Event&&h(t,Event)}function p(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function h(t,e){try{return t instanceof e}catch(t){return!1}}function v(t,e){return void 0===e&&(e=0),"string"!=typeof t||0===e||t.length<=e?t:t.slice(0,e)+"..."}function _(t,e){if(!Array.isArray(t))return"";for(var n=[],r=0;r=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(t){return null}}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&a+3*i.length+n.length>=u);)i.push(n),a+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function j(t,e){var n,r,i,o,a,s=t,u=[];if(!s||!s.tagName)return"";u.push(s.tagName.toLowerCase());var f=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(f&&f.length)f.forEach((function(t){u.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&u.push("#"+s.id),(n=s.className)&&c(n))for(r=n.split(/\s+/),a=0;a"}}function N(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function M(t,e){void 0===e&&(e=40);var n=Object.keys(P(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return v(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:v(i,e)}return""}function L(t){return U(t,new Map)}function U(t,e){if(l(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,o=Object.keys(t);i=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function F(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n>t/4).toString(16)}))}function z(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function J(t){var e=t.message,n=t.event_id;if(e)return e;var r=z(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function G(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],o=i[0]=i[0]||{};o.value||(o.value=e||""),o.type||(o.type=n||"Error")}function K(t,e){var n=z(t);if(n){var r=n.mechanism;if(n.mechanism=E({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=E({},r&&r.data,e.data);n.mechanism.data=i}}}function X(t){if(t&&t.__sentry_captured__)return!0;try{R(t,"__sentry_captured__",!0)}catch(t){}return!1}var V,Q=n(910),Z=["debug","info","warn","error","log","assert","trace"];V={enable:function(){},disable:function(){}},Z.forEach((function(t){V[t]=function(){}}));var tt,et="production";function nt(t){return new it((function(e){e(t)}))}function rt(t){return new it((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(tt||(tt={}));var it=function(){var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this);try{t(this._resolve,this._reject)}catch(t){this._reject(t)}}return t.__init=function(){this._state=tt.PENDING},t.__init2=function(){this._handlers=[]},t.then=function(t,n){var r=this;return new e((function(e,i){r._handlers.push([!1,function(n){if(t)try{e(t(n))}catch(t){i(t)}else e(n)},function(t){if(n)try{e(n(t))}catch(t){i(t)}else i(t)}]),r._executeHandlers()}))},t.catch=function(t){return this.then((function(t){return t}),t)},t.finally=function(t){var n=this;return new e((function(e,r){var i,o;return n.then((function(e){o=!1,i=e,t&&t()}),(function(e){o=!0,i=e,t&&t()})).then((function(){o?r(i):e(i)}))}))},t.__init3=function(){var t=this;this._resolve=function(e){t._setResult(tt.RESOLVED,e)}},t.__init4=function(){var t=this;this._reject=function(e){t._setResult(tt.REJECTED,e)}},t.__init5=function(){var t=this;this._setResult=function(e,n){t._state===tt.PENDING&&(p(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},t.__init6=function(){var t=this;this._executeHandlers=function(){if(t._state!==tt.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===tt.RESOLVED&&e[1](t._value),t._state===tt.REJECTED&&e[2](t._value),e[0]=!0)}))}}},e}();function ot(t,e){if(void 0===e&&(e={}),e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||(0,Q.ph)(),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:Y()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=""+e.did),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{var n=t.timestamp-t.started;t.duration=n>=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}var at=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={}}t.clone=function(e){var n=new t;return e&&(n._breadcrumbs=[].concat(e._breadcrumbs),n._tags=E({},e._tags),n._extra=E({},e._extra),n._contexts=E({},e._contexts),n._user=e._user,n._level=e._level,n._span=e._span,n._session=e._session,n._transactionName=e._transactionName,n._fingerprint=e._fingerprint,n._eventProcessors=[].concat(e._eventProcessors),n._requestSession=e._requestSession,n._attachments=[].concat(e._attachments),n._sdkProcessingMetadata=E({},e._sdkProcessingMetadata)),n};var e=t.prototype;return e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{},this._session&&ot(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=E({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=E({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=E({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=E({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this.getSpan();return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;if("function"==typeof e){var n=e(this);return n instanceof t?n:this}return e instanceof t?(this._tags=E({},this._tags,e._tags),this._extra=E({},this._extra,e._extra),this._contexts=E({},this._contexts,e._contexts),e._user&&Object.keys(e._user).length&&(this._user=e._user),e._level&&(this._level=e._level),e._fingerprint&&(this._fingerprint=e._fingerprint),e._requestSession&&(this._requestSession=e._requestSession)):l(e)&&(this._tags=E({},this._tags,e.tags),this._extra=E({},this._extra,e.extra),this._contexts=E({},this._contexts,e.contexts),e.user&&(this._user=e.user),e.level&&(this._level=e.level),e.fingerprint&&(this._fingerprint=e.fingerprint),e.requestSession&&(this._requestSession=e.requestSession)),this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=E({timestamp:(0,Q.yW)()},t);return this._breadcrumbs=[].concat(this._breadcrumbs,[r]).slice(-n),this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this._attachments},e.clearAttachments=function(){return this._attachments=[],this},e.applyToEvent=function(t,e){if(void 0===e&&(e={}),this._extra&&Object.keys(this._extra).length&&(t.extra=E({},this._extra,t.extra)),this._tags&&Object.keys(this._tags).length&&(t.tags=E({},this._tags,t.tags)),this._user&&Object.keys(this._user).length&&(t.user=E({},this._user,t.user)),this._contexts&&Object.keys(this._contexts).length&&(t.contexts=E({},this._contexts,t.contexts)),this._level&&(t.level=this._level),this._transactionName&&(t.transaction=this._transactionName),this._span){t.contexts=E({trace:this._span.getTraceContext()},t.contexts);var n=this._span.transaction;if(n){t.sdkProcessingMetadata=E({dynamicSamplingContext:n.getDynamicSamplingContext()},t.sdkProcessingMetadata);var r=n.name;r&&(t.tags=E({transaction:r},t.tags))}}return this._applyFingerprint(t),t.breadcrumbs=[].concat(t.breadcrumbs||[],this._breadcrumbs),t.breadcrumbs=t.breadcrumbs.length>0?t.breadcrumbs:void 0,t.sdkProcessingMetadata=E({},t.sdkProcessingMetadata,this._sdkProcessingMetadata),this._notifyEventProcessors([].concat(st(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=E({},this._sdkProcessingMetadata,t),this},e._notifyEventProcessors=function(t,e,n,r){var i=this;return void 0===r&&(r=0),new it((function(o,a){var s=t[r];if(null===e||"function"!=typeof s)o(e);else{var u=s(E({},e),n);p(u)?u.then((function(e){return i._notifyEventProcessors(t,e,n,r+1).then(o)})).then(null,a):i._notifyEventProcessors(t,u,n,r+1).then(o).then(null,a)}}))},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},e._applyFingerprint=function(t){var e;t.fingerprint=t.fingerprint?(e=t.fingerprint,Array.isArray(e)?e:[e]):[],this._fingerprint&&(t.fingerprint=t.fingerprint.concat(this._fingerprint)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint},t}();function st(){return(0,x.YO)("globalEventProcessors",(function(){return[]}))}function ut(t){st().push(t)}var ct=4,ft=function(){function t(t,e,n){void 0===e&&(e=new at),void 0===n&&(n=ct),this._version=n,this._stack=[{scope:e}],t&&this.bindClient(t)}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;i0}function mt(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return r;if(D(t))return t}catch(e){return t}var i=function(){var r,i=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var o=i.map((function(t){return mt(t,e)}));return t.apply(this,o)}catch(t){throw gt++,setTimeout((function(){gt--})),r=function(n){var r;n.addEventProcessor((function(t){return e.mechanism&&(G(t,void 0,void 0),K(t,e.mechanism)),t.extra=E({},t.extra,{arguments:i}),t})),r=t,pt().captureException(r,{captureContext:undefined})},pt().withScope(r),t}};try{for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(i[o]=t[o])}catch(t){}I(i,t),R(t,"__sentry_wrapped__",i);try{Object.getOwnPropertyDescriptor(i,"name").configurable&&Object.defineProperty(i,"name",{get:function(){return t.name}})}catch(t){}return i}var bt=["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"],St=function(){e.__initStatic=function(){this.id="TryCatch"};var t=e.prototype;function e(t){e.prototype.__init.call(this),this._options=E({XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){this._options.setTimeout&&A(_t,"setTimeout",Et),this._options.setInterval&&A(_t,"setInterval",Et),this._options.requestAnimationFrame&&A(_t,"requestAnimationFrame",wt),this._options.XMLHttpRequest&&"XMLHttpRequest"in _t&&A(XMLHttpRequest.prototype,"send",xt);var t=this._options.eventTarget;t&&(Array.isArray(t)?t:bt).forEach(kt)},e}();function Et(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n2?n[2]:void 0;if(i){var o=Rt,a=String(i);Rt=a,Lt("history",{from:o,to:a})}return t.apply(this,n)}}}();break;case"error":Wt=It.onerror,It.onerror=function(t,e,n,r,i){return Lt("error",{column:r,error:i,line:n,msg:t,url:e}),!(!Wt||Wt.__SENTRY_LOADER__)&&Wt.apply(this,arguments)},It.onerror.__SENTRY_INSTRUMENTED__=!0;break;case"unhandledrejection":Yt=It.onunhandledrejection,It.onunhandledrejection=function(t){return Lt("unhandledrejection",t),!(Yt&&!Yt.__SENTRY_LOADER__)||Yt.apply(this,arguments)},It.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0;break;default:return}}function Mt(t,e){Pt[t]=Pt[t]||[],Pt[t].push(e),Nt(t)}function Lt(t,e){if(t&&Pt[t])for(var n,r=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return At(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?At(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Pt[t]||[]);!(n=r()).done;){var i=n.value;try{i(e)}catch(t){}}}function Ut(t,e){return!!t&&"object"==typeof t&&!!t[e]}function qt(t){return"string"==typeof t?t:t?Ut(t,"url")?t.url:t.toString?t.toString():"":""}var Bt,Ft,$t=1e3;function Ht(t,e){return void 0===e&&(e=!1),function(n){if(n&&Ft!==n&&!function(t){if("keypress"!==t.type)return!1;try{var e=t.target;if(!e||!e.tagName)return!0;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||e.isContentEditable)return!1}catch(t){}return!0}(n)){var r="keypress"===n.type?"input":n.type;(void 0===Bt||function(t,e){if(!t)return!0;if(t.type!==e.type)return!0;try{if(t.target!==e.target)return!0}catch(t){}return!1}(Ft,n))&&(t({event:n,name:r,global:e}),Ft=n),clearTimeout(Bt),Bt=It.setTimeout((function(){Bt=void 0}),$t)}}}var Wt=null,Yt=null;function zt(t,e,n){void 0===e&&(e=100),void 0===n&&(n=1/0);try{return Gt("",t,e,n)}catch(t){return{ERROR:"**non-serializable** ("+t+")"}}}function Jt(t,e,n){void 0===e&&(e=3),void 0===n&&(n=102400);var r,i=zt(t,e);return r=i,function(t){return~-encodeURI(t).split(/%..|./).length}(JSON.stringify(r))>n?Jt(t,e-1,n):i}function Gt(t,e,r,i,o){var a,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===o&&(a="function"==typeof WeakSet,s=a?new WeakSet:[],o=[function(t){if(a)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){_[m]="[MaxProperties ~]";break}var b=y[m];_[m]=Gt(m,b,h-1,i,o),g++}return d(e),_}function Kt(t,e){var n=Vt(t,e),r={type:e&&e.name,value:Zt(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Xt(t,e){return{exception:{values:[Kt(t,e)]}}}function Vt(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(Qt.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var Qt=/Minified React error #\d+;/i;function Zt(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function te(t,e,n,r,i){var c;if(s(e)&&e.error)return Xt(t,e.error);if(u(e)||a(e,"DOMException")){var f=e;if("stack"in e)c=Xt(t,e);else{var p=f.name||(u(f)?"DOMError":"DOMException"),h=f.message?p+": "+f.message:p;G(c=ee(t,h,n,r),h)}return"code"in f&&(c.tags=E({},c.tags,{"DOMException.code":""+f.code})),c}return o(e)?Xt(t,e):l(e)||d(e)?(c=function(t,e,n,r){var i=pt().getClient(),o=i&&i.getOptions().normalizeDepth,a={exception:{values:[{type:d(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:"Non-Error "+(r?"promise rejection":"exception")+" captured with keys: "+M(e)}]},extra:{__serialized__:Jt(e,o)}};if(n){var s=Vt(t,n);s.length&&(a.exception.values[0].stacktrace={frames:s})}return a}(t,e,n,i),K(c,{synthetic:!0}),c):(G(c=ee(t,e,n,r),""+e,void 0),K(c,{synthetic:!0}),c)}function ee(t,e,n,r){var i={message:e};if(r&&n){var o=Vt(t,n);o.length&&(i.exception={values:[{value:e,stacktrace:{frames:o}}]})}return i}var ne=function(){e.__initStatic=function(){this.id="GlobalHandlers"};var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),this._options=E({onerror:!0,onunhandledrejection:!0},t)}return t.__init=function(){this.name=e.id},t.__init2=function(){this._installFunc={onerror:re,onunhandledrejection:ie}},t.setupOnce=function(){Error.stackTraceLimit=50;var t=this._options;for(var e in t){var n=this._installFunc[e];n&&t[e]&&(n(),this._installFunc[e]=void 0)}},e}();function re(){Mt("error",(function(t){var e=se(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(ne)){var o=t.msg,a=t.url,u=t.line,f=t.column,l=t.error;if(!(yt()||l&&l.__sentry_own_request__)){var d=void 0===l&&c(o)?function(t,e,n,r){var i=s(t)?t.message:t,o="Error",a=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return a&&(o=a[1],i=a[2]),oe({exception:{values:[{type:o,value:i}]}},e,n,r)}(o,a,u,f):oe(te(r,l||o,void 0,i,!1),a,u,f);d.level="error",ae(n,l,d,"onerror")}}}))}function ie(){Mt("unhandledrejection",(function(t){var e=se(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(ne)){var o=t;try{"reason"in t?o=t.reason:"detail"in t&&"reason"in t.detail&&(o=t.detail.reason)}catch(t){}if(yt()||o&&o.__sentry_own_request__)return!0;var a=f(o)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(o)}]}}:te(r,o,void 0,i,!0);a.level="error",ae(n,o,a,"onunhandledrejection")}}))}function oe(t,e,n,r){var i=t.exception=t.exception||{},o=i.values=i.values||[],a=o[0]=o[0]||{},s=a.stacktrace=a.stacktrace||{},u=s.frames=s.frames||[],f=isNaN(parseInt(r,10))?void 0:r,l=isNaN(parseInt(n,10))?void 0:n,d=c(e)&&e.length>0?e:function(){try{return k.document.location.href}catch(t){return""}}();return 0===u.length&&u.push({colno:f,filename:d,function:"?",in_app:!0,lineno:l}),t}function ae(t,e,n,r){K(n,{handled:!1,type:r}),t.captureEvent(n,{originalException:e})}function se(){var t=pt(),e=t.getClient(),n=e&&e.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1};return[t,n.stackParser,n.attachStacktrace]}ne.__initStatic();var ue=["fatal","error","warning","log","info","debug"];function ce(t){return"warn"===t?"warning":ue.includes(t)?t:"log"}function fe(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var le="Breadcrumbs",de=function(){e.__initStatic=function(){this.id=le};var t=e.prototype;function e(t){e.prototype.__init.call(this),this.options=E({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){var t;this.options.console&&Mt("console",pe),this.options.dom&&Mt("dom",(t=this.options.dom,function(e){var n,r="object"==typeof t?t.serializeAttribute:void 0,i="object"==typeof t&&"number"==typeof t.maxStringLength?t.maxStringLength:void 0;i&&i>1024&&(i=1024),"string"==typeof r&&(r=[r]);try{var o=e.event;n=function(t){return t&&!!t.target}(o)?T(o.target,{keyAttrs:r,maxStringLength:i}):T(o,{keyAttrs:r,maxStringLength:i})}catch(t){n=""}0!==n.length&&pt().addBreadcrumb({category:"ui."+e.name,message:n},{event:e.event,name:e.name,global:e.global})})),this.options.xhr&&Mt("xhr",he),this.options.fetch&&Mt("fetch",ve),this.options.history&&Mt("history",_e)},t.addSentryBreadcrumb=function(t){this.options.sentry&&pt().addBreadcrumb({category:"sentry."+("transaction"===t.type?"transaction":"event"),event_id:t.event_id,level:t.level,message:J(t)},{event:t})},e}();function pe(t){for(var e=0;e=e)return i;var o=Kt(t,n[r]);return ye(t,e,n[r],r,[o].concat(i))}ge.__initStatic();var me=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="HttpContext"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(){ut((function(e){if(pt().getIntegration(t)){if(!_t.navigator&&!_t.location&&!_t.document)return e;var n=e.request&&e.request.url||_t.location&&_t.location.href,r=(_t.document||{}).referrer,i=(_t.navigator||{}).userAgent,o=E({},e.request&&e.request.headers,r&&{Referer:r},i&&{"User-Agent":i}),a=E({},e.request,n&&{url:n},{headers:o});return E({},e,{request:a})}return e}))},t}();function be(t,e){return be=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},be(t,e)}function Se(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,be(t,e)}me.__initStatic();var Ee="7.56.0",we=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function xe(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,o=t.port,a=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(o?":"+o:"")+"/"+(r?r+"/":r)+a}function ke(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function Oe(t){var e="string"==typeof t?function(t){var e=we.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],o=n[2],a=void 0===o?"":o,s=n[3],u=n[4],c=void 0===u?"":u,f="",l=n[5],d=l.split("/");if(d.length>1&&(f=d.slice(0,-1).join("/"),l=d.pop()),l){var p=l.match(/^\d+/);p&&(l=p[0])}return ke({host:s,pass:a,path:f,projectId:l,port:c,protocol:r,publicKey:i})}console.error("Invalid Sentry Dsn: "+t)}(t):ke(t);if(e)return e}function Te(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return je(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?je(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function je(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Ge(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},t._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._dsn},t._prepareEvent=function(t,e,n){var r=this.getOptions(),i=Object.keys(this._integrations);return!e.integrations&&i.length>0&&(e.integrations=i),function(t,e,n,r){var i=t.normalizeDepth,o=void 0===i?3:i,a=t.normalizeMaxBreadth,s=void 0===a?1e3:a,u=E({},e,{event_id:e.event_id||n.event_id||Y(),timestamp:e.timestamp||(0,Q.yW)()}),c=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,o=e.maxValueLength,a=void 0===o?250:o;"environment"in t||(t.environment="environment"in e?n:et),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=v(t.message,a));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=v(s.value,a));var u=t.request;u&&u.url&&(u.url=v(u.url,a))}(u,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(u,c),void 0===e.type&&function(t,e){var n,r=x.n2._sentryDebugIds;if(r){var i=ze.get(e);i?n=i:(n=new Map,ze.set(e,n));var o=Object.keys(r).reduce((function(t,i){var o,a=n.get(i);a?o=a:(o=e(i),n.set(i,o));for(var s=o.length-1;s>=0;s--){var u=o[s];if(u.filename){t[u.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=o[t.filename])}))}))}catch(t){}}}(u,t.stackParser);var f=r;n.captureContext&&(f=at.clone(f).update(n.captureContext));var l=nt(u);if(f){if(f.getAttachments){var d=[].concat(n.attachments||[],f.getAttachments());d.length&&(n.attachments=d)}l=f.applyToEvent(u,n)}return l.then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof o&&o>0?function(t,e,n){if(!t)return null;var r=E({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return E({},t,t.data&&{data:zt(t.data,e,n)})}))},t.user&&{user:zt(t.user,e,n)},t.contexts&&{contexts:zt(t.contexts,e,n)},t.extra&&{extra:zt(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=zt(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){return t.data&&(t.data=zt(t.data,e,n)),t}))),r}(t,o,s):t}))}(r,t,e,n)},t._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){}))},t._processEvent=function(t,e,n){var r=this,i=this.getOptions(),o=i.sampleRate;if(!this._isEnabled())return rt(new Be("SDK not enabled, will not capture event.","log"));var a=Ve(t),s=Xe(t),u=t.type||"error",c="before send for type `"+u+"`";if(s&&"number"==typeof o&&Math.random()>o)return this.recordDroppedEvent("sample_rate","error",t),rt(new Be("Discarding event because it's not included in the random sample (sampling rate = "+o+")","log"));var f="replay_event"===u?"replay":u;return this._prepareEvent(t,e,n).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",f,t),new Be("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var o=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;return Xe(e)&&r?r(e,n):Ve(e)&&i?i(e,n):e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(p(t))return t.then((function(t){if(!l(t)&&null!==t)throw new Be(n);return t}),(function(t){throw new Be(e+" rejected with "+t)}));if(!l(t)&&null!==t)throw new Be(n);return t}(o,c)})).then((function(i){if(null===i)throw r.recordDroppedEvent("before_send",f,t),new Be(c+" returned `null`, will not send event.","log");var o=n&&n.getSession();!a&&o&&r._updateSessionFromEvent(o,i);var s=i.transaction_info;return a&&s&&i.transaction!==t.transaction&&(i.transaction_info=E({},s,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof Be)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new Be("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},t._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},t._sendEnvelope=function(t){if(this._transport&&this._dsn)return this.emit("beforeEnvelope",t),this._transport.send(t).then(null,(function(t){}))},t._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},e}();function Xe(t){return void 0===t.type}function Ve(t){return"transaction"===t.type}var Qe=n(476),Ze=function(t){function e(e){var n,r=_t.SENTRY_SDK_SOURCE||(0,Qe.S)();return e._metadata=e._metadata||{},e._metadata.sdk=e._metadata.sdk||{name:"sentry.javascript.browser",packages:[{name:r+":@sentry/browser",version:Ee}],version:Ee},n=t.call(this,e)||this,e.sendClientReports&&_t.document&&_t.document.addEventListener("visibilitychange",(function(){"hidden"===_t.document.visibilityState&&n._flushOutcomes()})),n}Se(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=te(t,e,n&&n.syntheticException||void 0,r);return K(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),nt(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var o=ee(t,e,r&&r.syntheticException||void 0,i);return o.level=n,r&&r.event_id&&(o.event_id=r.event_id),nt(o)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.sendEvent=function(e,n){var r=this.getIntegrationById(le);r&&r.addSentryBreadcrumb&&r.addSentryBreadcrumb(e),t.prototype.sendEvent.call(this,e,n)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,o=E({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:xe(i)}),a=function(t){return[{type:"user_report"},t]}(t);return Ae(o,[a])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,Ae((n=this._options.tunnel&&xe(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:(0,Q.yW)(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(Ke);function tn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return en(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?en(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function en(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){nt(t).then((function(){--i||(clearTimeout(o),n(!0))}),r)}))}))}}}(t.bufferSize||rn));var r={};function i(i){var o=[];if(Re(i,(function(e,n){var i,a,s,u=Ne(n);if(i=r,a=u,void 0===s&&(s=Date.now()),function(t,e){return t[e]||t.all||0}(i,a)>s){var c=an(e,n);t.recordDroppedEvent("ratelimit_backoff",u,c)}else o.push(e)})),0===o.length)return nt();var a=Ae(i[0],o),s=function(e){Re(a,(function(n,r){var i=an(n,r);t.recordDroppedEvent(e,Ne(r),i)}))};return n.add((function(){return e({body:De(a,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var o=E({},t),a=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(a)for(var u,c=tn(a.trim().split(","));!(u=c()).done;){var f=u.value.split(":",2),l=f[0],d=f[1],p=parseInt(l,10),h=1e3*(isNaN(p)?60:p);if(d)for(var v,_=tn(d.split(";"));!(v=_()).done;)o[v.value]=n+h;else o.all=n+h}else s?o.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?nn:r-e}(s,n):429===r&&(o.all=n+6e4);return o}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof Be)return s("queue_overflow"),nt();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function an(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var sn=void 0;function un(t,e){void 0===e&&(e=function(){if(sn)return sn;if(Tt(_t.fetch))return sn=_t.fetch.bind(_t);var t=_t.document,e=_t.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return sn=e.bind(_t)}());var n=0,r=0;return on(t,(function(i){var o=i.body.length;n+=o,r++;var a=E({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,a).then((function(t){return n-=o,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return sn=void 0,n-=o,r--,rt(t)}}))}var cn="?";function fn(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var ln=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dn=/\((\S*)(?::(\d+))(?::(\d+))\)/,pn=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,hn=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vn=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,_n=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=$.test(a)?a.replace($,"$1"):a;if(!s.match(/\S*Error: /)){for(var u,c=B(r);!(u=c()).done;){var f=(0,u.value)(s);if(f){n.push(f);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=t.slice(0,50),n=e[e.length-1].function;n&&/sentryWrapped/.test(n)&&e.pop(),e.reverse();var r=e[e.length-1].function;return r&&/captureMessage|captureException/.test(r)&&e.pop(),e.map((function(t){return E({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=ln.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=dn.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=gn(e[1]||cn,e[2]),i=r[0];return fn(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=pn.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=hn.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||cn,o=gn(i,r);return i=o[0],fn(r=o[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=vn.exec(t);return e?fn(e[2],e[1]||cn,+e[3],e[4]?+e[4]:void 0):void 0}]]),gn=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:cn,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},yn=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="Dedupe"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(e,n){var r=function(e){if(e.type)return e;var r=n().getIntegration(t);if(r){try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!bn(t,e)&&!!mn(t,e))))}(t,e)||!!function(t,e){var n=Sn(e),r=Sn(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!bn(t,e)&&!!mn(t,e)))}(t,e))}(e,r._previousEvent))return null}catch(t){return r._previousEvent=e}return r._previousEvent=e}return e};r.id=this.name,e(r)},t}();function mn(t,e){var n=En(t),r=En(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i{var t={648:(t,e,n)=>{var r=n(288).default;function i(){"use strict";t.exports=i=function(){return e},t.exports.__esModule=!0,t.exports.default=t.exports;var e={},n=Object.prototype,o=n.hasOwnProperty,a=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",u=s.asyncIterator||"@@asyncIterator",f=s.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function p(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,o=Object.create(i.prototype),s=new j(r||[]);return a(o,"_invoke",{value:w(t,n,s)}),o}function h(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=p;var d={};function v(){}function g(){}function _(){}var m={};l(m,c,(function(){return this}));var y=Object.getPrototypeOf,b=y&&y(y(C([])));b&&b!==n&&o.call(b,c)&&(m=b);var S=_.prototype=v.prototype=Object.create(m);function x(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function E(t,e){function n(i,a,s,c){var u=h(t[i],t,a);if("throw"!==u.type){var f=u.arg,l=f.value;return l&&"object"==r(l)&&o.call(l,"__await")?e.resolve(l.__await).then((function(t){n("next",t,s,c)}),(function(t){n("throw",t,s,c)})):e.resolve(l).then((function(t){f.value=t,s(f)}),(function(t){return n("throw",t,s,c)}))}c(u.arg)}var i;a(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,i){n(t,r,e,i)}))}return i=i?i.then(o,o):o()}})}function w(t,e,n){var r="suspendedStart";return function(i,o){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw o;return{value:void 0,done:!0}}for(n.method=i,n.arg=o;;){var a=n.delegate;if(a){var s=k(a,n);if(s){if(s===d)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var c=h(t,e,n);if("normal"===c.type){if(r=n.done?"completed":"suspendedYield",c.arg===d)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r="completed",n.method="throw",n.arg=c.arg)}}}function k(t,e){var n=e.method,r=t.iterator[n];if(void 0===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=void 0,k(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=h(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,d;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,d):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,d)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function j(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function C(t){if(t){var e=t[c];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n=0;--r){var i=this.tryEntries[r],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=o.call(i,"catchLoc"),c=o.call(i,"finallyLoc");if(s&&c){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),T(n),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;T(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:C(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),d}},e}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},288:t=>{function e(n){return t.exports=e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.__esModule=!0,t.exports.default=t.exports,e(n)}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports},357:(t,e,n)=>{var r=n(648)();t.exports=r;try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var o=e[r]={exports:{}};return t[r](o,o.exports,n),o.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=!1;function o(t){return t&&t.Math==Math?t:void 0}var a="object"==typeof globalThis&&o(globalThis)||"object"==typeof window&&o(window)||"object"==typeof self&&o(self)||"object"==typeof n.g&&o(n.g)||function(){return this}()||{};function s(){return a}function c(t,e,n){var r=n||a,i=r.__SENTRY__=r.__SENTRY__||{};return i[t]||(i[t]=e())}var u=["debug","info","warn","error","log","assert","trace"],f={};function l(t){if(!("console"in a))return t();var e=a.console,n={},r=Object.keys(f);r.forEach((function(t){var r=f[t];n[t]=e[t],e[t]=r}));try{return t()}finally{r.forEach((function(t){e[t]=n[t]}))}}var p,h,d=(p=!1,h={enable:function(){p=!0},disable:function(){p=!1},isEnabled:function(){return p}},i?u.forEach((function(t){h[t]=function(){for(var e=arguments.length,n=new Array(e),r=0;r";try{for(var n,r=t,i=[],o=0,a=0,s=Array.isArray(e)?e:e.keyAttrs,c=!Array.isArray(e)&&e.maxStringLength||I;r&&o++<5&&!("html"===(n=P(r,s))||o>1&&a+3*i.length+n.length>=c);)i.push(n),a+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function P(t,e){var n,r,i,o,a,s=t,c=[];if(!s||!s.tagName)return"";if(C.HTMLElement&&s instanceof HTMLElement&&s.dataset&&s.dataset.sentryComponent)return s.dataset.sentryComponent;c.push(s.tagName.toLowerCase());var u=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(u&&u.length)u.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&c.push("#"+s.id),(n=s.className)&&S(n))for(r=n.split(/\s+/),a=0;a"}}function H(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function Y(t){return $(t,new Map)}function $(t,e){if(function(t){if(!w(t))return!1;try{var e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,o=Object.keys(t);i>t/4).toString(16)}))}function z(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function V(t){var e=t.message,n=t.event_id;if(e)return e;var r=z(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function G(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],o=i[0]=i[0]||{};o.value||(o.value=e||""),o.type||(o.type=n||"Error")}function W(t,e){var n=z(t);if(n){var r=n.mechanism;if(n.mechanism=v({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=v({},r&&r.data,e.data);n.mechanism.data=i}}}function K(t){if(t&&t.__sentry_captured__)return!0;try{M(t,"__sentry_captured__",!0)}catch(t){}return!1}var X,Q=!1;function Z(t){return new et((function(e){e(t)}))}function tt(t){return new et((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(X||(X={}));var et=function(){function t(e){t.prototype.__init.call(this),t.prototype.__init2.call(this),t.prototype.__init3.call(this),t.prototype.__init4.call(this),this._state=X.PENDING,this._handlers=[];try{e(this._resolve,this._reject)}catch(t){this._reject(t)}}var e=t.prototype;return e.then=function(e,n){var r=this;return new t((function(t,i){r._handlers.push([!1,function(n){if(e)try{t(e(n))}catch(t){i(t)}else t(n)},function(e){if(n)try{t(n(e))}catch(t){i(t)}else i(e)}]),r._executeHandlers()}))},e.catch=function(t){return this.then((function(t){return t}),t)},e.finally=function(e){var n=this;return new t((function(t,r){var i,o;return n.then((function(t){o=!1,i=t,e&&e()}),(function(t){o=!0,i=t,e&&e()})).then((function(){o?r(i):t(i)}))}))},e.__init=function(){var t=this;this._resolve=function(e){t._setResult(X.RESOLVED,e)}},e.__init2=function(){var t=this;this._reject=function(e){t._setResult(X.REJECTED,e)}},e.__init3=function(){var t=this;this._setResult=function(e,n){t._state===X.PENDING&&(O(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},e.__init4=function(){var t=this;this._executeHandlers=function(){if(t._state!==X.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===X.RESOLVED&&e[1](t._value),t._state===X.REJECTED&&e[2](t._value),e[0]=!0)}))}}},t}();function nt(){return c("globalEventProcessors",(function(){return[]}))}function rt(t){nt().push(t)}function it(t,e,n,r){return void 0===r&&(r=0),new et((function(i,o){var a=t[r];if(null===e||"function"!=typeof a)i(e);else{var s=a(v({},e),n);Q&&a.id&&null===s&&d.log('Event processor "'+a.id+'" dropped event'),O(s)?s.then((function(e){return it(t,e,n,r+1).then(i)})).then(null,o):it(t,s,n,r+1).then(i).then(null,o)}}))}var ot=1e3;function at(){return Date.now()/ot}var st=function(){var t=a.performance;if(!t||!t.now)return at;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/ot}}(),ct=(function(){var t=a.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function ft(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return lt(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?lt(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function lt(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nn?_t(t,e-1,n):i}function mt(t,e,r,i,o){var a,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===o&&(a="function"==typeof WeakSet,s=a?new WeakSet:[],o=[function(t){if(a)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){v[m]="[MaxProperties ~]";break}var y=_[m];v[m]=mt(m,y,h-1,i,o),g++}return l(e),v}var yt=1;function bt(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=St(t);return Y({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function St(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}var xt=new WeakMap;var Et=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function wt(t,e){return Ft().captureEvent(t,e)}function kt(t,e){Ft().addBreadcrumb(t,e)}function Ot(){return Ft().getClient()}function Tt(t){return t.transaction}function jt(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=Y({environment:r.environment||ct,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}function Ct(t){var e=Ot();if(!e)return{};var n=jt(St(t).trace_id||"",e,Ft().getScope()),r=Tt(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=St(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&yt)}(r)),e.emit&&e.emit("createDsc",n),n}function It(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=Y(n);c&&Object.keys(c).length&&(t.extra=v({},c,t.extra));var u=Y(r);u&&Object.keys(u).length&&(t.tags=v({},u,t.tags));var f=Y(i);f&&Object.keys(f).length&&(t.user=v({},f,t.user));var l=Y(o);l&&Object.keys(l).length&&(t.contexts=v({},l,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=v({trace:bt(e)},t.contexts);var n=Tt(e);if(n){t.sdkProcessingMetadata=v({dynamicSamplingContext:Ct(e)},t.sdkProcessingMetadata);var r=St(n).description;r&&(t.tags=v({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=v({},t.sdkProcessingMetadata,e)}(t,o)}function At(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.sdkProcessingMetadata,c=e.breadcrumbs,u=e.fingerprint,f=e.eventProcessors,l=e.attachments,p=e.propagationContext,h=e.transactionName,d=e.span;Pt(t,"extra",n),Pt(t,"tags",r),Pt(t,"user",i),Pt(t,"contexts",o),Pt(t,"sdkProcessingMetadata",s),a&&(t.level=a),h&&(t.transactionName=h),d&&(t.span=d),c.length&&(t.breadcrumbs=[].concat(t.breadcrumbs,c)),u.length&&(t.fingerprint=[].concat(t.fingerprint,u)),f.length&&(t.eventProcessors=[].concat(t.eventProcessors,f)),l.length&&(t.attachments=[].concat(t.attachments,l)),t.propagationContext=v({},t.propagationContext,p)}function Pt(t,e,n){if(n&&Object.keys(n).length)for(var r in t[e]=v({},t[e]),n)Object.prototype.hasOwnProperty.call(n,r)&&(t[e][r]=n[r])}var Dt,Nt=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=Lt()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=v({},this._tags),e._extra=v({},this._extra),e._contexts=v({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=v({},this._sdkProcessingMetadata),e._propagationContext=v({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&ut(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=v({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=v({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=v({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=v({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=v({},this._tags,r.tags),this._extra=v({},this._extra,r.extra),this._contexts=v({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(w(n)){var i=e;this._tags=v({},this._tags,i.tags),this._extra=v({},this._extra,i.extra),this._contexts=v({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=Lt(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=v({timestamp:at()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),It(t,this.getScopeData()),it([].concat(n,nt(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=v({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:J();if(!this._client)return d.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,v({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:J();if(!this._client)return d.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,v({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:J();return this._client?(this._client.captureEvent(t,v({},e,{event_id:n}),this),n):(d.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function Lt(){return{traceId:J(),spanId:J().substring(16)}}var Rt="7.119.1",Mt=parseFloat(Rt),Ut=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=Mt),this._version=r,e?i=e:(i=new Nt).setClient(t),n?o=n:(o=new Nt).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(n=r()).done;){var i=n.value;i&&i.afterAllSetup&&i.afterAllSetup(t)}}function Vt(t,e,n){if(n[e.name])Q&&d.log("Integration skipped because it was already installed: "+e.name);else{if(n[e.name]=e,-1===Jt.indexOf(e.name)&&(e.setupOnce(rt,Ft),Jt.push(e.name)),e.setup&&"function"==typeof e.setup&&e.setup(t),t.on&&"function"==typeof e.preprocessEvent){var r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(function(e,n){return r(e,n,t)}))}if(t.addEventProcessor&&"function"==typeof e.processEvent){var i=e.processEvent.bind(e),o=Object.assign((function(e,n){return i(e,n,t)}),{id:e.name});t.addEventProcessor(o)}Q&&d.log("Integration installed: "+e.name)}}function Gt(t,e){return Object.assign((function(){return e.apply(void 0,arguments)}),{id:t})}var Wt,Kt=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/],Xt=[/^.*\/healthcheck$/,/^.*\/healthy$/,/^.*\/live$/,/^.*\/ready$/,/^.*\/heartbeat$/,/^.*\/health$/,/^.*\/healthz$/],Qt="InboundFilters",Zt=function(t){return void 0===t&&(t={}),{name:Qt,setupOnce:function(){},processEvent:function(e,n,r){var i=r.getOptions(),o=function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),{allowUrls:[].concat(t.allowUrls||[],e.allowUrls||[]),denyUrls:[].concat(t.denyUrls||[],e.denyUrls||[]),ignoreErrors:[].concat(t.ignoreErrors||[],e.ignoreErrors||[],t.disableErrorDefaults?[]:Kt),ignoreTransactions:[].concat(t.ignoreTransactions||[],e.ignoreTransactions||[],t.disableTransactionDefaults?[]:Xt),ignoreInternal:void 0===t.ignoreInternal||t.ignoreInternal}}(t,i);return function(t,e){return e.ignoreInternal&&function(t){try{return"SentryError"===t.exception.values[0].type}catch(t){}return!1}(t)?(Q&&d.warn("Event dropped due to being internal Sentry Error.\nEvent: "+V(t)),!0):function(t,e){return!(t.type||!e||!e.length)&&function(t){var e,n=[];t.message&&n.push(t.message);try{e=t.exception.values[t.exception.values.length-1]}catch(t){}return e&&e.value&&(n.push(e.value),e.type&&n.push(e.type+": "+e.value)),Q&&0===n.length&&d.error("Could not extract message for event "+V(t)),n}(t).some((function(t){return L(t,e)}))}(t,e.ignoreErrors)?(Q&&d.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: "+V(t)),!0):function(t,e){if("transaction"!==t.type||!e||!e.length)return!1;var n=t.transaction;return!!n&&L(n,e)}(t,e.ignoreTransactions)?(Q&&d.warn("Event dropped due to being matched by `ignoreTransactions` option.\nEvent: "+V(t)),!0):function(t,e){if(!e||!e.length)return!1;var n=ee(t);return!!n&&L(n,e)}(t,e.denyUrls)?(Q&&d.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: "+V(t)+".\nUrl: "+ee(t)),!0):!function(t,e){if(!e||!e.length)return!0;var n=ee(t);return!n||L(n,e)}(t,e.allowUrls)&&(Q&&d.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: "+V(t)+".\nUrl: "+ee(t)),!0)}(e,o)?null:e}}},te=Gt(Qt,Zt);function ee(t){try{var e;try{e=t.exception.values[0].stacktrace.frames}catch(t){}return e?function(t){void 0===t&&(t=[]);for(var e=t.length-1;e>=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(e){return Q&&d.error("Cannot extract url for event "+V(t)),null}}var ne="FunctionToString",re=new WeakMap,ie=function(){return{name:ne,setupOnce:function(){Wt=Function.prototype.toString;try{Function.prototype.toString=function(){for(var t=q(this),e=re.has(Ot())&&void 0!==t?t:this,n=arguments.length,r=new Array(n),i=0;i0}function ue(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return"function"==typeof r?r:t;if(q(t))return t}catch(e){return t}var i=function(){var r=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var i=r.map((function(t){return ue(t,e)}));return t.apply(this,i)}catch(t){throw se++,setTimeout((function(){se--})),function(){for(var t=Ft(),e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=o()).done;){var a=r.value;try{a(e)}catch(e){i&&d.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+vt(a)+"\nError:",e)}}}var we=null;function ke(){we=a.onerror,a.onerror=function(t,e,n,r,i){return Ee("error",{column:r,error:i,line:n,msg:t,url:e}),!(!we||we.__SENTRY_LOADER__)&&we.apply(this,arguments)},a.onerror.__SENTRY_INSTRUMENTED__=!0}var Oe=null;function Te(){Oe=a.onunhandledrejection,a.onunhandledrejection=function(t){return Ee("unhandledrejection",t),!(Oe&&!Oe.__SENTRY_LOADER__)||Oe.apply(this,arguments)},a.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function je(t,e){var n=Ie(t,e),r={type:e&&e.name,value:Pe(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Ce(t,e){return{exception:{values:[je(t,e)]}}}function Ie(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(Ae.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var Ae=/Minified React error #\d+;/i;function Pe(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function De(t,e,n,r,i){var o;if(y(e)&&e.error)return Ce(t,e.error);if(b(e)||m(e,"DOMException")){var a=e;if("stack"in e)o=Ce(t,e);else{var s=a.name||(b(a)?"DOMError":"DOMException"),c=a.message?s+": "+a.message:s;G(o=Ne(t,c,n,r),c)}return"code"in a&&(o.tags=v({},o.tags,{"DOMException.code":""+a.code})),o}return _(e)?Ce(t,e):w(e)||k(e)?(o=function(t,e,n,r){var i=Ot(),o=i&&i.getOptions().normalizeDepth,a={exception:{values:[{type:k(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:Le(e,{isUnhandledRejection:r})}]},extra:{__serialized__:_t(e,o)}};if(n){var s=Ie(t,n);s.length&&(a.exception.values[0].stacktrace={frames:s})}return a}(t,e,n,i),W(o,{synthetic:!0}),o):(G(o=Ne(t,e,n,r),""+e,void 0),W(o,{synthetic:!0}),o)}function Ne(t,e,n,r){var i={};if(r&&n){var o=Ie(t,n);o.length&&(i.exception={values:[{value:e,stacktrace:{frames:o}}]})}if(x(e)){var a=e.__sentry_template_string__,s=e.__sentry_template_values__;return i.logentry={message:a,params:s},i}return i.message=e,i}function Le(t,e){var n=e.isUnhandledRejection,r=function(t,e){void 0===e&&(e=40);var n=Object.keys(B(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return D(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:D(i,e)}return""}(t),i=n?"promise rejection":"exception";return y(t)?"Event `ErrorEvent` captured as "+i+" with message `"+t.message+"`":k(t)?"Event `"+function(t){try{var e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch(t){}}(t)+"` (type="+t.type+") captured as "+i:"Object captured as "+i+" with keys: "+r}var Re="GlobalHandlers",Me=function(t){void 0===t&&(t={});var e=v({onerror:!0,onunhandledrejection:!0},t);return{name:Re,setupOnce:function(){Error.stackTraceLimit=50},setup:function(t){e.onerror&&(function(t){var e,n;e=function(e){var n=Fe(),r=n.stackParser,i=n.attachStacktrace;if(Ot()===t&&!ce()){var o=e.msg,a=e.url,s=e.line,c=e.column,u=e.error,f=void 0===u&&S(o)?function(t,e,n,r){var i=y(t)?t.message:t,o="Error",a=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return a&&(o=a[1],i=a[2]),qe({exception:{values:[{type:o,value:i}]}},e,n,r)}(o,a,s,c):qe(De(r,u||o,void 0,i,!1),a,s,c);f.level="error",wt(f,{originalException:u,mechanism:{handled:!1,type:"onerror"}})}},Se(n="error",e),xe(n,ke)}(t),Be("onerror")),e.onunhandledrejection&&(function(t){var e;Se(e="unhandledrejection",(function(e){var n=Fe(),r=n.stackParser,i=n.attachStacktrace;if(Ot()===t&&!ce()){var o=function(t){if(E(t))return t;var e=t;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch(t){}return t}(e),a=E(o)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(o)}]}}:De(r,o,void 0,i,!0);a.level="error",wt(a,{originalException:o,mechanism:{handled:!1,type:"onunhandledrejection"}})}})),xe(e,Te)}(t),Be("onunhandledrejection"))}}},Ue=Gt(Re,Me);function qe(t,e,n,r){var i=t.exception=t.exception||{},o=i.values=i.values||[],a=o[0]=o[0]||{},s=a.stacktrace=a.stacktrace||{},c=s.frames=s.frames||[],u=isNaN(parseInt(r,10))?void 0:r,f=isNaN(parseInt(n,10))?void 0:n,l=S(e)&&e.length>0?e:function(){try{return C.document.location.href}catch(t){return""}}();return 0===c.length&&c.push({colno:u,filename:l,function:"?",in_app:!0,lineno:f}),t}function Be(t){}function Fe(){var t=Ot();return t&&t.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1}}function He(){"console"in a&&u.forEach((function(t){t in a.console&&R(a.console,t,(function(e){return f[t]=e,function(){for(var e=arguments.length,n=new Array(e),r=0;r2?n[2]:void 0;if(i){var o=on,a=String(i);on=a,Ee("history",{from:o,to:a})}return t.apply(this,n)}}}var un=["fatal","error","warning","log","info","debug"];function fn(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var ln=1024,pn="Breadcrumbs",hn=function(t){void 0===t&&(t={});var e=v({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t);return{name:pn,setupOnce:function(){},setup:function(t){var n;e.console&&(n=function(t){return function(e){if(Ot()===t){var n={category:"console",data:{arguments:e.args,logger:"console"},level:(r=e.level,"warn"===r?"warning":un.includes(r)?r:"log"),message:N(e.args," ")};if("assert"===e.level){if(!1!==e.args[0])return;n.message="Assertion failed: "+(N(e.args.slice(1)," ")||"console.assert"),n.data.arguments=e.args.slice(1)}kt(n,{input:e.args,level:e.level})}var r}}(t),Se("console",n),xe("console",He)),e.dom&&function(t){Se("dom",t),xe("dom",Ge)}(function(t,e){return function(n){if(Ot()===t){var r,i,o="object"==typeof e?e.serializeAttribute:void 0,a="object"==typeof e&&"number"==typeof e.maxStringLength?e.maxStringLength:void 0;a&&a>ln&&(a=ln),"string"==typeof o&&(o=[o]);try{var s=n.event,c=function(t){return!!t&&!!t.target}(s)?s.target:s;r=A(c,{keyAttrs:o,maxStringLength:a}),i=function(t){if(!C.HTMLElement)return null;for(var e=t,n=0;n<5;n++){if(!e)return null;if(e instanceof HTMLElement&&e.dataset.sentryComponent)return e.dataset.sentryComponent;e=e.parentNode}return null}(c)}catch(t){r=""}if(0!==r.length){var u={category:"ui."+n.name,message:r};i&&(u.data={"ui.component_name":i}),kt(u,{event:n.event,name:n.name,global:n.global})}}}}(t,e.dom)),e.xhr&&function(t){Se("xhr",t),xe("xhr",Qe)}(function(t){return function(e){if(Ot()===t){var n=e.startTimestamp,r=e.endTimestamp,i=e.xhr[Xe];if(n&&r&&i){var o=i.method,a=i.url,s=i.status_code,c=i.body;kt({category:"xhr",data:{method:o,url:a,status_code:s},type:"http"},{xhr:e.xhr,input:c,startTimestamp:n,endTimestamp:r})}}}}(t)),e.fetch&&function(t){var e="fetch";Se(e,t),xe(e,en)}(function(t){return function(e){if(Ot()===t){var n=e.startTimestamp,r=e.endTimestamp;if(r&&(!e.fetchData.url.match(/sentry_key/)||"POST"!==e.fetchData.method))if(e.error)kt({category:"fetch",data:e.fetchData,level:"error",type:"http"},{data:e.error,input:e.args,startTimestamp:n,endTimestamp:r});else{var i=e.response;kt({category:"fetch",data:v({},e.fetchData,{status_code:i&&i.status}),type:"http"},{input:e.args,response:i,startTimestamp:n,endTimestamp:r})}}}}(t)),e.history&&function(t){var e="history";Se(e,t),xe(e,cn)}(function(t){return function(e){if(Ot()===t){var n=e.from,r=e.to,i=fn(ae.location.href),o=n?fn(n):void 0,a=fn(r);o&&o.path||(o=i),i.protocol===a.protocol&&i.host===a.host&&(r=a.relative),i.protocol===o.protocol&&i.host===o.host&&(n=o.relative),kt({category:"navigation",data:{from:n,to:r}})}}}(t)),e.sentry&&t.on&&t.on("beforeSendEvent",function(t){return function(e){Ot()===t&&kt({category:"sentry."+("transaction"===e.type?"transaction":"event"),event_id:e.event_id,level:e.level,message:V(e)},{event:e})}}(t))}}},dn=Gt(pn,hn);function vn(t,e,n,r,i,o,a){if(void 0===n&&(n=250),o.exception&&o.exception.values&&a&&T(a.originalException,Error)){var s,c,u=o.exception.values.length>0?o.exception.values[o.exception.values.length-1]:void 0;u&&(o.exception.values=(s=gn(t,e,i,a.originalException,r,o.exception.values,u,0),c=n,s.map((function(t){return t.value&&(t.value=D(t.value,c)),t}))))}}function gn(t,e,n,r,i,o,a,s){if(o.length>=n+1)return o;var c=[].concat(o);if(T(r[i],Error)){_n(a,s);var u=t(e,r[i]),f=c.length;mn(u,i,f,s),c=gn(t,e,n,r[i],i,[u].concat(c),u,f)}return Array.isArray(r.errors)&&r.errors.forEach((function(r,o){if(T(r,Error)){_n(a,s);var u=t(e,r),f=c.length;mn(u,"errors["+o+"]",f,s),c=gn(t,e,n,r,i,[u].concat(c),u,f)}})),c}function _n(t,e){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=v({},t.mechanism,"AggregateError"===t.type&&{is_exception_group:!0},{exception_id:e})}function mn(t,e,n,r){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=v({},t.mechanism,{type:"chained",source:e,exception_id:n,parent_id:r})}var yn="LinkedErrors",bn=function(t){void 0===t&&(t={});var e=t.limit||5,n=t.key||"cause";return{name:yn,setupOnce:function(){},preprocessEvent:function(t,r,i){var o=i.getOptions();vn(je,o.stackParser,o.maxValueLength,n,e,t,r)}}},Sn=Gt(yn,bn),xn="HttpContext",En=function(){return{name:xn,setupOnce:function(){},preprocessEvent:function(t){if(ae.navigator||ae.location||ae.document){var e=t.request&&t.request.url||ae.location&&ae.location.href,n=(ae.document||{}).referrer,r=(ae.navigator||{}).userAgent,i=v({},t.request&&t.request.headers,n&&{Referer:n},r&&{"User-Agent":r}),o=v({},t.request,e&&{url:e},{headers:i});t.request=o}}}},wn=Gt(xn,En);function kn(t,e){return kn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},kn(t,e)}function On(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,kn(t,e)}var Tn=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function jn(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,o=t.port,a=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(o?":"+o:"")+"/"+(r?r+"/":r)+a}function Cn(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function In(t){var e="string"==typeof t?function(t){var e=Tn.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],o=n[2],a=void 0===o?"":o,s=n[3],c=n[4],u=void 0===c?"":c,f="",p=n[5],h=p.split("/");if(h.length>1&&(f=h.slice(0,-1).join("/"),p=h.pop()),p){var d=p.match(/^\d+/);d&&(p=d[0])}return Cn({host:s,pass:a,path:f,projectId:p,port:u,protocol:r,publicKey:i})}l((function(){console.error("Invalid Sentry Dsn: "+t)}))}(t):Cn(t);if(e&&function(t){if(!i)return!0;var e=t.port,n=t.projectId,r=t.protocol;return!(["protocol","publicKey","host","projectId"].find((function(e){return!t[e]&&(d.error("Invalid Sentry Dsn: "+e+" missing"),!0)}))||(n.match(/^\d+$/)?function(t){return"http"===t||"https"===t}(r)?e&&isNaN(parseInt(e,10))&&(d.error("Invalid Sentry Dsn: Invalid port "+e),1):(d.error("Invalid Sentry Dsn: Invalid protocol "+r),1):(d.error("Invalid Sentry Dsn: Invalid projectId "+n),1)))}(e))return e}function An(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Pn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Pn(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Pn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(t);!(e=r()).done;){var i=e.value,o=Object.entries(i.tags),a=o.length>0?"|#"+o.map((function(t){return t[0]+":"+t[1]})).join(","):"";n+=i.name+"@"+i.unit+":"+i.metric+"|"+i.metricType+a+"|T"+i.timestamp+"\n"}return n}(t);return[{type:"statsd",length:e.length},e]}(t);return Dn(i,[o])}function Kn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Xn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xn(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Xn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?" ("+r+" times)":"")),this._outcomes[i]=(this._outcomes[i]||0)+r}},e.captureAggregateMetrics=function(t){Q&&d.log("Flushing aggregated metrics, number of metrics: "+t.length);var e=Wn(t,this._dsn,this._options._metadata,this._options.tunnel);this._sendEnvelope(e)},e.on=function(t,e){this._hooks[t]||(this._hooks[t]=[]),this._hooks[t].push(e)},e.emit=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},e._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._transport},e._prepareEvent=function(t,e,n,r){var i=this;void 0===r&&(r=Ft().getIsolationScope());var o=this.getOptions(),s=Object.keys(this._integrations);return!e.integrations&&s.length>0&&(e.integrations=s),this.emit("preprocessEvent",t,e),function(t,e,n,r,i,o){var s=t.normalizeDepth,c=void 0===s?3:s,u=t.normalizeMaxBreadth,f=void 0===u?1e3:u,l=v({},e,{event_id:e.event_id||n.event_id||J(),timestamp:e.timestamp||at()}),p=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,o=e.maxValueLength,a=void 0===o?250:o;"environment"in t||(t.environment="environment"in e?n:ct),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=D(t.message,a));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=D(s.value,a));var c=t.request;c&&c.url&&(c.url=D(c.url,a))}(l,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(l,p),void 0===e.type&&function(t,e){var n,r=a._sentryDebugIds;if(r){var i=xt.get(e);i?n=i:(n=new Map,xt.set(e,n));var o=Object.keys(r).reduce((function(t,i){var o,a=n.get(i);a?o=a:(o=e(i),n.set(i,o));for(var s=o.length-1;s>=0;s--){var c=o[s];if(c.filename){t[c.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=o[t.filename])}))}))}catch(t){}}}(l,t.stackParser);var h=function(t,e){if(!e)return t;var n=t?t.clone():new Nt;return n.update(e),n}(r,n.captureContext);n.mechanism&&W(l,n.mechanism);var d=i&&i.getEventProcessors?i.getEventProcessors():[],g=(Dt||(Dt=new Nt),Dt).getScopeData();o&&At(g,o.getScopeData()),h&&At(g,h.getScopeData());var _=[].concat(n.attachments||[],g.attachments);return _.length&&(n.attachments=_),It(l,g),it([].concat(d,nt(),g.eventProcessors),l,n).then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof c&&c>0?function(t,e,n){if(!t)return null;var r=v({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return v({},t,t.data&&{data:gt(t.data,e,n)})}))},t.user&&{user:gt(t.user,e,n)},t.contexts&&{contexts:gt(t.contexts,e,n)},t.extra&&{extra:gt(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=gt(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){var r=St(t).data;return r&&(t.data=gt(r,e,n)),t}))),r}(t,c,f):t}))}(o,t,e,n,this,r).then((function(t){if(null===t)return t;var e=v({},r.getPropagationContext(),n?n.getPropagationContext():void 0);if((!t.contexts||!t.contexts.trace)&&e){var o=e.traceId,a=e.spanId,s=e.parentSpanId,c=e.dsc;t.contexts=v({trace:{trace_id:o,span_id:a,parent_span_id:s}},t.contexts);var u=c||jt(o,i,n);t.sdkProcessingMetadata=v({dynamicSamplingContext:u},t.sdkProcessingMetadata)}return t}))},e._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){if(Q){var e=t;"log"===e.logLevel?d.log(e.message):d.warn(e)}}))},e._processEvent=function(t,e,n){var r=this,i=this.getOptions(),o=i.sampleRate,a=er(t),s=tr(t),c=t.type||"error",u="before send for type `"+c+"`";if(s&&"number"==typeof o&&Math.random()>o)return this.recordDroppedEvent("sample_rate","error",t),tt(new $n("Discarding event because it's not included in the random sample (sampling rate = "+o+")","log"));var f="replay_event"===c?"replay":c,l=(t.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(t,e,n,l).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",f,t),new $n("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var o=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;if(tr(e)&&r)return r(e,n);if(er(e)&&i){if(e.spans){var o=e.spans.length;e.sdkProcessingMetadata=v({},e.sdkProcessingMetadata,{spanCountBeforeProcessing:o})}return i(e,n)}return e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(O(t))return t.then((function(t){if(!w(t)&&null!==t)throw new $n(n);return t}),(function(t){throw new $n(e+" rejected with "+t)}));if(!w(t)&&null!==t)throw new $n(n);return t}(o,u)})).then((function(i){if(null===i){if(r.recordDroppedEvent("before_send",f,t),a){var o=1+(t.spans||[]).length;r.recordDroppedEvent("before_send","span",o)}throw new $n(u+" returned `null`, will not send event.","log")}var s=n&&n.getSession();if(!a&&s&&r._updateSessionFromEvent(s,i),a){var c=(i.sdkProcessingMetadata&&i.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);c>0&&r.recordDroppedEvent("before_send","span",c)}var l=i.transaction_info;return a&&l&&i.transaction!==t.transaction&&(i.transaction_info=v({},l,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof $n)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new $n("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},e._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},e._sendEnvelope=function(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)return this._transport.send(t).then(null,(function(t){Q&&d.error("Error while sending event:",t)}));Q&&d.error("Transport disabled")},e._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},t}();function tr(t){return void 0===t.type}function er(t){return"transaction"===t.type}var nr=function(t){function e(e){var n;return function(t,e,n,r){void 0===n&&(n=[e]),void 0===r&&(r="npm");var i=t._metadata||{};i.sdk||(i.sdk={name:"sentry.javascript."+e,packages:n.map((function(t){return{name:r+":@sentry/"+t,version:Rt}})),version:Rt}),t._metadata=i}(e,"browser",["browser"],ae.SENTRY_SDK_SOURCE||"npm"),n=t.call(this,e)||this,e.sendClientReports&&ae.document&&ae.document.addEventListener("visibilitychange",(function(){"hidden"===ae.document.visibilityState&&n._flushOutcomes()})),n}On(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=De(t,e,n&&n.syntheticException||void 0,r);return W(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),Z(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var o=Ne(t,e,r&&r.syntheticException||void 0,i);return o.level=n,r&&r.event_id&&(o.event_id=r.event_id),Z(o)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,o=v({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:jn(i)}),a=function(t){return[{type:"user_report"},t]}(t);return Dn(o,[a])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,Dn((n=this._options.tunnel&&jn(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:at(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(Zn);function rr(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return ir(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ir(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function ir(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){Z(t).then((function(){--i||(clearTimeout(o),n(!0))}),r)}))}))}}}(t.bufferSize||ar));var r={};function i(i){var o=[];if(Nn(i,(function(e,n){var i=qn(n);if(function(t,e,n){return void 0===n&&(n=Date.now()),function(t,e){return t[e]||t.all||0}(t,e)>n}(r,i)){var a=cr(e,n);t.recordDroppedEvent("ratelimit_backoff",i,a)}else o.push(e)})),0===o.length)return Z();var a=Dn(i[0],o),s=function(e){Nn(a,(function(n,r){var i=cr(n,r);t.recordDroppedEvent(e,qn(r),i)}))};return n.add((function(){return e({body:Rn(a,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&Q&&d.warn("Sentry responded with status code "+t.statusCode+" to sent event."),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var o=v({},t),a=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(a)for(var c,u=rr(a.trim().split(","));!(c=u()).done;){var f=c.value.split(":",5),l=f[0],p=f[1],h=f[4],d=parseInt(l,10),g=1e3*(isNaN(d)?60:d);if(p)for(var _,m=rr(p.split(";"));!(_=m()).done;){var y=_.value;"metric_bucket"===y&&h&&!h.split(";").includes("custom")||(o[y]=n+g)}else o.all=n+g}else s?o.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?or:r-e}(s,n):429===r&&(o.all=n+6e4);return o}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof $n)return Q&&d.error("Skipped sending event because buffer is full."),s("queue_overflow"),Z();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function cr(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var ur=void 0;function fr(t,e){void 0===e&&(e=function(){if(ur)return ur;if(tn(ae.fetch))return ur=ae.fetch.bind(ae);var t=ae.document,e=ae.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return ur=e.bind(ae)}());var n=0,r=0;return sr(t,(function(i){var o=i.body.length;n+=o,r++;var a=v({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,a).then((function(t){return n-=o,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return ur=void 0,n-=o,r--,tt(t)}}))}var lr="?";function pr(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var hr=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dr=/\((\S*)(?::(\d+))(?::(\d+))\)/,vr=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,gr=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,_r=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,mr=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=pt.test(a)?a.replace(pt,"$1"):a;if(!s.match(/\S*Error: /)){for(var c,u=ft(r);!(c=u()).done;){var f=(0,c.value)(s);if(f){n.push(f);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=Array.from(t);return/sentryWrapped/.test(e[e.length-1].function||"")&&e.pop(),e.reverse(),ht.test(e[e.length-1].function||"")&&(e.pop(),ht.test(e[e.length-1].function||"")&&e.pop()),e.slice(0,50).map((function(t){return v({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=hr.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=dr.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=yr(e[1]||lr,e[2]),i=r[0];return pr(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=vr.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=gr.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||lr,o=yr(i,r);return i=o[0],pr(r=o[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=_r.exec(t);return e?pr(e[2],e[1]||lr,+e[3],e[4]?+e[4]:void 0):void 0}]]),yr=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:lr,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},br="Dedupe",Sr=function(){var t;return{name:br,setupOnce:function(){},processEvent:function(e){if(e.type)return e;try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!Er(t,e)&&!!xr(t,e))))}(t,e)||!!function(t,e){var n=wr(e),r=wr(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!Er(t,e)&&!!xr(t,e)))}(t,e))}(e,t))return null}catch(t){}return t=e}}};function xr(t,e){var n=kr(t),r=kr(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i>t/4).toString(16)}))}function Nr(){return Date.now()/1e3}var Lr=function(){var t=Ar.performance;if(!t||!t.now)return Nr;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/1e3}}(),Rr=(function(){var t=Ar.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function Gr(t){return t.transaction}var Wr=1;function Kr(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=Xr(t);return Jr({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function Xr(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function Qr(t){var e=fi();if(!e)return{};var n=function(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=Jr({environment:r.environment||Hr,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}(Xr(t).trace_id||"",e,oi().getScope()),r=Gr(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=Xr(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&Wr)}(r)),e.emit&&e.emit("createDsc",n),n}var Zr=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=ti()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=v({},this._tags),e._extra=v({},this._extra),e._contexts=v({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=v({},this._sdkProcessingMetadata),e._propagationContext=v({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&Vr(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=v({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=v({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=v({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=v({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=v({},this._tags,r.tags),this._extra=v({},this._extra,r.extra),this._contexts=v({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(jr(n)){var i=e;this._tags=v({},this._tags,i.tags),this._extra=v({},this._extra,i.extra),this._contexts=v({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=ti(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=v({timestamp:Nr()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),function(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=Jr(n);c&&Object.keys(c).length&&(t.extra=v({},c,t.extra));var u=Jr(r);u&&Object.keys(u).length&&(t.tags=v({},u,t.tags));var f=Jr(i);f&&Object.keys(f).length&&(t.user=v({},f,t.user));var l=Jr(o);l&&Object.keys(l).length&&(t.contexts=v({},l,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=v({trace:Kr(e)},t.contexts);var n=Gr(e);if(n){t.sdkProcessingMetadata=v({dynamicSamplingContext:Qr(e)},t.sdkProcessingMetadata);var r=Xr(n).description;r&&(t.tags=v({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=v({},t.sdkProcessingMetadata,e)}(t,o)}(t,this.getScopeData()),$r([].concat(n,Pr("globalEventProcessors",(function(){return[]})),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=v({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:Dr();if(!this._client)return Fr.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,v({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:Dr();if(!this._client)return Fr.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,v({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:Dr();return this._client?(this._client.captureEvent(t,v({},e,{event_id:n}),this),n):(Fr.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function ti(){return{traceId:Dr(),spanId:Dr().substring(16)}}var ei=parseFloat("7.119.1"),ni=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=ei),this._version=r,e?i=e:(i=new Zr).setClient(t),n?o=n:(o=new Zr).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){Rr&&Fr.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+pi(o)+"\nError:",e)}}}("console",{args:n,level:t});var i=Ur[t];i&&i.apply(Ar.console,n)}}))}))}var _i=["fatal","error","warning","log","info","debug"];function mi(t){return"warn"===t?"warning":_i.includes(t)?t:"log"}function yi(t,e){if(!Array.isArray(t))return"";for(var n,r=[],i=0;i(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","import { dynamicRequire, isNodeEnv } from './node';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance(): Performance | undefined {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = (module) => {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: () => {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n","import { isRegExp, isString } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","import type { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*healthcheck.*$/,\n /^.*healthy.*$/,\n /^.*live.*$/,\n /^.*ready.*$/,\n /^.*heartbeat.*$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcess: EventProcessor = (event: Event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n}\n\n/** JSDoc */\nexport function _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nexport function _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n __DEBUG_BUILD__ &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n const { values } = event.exception;\n try {\n const { type = '', value = '' } = (values && values[values.length - 1]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n }\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: { [key: string]: unknown }, name: string, value: unknown): void {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(value: V):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { node } from './node-stack-trace';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = stack.slice(0, STACKTRACE_FRAME_LIMIT);\n\n const lastFrameFunction = localStack[localStack.length - 1].function;\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (lastFrameFunction && /sentryWrapped/.test(lastFrameFunction)) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n const firstFrameFunction = localStack[localStack.length - 1].function;\n // 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)\n if (firstFrameFunction && /captureMessage|captureException/.test(firstFrameFunction)) {\n localStack.pop();\n }\n\n return localStack.map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n const getRandomByte =\n crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","import type { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalSingleton, GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] as const;\nexport type ConsoleLevel = (typeof CONSOLE_LEVELS)[number];\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record<(typeof CONSOLE_LEVELS)[number], LoggerMethod>;\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const originalConsole = GLOBAL_OBJ.console as Console & Record;\n const wrappedLevels: Partial = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] as WrappedFunction).__sentry_original__;\n if (level in originalConsole && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] as LoggerConsoleMethods[typeof level];\n originalConsole[level] = originalWrappedFunc as Console[typeof level];\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level as (typeof CONSOLE_LEVELS)[number]];\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if (__DEBUG_BUILD__) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nlet logger: Logger;\nif (__DEBUG_BUILD__) {\n logger = getGlobalSingleton('logger', makeLogger);\n} else {\n logger = makeLogger();\n}\n\nexport { logger };\n","export const DEFAULT_ENVIRONMENT = 'production';\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States = States.PENDING;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]> = [];\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport {\n arrayify,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isPlainObject,\n isThenable,\n logger,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { updateSession } from './session';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /** Transaction Name */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n this._user = user || {};\n if (this._session) {\n updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as (scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getAttachments(): Attachment[] {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n public applyToEvent(event: Event, hint: EventHint = {}): PromiseLike {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transaction = this._span.transaction;\n if (transaction) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: transaction.getDynamicSamplingContext(),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n __DEBUG_BUILD__ &&\n processor.id &&\n result === null &&\n logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalSingleton, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this._stack = [{ scope }];\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n this.getScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n this.getScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n this.getScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n this.getScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n this.getScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n this.getScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (__DEBUG_BUILD__ && !result) {\n // eslint-disable-next-line no-console\n console.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n public shouldSendDefaultPii(): boolean {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n private _withClient(callback: (client: Client, scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n __DEBUG_BUILD__ && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(carrier) || getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {\n const globalHubTopStack = parent.getStackTop();\n setHubOnCarrier(carrier, new Hub(globalHubTopStack.client, Scope.clone(globalHubTopStack.scope)));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope: Scope) => {\n scope.addEventProcessor((event: SentryEvent) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n}\n","import type {\n Breadcrumb,\n CaptureContext,\n CheckIn,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n MonitorConfig,\n Primitive,\n Severity,\n SeverityLevel,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { logger, uuid4 } from '@sentry/utils';\n\nimport type { Hub } from './hub';\nimport { getCurrentHub } from './hub';\nimport type { Scope } from './scope';\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): ReturnType {\n return getCurrentHub().captureException(exception, { captureContext });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): ReturnType {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event, hint?: EventHint): ReturnType {\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb): ReturnType {\n getCurrentHub().addBreadcrumb(breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): ReturnType {\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): ReturnType {\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): ReturnType {\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): ReturnType {\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): ReturnType {\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const client = getCurrentHub().getClient();\n if (!client) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig);\n }\n\n return uuid4();\n}\n","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\n/** JSDoc */\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nexport class TryCatch implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'TryCatch';\n\n /**\n * @inheritDoc\n */\n public name: string = TryCatch.id;\n\n /** JSDoc */\n private readonly _options: TryCatchOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n public setupOnce(): void {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n}\n\n/** JSDoc */\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: () => void): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type {\n HandlerDataFetch,\n HandlerDataXhr,\n SentryWrappedXMLHttpRequest,\n SentryXhrData,\n WrappedFunction,\n} from '@sentry/types';\n\nimport { isString } from './is';\nimport { CONSOLE_LEVELS, logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v2__';\n\nexport type InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n __DEBUG_BUILD__ && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in WINDOW)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: string): void {\n if (!(level in WINDOW.console)) {\n return;\n }\n\n fill(WINDOW.console, level, function (originalConsoleMethod: () => any): Function {\n return function (...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(WINDOW.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(WINDOW, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(WINDOW, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in WINDOW)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const url = args[1];\n const xhrInfo: SentryXhrData = (this[SENTRY_XHR_DATA_KEY] = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n request_headers: {},\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args: args as [string, string],\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr: this,\n } as HandlerDataXhr);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs as [string, string];\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n if (sentryXhrData && args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in WINDOW)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler: (typeof WINDOW)['onerror'] | null = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n WINDOW.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nlet _oldOnUnhandledRejectionHandler: (typeof WINDOW)['onunhandledrejection'] | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n WINDOW.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n// TODO remove this in v7 (this means the method will no longer be exported, under any name)\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, Severity, SeverityLevel, StackFrame, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n isUnhandledRejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception as DOMError) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n input: string,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\n return event;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Hub, Integration, Primitive, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\n/** JSDoc */\ntype GlobalHandlersIntegrations = Record;\n\n/** Global handlers */\nexport class GlobalHandlers implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GlobalHandlers';\n\n /**\n * @inheritDoc\n */\n public name: string = GlobalHandlers.id;\n\n /** JSDoc */\n private readonly _options: GlobalHandlersIntegrations;\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n private _installFunc: Record void) | undefined> = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n\n /** JSDoc */\n public constructor(options?: GlobalHandlersIntegrations) {\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key as GlobalHandlersIntegrationsOptionKeys];\n if (installFunc && options[key as GlobalHandlersIntegrationsOptionKeys]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key as GlobalHandlersIntegrationsOptionKeys] = undefined;\n }\n }\n }\n}\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler(): void {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler(): void {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e: any) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n __DEBUG_BUILD__ && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions(): [Hub, StackParser, boolean | undefined] {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n .replace(':80', '')\n .replace(':443', '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable max-lines */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event as SentryEvent, HandlerDataFetch, HandlerDataXhr, Integration } from '@sentry/types';\nimport type {\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n addInstrumentationHandler,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n SENTRY_XHR_DATA_KEY,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\ntype HandlerData = Record;\n\n/** JSDoc */\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nexport const BREADCRUMB_INTEGRATION_ID = 'Breadcrumbs';\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nexport class Breadcrumbs implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = BREADCRUMB_INTEGRATION_ID;\n\n /**\n * @inheritDoc\n */\n public name: string = Breadcrumbs.id;\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n public readonly options: Readonly;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n public setupOnce(): void {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n\n /**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\n public addSentryBreadcrumb(event: SentryEvent): void {\n if (this.options.sentry) {\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n }\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerData) => void {\n function _innerDomBreadcrumb(handlerData: HandlerData): void {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n target = _isEvent(event)\n ? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })\n : htmlTreeAsString(event, { keyAttrs, maxStringLength });\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _consoleBreadcrumb(handlerData: HandlerData & { args: unknown[]; level: string }): void {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/6010\n // see: https://github.com/getsentry/sentry-javascript/issues/5916\n for (let i = 0; i < handlerData.args.length; i++) {\n if (handlerData.args[i] === 'ref=Ref<') {\n handlerData.args[i + 1] = 'viewRef';\n break;\n }\n }\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _xhrBreadcrumb(handlerData: HandlerData & HandlerDataXhr): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _fetchBreadcrumb(handlerData: HandlerData & HandlerDataFetch & { response?: Response }): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: handlerData.response && handlerData.response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp,\n endTimestamp,\n };\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _historyBreadcrumb(handlerData: HandlerData & { from: string; to: string }): void {\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return event && !!(event as Record).target;\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, ExtendedError, Integration, StackParser } from '@sentry/types';\nimport { isInstanceOf } from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { exceptionFromError } from '../eventbuilder';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\ninterface LinkedErrorsOptions {\n key: string;\n limit: number;\n}\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: LinkedErrorsOptions['key'];\n\n /**\n * @inheritDoc\n */\n private readonly _limit: LinkedErrorsOptions['limit'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: Partial = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n const client = getCurrentHub().getClient();\n if (!client) {\n return;\n }\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(client.getOptions().stackParser, self._key, self._limit, event, hint) : event;\n });\n }\n}\n\n/**\n * @inheritDoc\n */\nexport function _handler(\n parser: StackParser,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): Event | null {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(parser, limit, hint.originalException as ExtendedError, key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nexport function _walkErrorTree(\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n stack: Exception[] = [],\n): Exception[] {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(parser, error[key]);\n return _walkErrorTree(parser, limit, error[key], key, [exception, ...stack]);\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, Integration } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\n/** HttpContext integration collects information about HTTP request headers */\nexport class HttpContext implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'HttpContext';\n\n /**\n * @inheritDoc\n */\n public name: string = HttpContext.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n if (getCurrentHub().getIntegration(HttpContext)) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n}\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export const SDK_VERSION = '7.56.0';\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!__DEBUG_BUILD__) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","import type { ConsoleLevel } from './logger';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { Integration, Options } from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\nimport { addGlobalEventProcessor } from './scope';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(integration: Integration, integrationIndex: IntegrationIndex): void {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n __DEBUG_BUILD__ && logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n","import type { ClientOptions, Event, EventHint, StackFrame, StackParser } from '@sentry/types';\nimport { dateTimestampInSeconds, GLOBAL_OBJ, normalize, resolvedSyncPromise, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { Scope } from '../scope';\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n Integration,\n IntegrationClass,\n Outcome,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n SentryError,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport type { IntegrationIndex } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean = false;\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number } = {};\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record = {};\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n __DEBUG_BUILD__ && logger.warn('No DSN provided, client will not do anything.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n __DEBUG_BUILD__ && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n setupIntegration(integration, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n if (this._dsn) {\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n if (this._dsn) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n void this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, _event?: Event): void {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n __DEBUG_BUILD__ && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n\n /** @inheritdoc */\n public on(hook: 'startTransaction' | 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-ignore We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction' | 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n // @ts-ignore we cannot enforce the callback to match the hook\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent(options, event, hint, scope);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (__DEBUG_BUILD__) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n if (this._transport && this._dsn) {\n this.emit('beforeEnvelope', envelope);\n\n return this._transport.send(envelope).then(null, reason => {\n __DEBUG_BUILD__ && logger.error('Error while sending event:', reason);\n });\n } else {\n __DEBUG_BUILD__ && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: string,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n","import type { Scope } from '@sentry/core';\nimport { BaseClient, SDK_VERSION } from '@sentry/core';\nimport type {\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { Breadcrumbs } from './integrations';\nimport { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options & BrowserClientReplayOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint?: EventHint): void {\n // We only want to add the sentry event breadcrumb when the user has the breadcrumb integration installed and\n // activated its `sentry` option.\n // We also do not want to use the `Breadcrumbs` class here directly, because we do not want it to be included in\n // bundles, if it is not used by the SDK.\n // This all sadly is a bit ugly, but we currently don't have a \"pre-send\" hook on the integrations so we do it this\n // way for now.\n const breadcrumbIntegration = this.getIntegrationById(BREADCRUMB_INTEGRATION_ID) as Breadcrumbs | undefined;\n // We check for definedness of `addSentryBreadcrumb` in case users provided their own integration with id\n // \"Breadcrumbs\" that does not have this function.\n if (breadcrumbIntegration && breadcrumbIntegration.addSentryBreadcrumb) {\n breadcrumbIntegration.addSentryBreadcrumb(event);\n }\n\n super.sendEvent(event, hint);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n void this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n __DEBUG_BUILD__ && logger.log('No outcomes to send');\n return;\n }\n\n if (!this._dsn) {\n __DEBUG_BUILD__ && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n void this._sendEnvelope(envelope);\n }\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type { TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, category: string): number {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, category: string, now: number = Date.now()): boolean {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n SentryError,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n __DEBUG_BUILD__ && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n __DEBUG_BUILD__ && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import type { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcessor: EventProcessor = currentEvent => {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n __DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport {\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n Integrations as CoreIntegrations,\n} from '@sentry/core';\nimport type { UserFeedback } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n logger,\n resolvedSyncPromise,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, HttpContext, LinkedErrors, TryCatch } from './integrations';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\nexport const defaultIntegrations = [\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\n];\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nexport function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n __DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n __DEBUG_BUILD__ && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n __DEBUG_BUILD__ && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function flush(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function close(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\nfunction startSessionOnHub(hub: Hub): void {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n __DEBUG_BUILD__ &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getCurrentHub().getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import type { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { CONSOLE_LEVELS, fill, GLOBAL_OBJ, safeJoin, severityLevelFromString } from '@sentry/utils';\n\n/** Send Console API calls as Sentry Events */\nexport class CaptureConsole implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'CaptureConsole';\n\n /**\n * @inheritDoc\n */\n public name: string = CaptureConsole.id;\n\n /**\n * @inheritDoc\n */\n private readonly _levels: readonly string[] = CONSOLE_LEVELS;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { levels?: string[] } = {}) {\n if (options.levels) {\n this._levels = options.levels;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n this._levels.forEach((level: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if (!(level in (GLOBAL_OBJ as any).console)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n fill((GLOBAL_OBJ as any).console, level, (originalConsoleMethod: () => any) => (...args: any[]): void => {\n const hub = getCurrentHub();\n\n if (hub.getIntegration(CaptureConsole)) {\n hub.withScope(scope => {\n scope.setLevel(severityLevelFromString(level));\n scope.setExtra('arguments', args);\n scope.addEventProcessor(event => {\n event.logger = 'console';\n return event;\n });\n\n let message = safeJoin(args, ' ');\n if (level === 'assert') {\n if (args[0] === false) {\n message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n hub.captureMessage(message);\n }\n } else if (level === 'error' && args[0] instanceof Error) {\n hub.captureException(args[0]);\n } else {\n hub.captureMessage(message);\n }\n });\n }\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(GLOBAL_OBJ.console, args);\n }\n });\n });\n }\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["isBrowserBundle","__SENTRY_BROWSER_BUNDLE__","getSDKSource","isNodeEnv","Object","prototype","toString","call","process","dynamicRequire","mod","request","require","WINDOW","getGlobalObject","dateTimestampSource","nowSeconds","Date","now","platformPerformance","module","performance","_","getNodePerformance","timeOrigin","getBrowserPerformance","timestampSource","undefined","dateTimestampInSeconds","bind","timestampInSeconds","threshold","performanceNow","dateNow","timeOriginDelta","Math","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","isGlobalObj","obj","GLOBAL_OBJ","globalThis","window","self","global","getGlobalSingleton","name","creator","gbl","__SENTRY__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","id","loaded","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","defineProperty","enumerable","get","g","this","Function","e","hmd","create","children","set","Error","prop","hasOwnProperty","r","Symbol","toStringTag","value","flarum","core","compat","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","then","base","_e","truncate","str","max","length","slice","safeJoin","input","delimiter","Array","isArray","output","i","push","String","join","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","InboundFilters","__initStatic","_proto","_options","__init","setupOnce","addGlobalEventProcessor","getCurrentHub","eventProcess","event","hub","getIntegration","client","getClient","clientOptions","getOptions","options","internalOptions","allowUrls","concat","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","exception","values","type","_isSentryError","message","_ref","_ref$type","_ref$value","oO","_getPossibleEventMessages","_isIgnoredError","transaction","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","frames","stacktrace","frame","filename","_getLastValidUrl","_extends","assign","target","arguments","source","apply","originalFunctionToString","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","nextStr","currentElem","out","height","len","keyAttrs","maxStringLength","_htmlElementAsString","separator","parentNode","reverse","_oO","el","classes","attr","tagName","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","forEach","keyAttrPair","split","allowedAttrs","fill","replacementFactory","original","wrapped","markFunctionWrapped","_Oo","addNonEnumerableProperty","writable","configurable","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","extractExceptionKeysForMessage","maxLength","keys","sort","includedKeys","serialized","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","memoVal","returnValue","_i","_Object$keys","item","FunctionToString","context","_len","args","_key","WEBPACK_ERROR_REGEXP","defaultFunctionName","getFunctionName","fn","uuid4","crypto","msCrypto","randomUUID","replace","getRandomByte","getRandomValues","Uint8Array","random","c","getFirstException","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","err","logger","CONSOLE_LEVELS","enable","disable","States","DEFAULT_ENVIRONMENT","resolvedSyncPromise","SyncPromise","resolve","rejectedSyncPromise","reason","reject","executor","__init2","__init3","__init4","__init5","__init6","_resolve","_reject","_state","PENDING","_handlers","onfulfilled","onrejected","_this","result","_executeHandlers","val","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","state","_value","_this6","cachedHandlers","handler","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","clone","scope","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","addScopeListener","callback","addEventProcessor","setUser","_notifyScopeListeners","getUser","getRequestSession","setRequestSession","requestSession","setTags","tags","setTag","_extends2","setExtras","extras","setExtra","extra","_extends3","setFingerprint","fingerprint","setLevel","level","setTransactionName","setContext","setSpan","span","getSpan","getTransaction","setSession","getSession","update","captureContext","updatedScope","contexts","clear","addBreadcrumb","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","hint","trace","getTraceContext","sdkProcessingMetadata","dynamicSamplingContext","getDynamicSamplingContext","transactionName","_applyFingerprint","breadcrumbs","_notifyEventProcessors","getGlobalEventProcessors","setSDKProcessingMetadata","newData","processors","index","processor","final","maybeArray","API_VERSION","Hub","_version","_stack","bindClient","isOlderThan","version","getStackTop","setupIntegrations","pushScope","getScope","getStack","popScope","pop","withScope","captureException","_lastEventId","syntheticException","_withClient","originalException","captureMessage","captureEvent","lastEventId","_this$getStackTop","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","originalConsole","console","wrappedLevels","originalWrappedFunc","consoleSandbox","emit","configureScope","_this$getStackTop2","run","oldHub","makeMain","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2","_ref2$environment","navigator","startingTime","toJSON","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","_this$getStackTop5","method","sentry","getMainCarrier","extensions","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","ignoreOnError","shouldIgnoreOnError","wrap","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","arg","ex","setTimeout","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","TryCatch","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","originalCallback","originalSend","xhr","wrapOptions","originalFunction","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","isNativeFetch","lastHref","SENTRY_XHR_DATA_KEY","handlers","instrumented","instrument","originalConsoleMethod","triggerHandlers","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","document","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","instrumentDOM","xhrproto","originalOpen","_len3","_key3","xhrInfo","toUpperCase","request_headers","match","__sentry_own_request__","onreadystatechangeHandler","readyState","status_code","endTimestamp","startTimestamp","onreadystatechange","_len4","readyStateArgs","_key4","_len5","setRequestHeaderArgs","_key5","header","sentryXhrData","_len6","_key6","body","instrumentXHR","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","error","chrome","isChromePackagedApp","app","runtime","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","location","href","from","_len7","_key7","historyReplacementFunction","originalHistoryFunction","_len8","_key8","instrumentHistory","_oldOnErrorHandler","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","onunhandledrejection","addInstrumentationHandler","_step","_iterator","_createForOfIteratorHelperLoose","done","resource","debounceTimerID","lastCapturedEvent","debounceDuration","globalListener","isContentEditable","shouldSkipDOMEvent","previous","current","shouldShortcircuitPreviousDebounce","clearTimeout","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","object","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","isSyntheticEvent","objName","getPrototypeOf","constructor","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","numAdded","visitable","visitKey","visitValue","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","__serialized__","eventFromPlainObject","synthetic","GlobalHandlers","_installFunc","_installGlobalOnErrorHandler","_installGlobalOnUnhandledRejectionHandler","stackTraceLimit","installFunc","_getHubAndOptions","getHubAndOptions","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","addMechanismAndCapture","_getHubAndOptions2","ev","ev0","ev0s","ev0sf","colno","isNaN","parseInt","lineno","getLocationHref","in_app","validSeverityLevels","severityLevelFromString","parseUrl","query","fragment","host","path","protocol","search","hash","relative","BREADCRUMB_INTEGRATION_ID","Breadcrumbs","dom","_consoleBreadcrumb","serializeAttribute","_isEvent","category","_xhrBreadcrumb","_fetchBreadcrumb","_historyBreadcrumb","addSentryBreadcrumb","parsedLoc","parsedFrom","parsedTo","LinkedErrors","_limit","limit","parser","linkedErrors","_walkErrorTree","_handler","HttpContext","referrer","headers","Referer","_setPrototypeOf","p","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","SDK_VERSION","DSN_REGEX","dsnToString","dsn","withPassword","pass","port","projectId","publicKey","dsnFromComponents","components","makeDsn","exec","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","createEnvelope","items","forEachEnvelopeItem","envelope","envelopeItem","encodeUTF8","textEncoder","TextEncoder","encode","serializeEnvelope","envHeaders","parts","append","next","_step2","_iterator2","itemHeaders","payload","stringifiedPayload","buffers","_step3","totalLength","reduce","acc","buf","merged","offset","_iterator3","buffer","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","sdk","_metadataOrEvent$sdk","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","indexOf","TypeError","Wrapper","SentryError","_Error","logLevel","ReferenceError","_assertThisInitialized","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","tunnel","sdkInfo","_metadata","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","encodeURIComponent","_encodedAuth","installedIntegrations","setupIntegration","integrationIndex","debugIdStackParserCache","WeakMap","BaseClient","_dsn","_transport","transport","recordDroppedEvent","transportOptions","_integrations","_integrationsInitialized","_numProcessing","_outcomes","_hooks","_process","eventFromException","_captureEvent","promisedEvent","eventFromMessage","_isEnabled","sendSession","getDsn","getSdkMetadata","getTransport","flush","timeout","_isClientDoneProcessing","clientFinished","transportFlushed","close","enabled","integrations","getIntegrationById","integrationId","addIntegration","sendEvent","newItem","env","metadata","eventType","packages","enhanceEventWithSdkInfo","envelopeHeaders","sent_at","createEventEnvelopeHeaders","createEventEnvelope","attachments","promise","_sendEnvelope","sendResponse","createSessionEnvelope","_event","sendClientReports","on","hook","rest","_updateSessionFromEvent","crashed","errored","exceptions","sessionNonTerminal","Number","ticked","interval","clearInterval","_prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","dist","_options$maxValueLeng","maxValueLength","applyClientOptions","integrationNames","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","filenameDebugIdMap","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","b","spans","normalizeEvent","prepareEvent","_processEvent","finalEvent","sampleRate","isTransaction","isTransactionEvent","beforeSendLabel","dataCategory","__sentry__","beforeSend","beforeSendTransaction","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","transactionInfo","transaction_info","_this7","send","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","sdkSource","SENTRY_SDK_SOURCE","visibilityState","_flushOutcomes","breadcrumbIntegration","captureUserFeedback","feedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","platform","discarded_events","DEFAULT_RETRY_AFTER","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","remove","task","$","taskProducer","drain","counter","capturedSetTimeout","makePromiseBuffer","bufferSize","rateLimits","filteredEnvelopeItems","limits","envelopeItemDataCategory","all","disabledUntil","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","trim","_limit$split","retryAfter","categories","headerDelay","delay","headerDate","parse","parseRetryAfterHeader","updateRateLimits","__sentry__baseTransport__","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","lastFrameFunction","firstFrameFunction","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","Dedupe","eventProcessor","currentEvent","previousEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","_previousEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","script","async","src","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","injectionPoint","Integrations","CaptureConsole","levels","_levels","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","tracesSampleRate","replaysSessionSampleRate","replaysOnErrorSampleRate","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"forum.js","mappings":";2BAAA,IAAIA,EAAUC,EAAAA,KAAAA,QACd,SAASC,IACP,aACAC,EAAOC,QAAUF,EAAsB,WACrC,OAAOE,CACT,EAAGD,EAAOC,QAAQC,YAAa,EAAMF,EAAOC,QAAiB,QAAID,EAAOC,QACxE,IAAIA,EAAU,CAAC,EACbE,EAAKC,OAAOC,UACZC,EAASH,EAAGI,eACZC,EAAiBJ,OAAOI,gBAAkB,SAAUC,EAAKC,EAAKC,GAC5DF,EAAIC,GAAOC,EAAKC,KAClB,EACAC,EAAU,mBAAqBC,OAASA,OAAS,CAAC,EAClDC,EAAiBF,EAAQG,UAAY,aACrCC,EAAsBJ,EAAQK,eAAiB,kBAC/CC,EAAoBN,EAAQO,aAAe,gBAC7C,SAASC,EAAOZ,EAAKC,EAAKE,GACxB,OAAOR,OAAOI,eAAeC,EAAKC,EAAK,CACrCE,MAAOA,EACPU,YAAY,EACZC,cAAc,EACdC,UAAU,IACRf,EAAIC,EACV,CACA,IACEW,EAAO,CAAC,EAAG,GACb,CAAE,MAAOI,GACPJ,EAAS,SAAgBZ,EAAKC,EAAKE,GACjC,OAAOH,EAAIC,GAAOE,CACpB,CACF,CACA,SAASc,EAAKC,EAASC,EAASC,EAAMC,GACpC,IAAIC,EAAiBH,GAAWA,EAAQvB,qBAAqB2B,EAAYJ,EAAUI,EACjFC,EAAY7B,OAAO8B,OAAOH,EAAe1B,WACzC8B,EAAU,IAAIC,EAAQN,GAAe,IACvC,OAAOtB,EAAeyB,EAAW,UAAW,CAC1CrB,MAAOyB,EAAiBV,EAASE,EAAMM,KACrCF,CACN,CACA,SAASK,EAASC,EAAI9B,EAAK+B,GACzB,IACE,MAAO,CACLC,KAAM,SACND,IAAKD,EA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ARA,IAAAA,EAAW,YAEtC,IAAIC,EAAW,CAAC,EAGhB,GAAItc,IAAK,KAAAuc,EAGoCC,EAFrC/9B,EAAkB,OAAd89B,EAAGvc,IAAAA,cAAW,EAAXuc,EAAa99B,KAEtBuhB,IAAAA,SAAevhB,GAAqB,GAAbA,EAAKlJ,OACtBinC,EAAG,CACT79B,WAAY,WACZpJ,GAAIkJ,EAAKlJ,OACR8mC,GAAW59B,EAAKK,WAHnBw9B,EAG6BE,EAGxBxc,IAAAA,KAAS,6BACZsc,EAASz9B,MAAQJ,EAAKI,UAEfmhB,IAAAA,KAASxhB,SAAsC,GAA3BwhB,IAAAA,KAASxhB,QAAQi+B,SAC9CH,EAAW,CACT/mC,GAAIyqB,IAAAA,KAASxhB,QAAQi+B,QAG3B,CAEA,OAAOH,CACT,EAEAtc,IAAAA,aAAiBhf,IAAI,cAAc,WACjCyC,KAAgBuF,QAAQ0yB,OAAOM,cACjC","sources":["webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/regeneratorRuntime.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/typeof.js","webpack://@fof/sentry/./node_modules/@babel/runtime/regenerator/index.js","webpack://@fof/sentry/webpack/bootstrap","webpack://@fof/sentry/webpack/runtime/compat get default export","webpack://@fof/sentry/webpack/runtime/define property getters","webpack://@fof/sentry/webpack/runtime/global","webpack://@fof/sentry/webpack/runtime/hasOwnProperty shorthand","webpack://@fof/sentry/webpack/runtime/make namespace object","webpack://@fof/sentry/external root \"flarum.core.compat['forum/app']\"","webpack://@fof/sentry/../../src/debug-build.ts","webpack://@fof/sentry/../../src/worldwide.ts","webpack://@fof/sentry/../../src/logger.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://@fof/sentry/../../src/is.ts","webpack://@fof/sentry/../../src/browser.ts","webpack://@fof/sentry/../../src/string.ts","webpack://@fof/sentry/../../src/object.ts","webpack://@fof/sentry/../../src/misc.ts","webpack://@fof/sentry/../../src/syncpromise.ts","webpack://@fof/sentry/../../src/eventProcessors.ts","webpack://@fof/sentry/../../src/time.ts","webpack://@fof/sentry/../../src/constants.ts","webpack://@fof/sentry/../../src/session.ts","webpack://@fof/sentry/../../src/stacktrace.ts","webpack://@fof/sentry/../../src/normalize.ts","webpack://@fof/sentry/../../src/memo.ts","webpack://@fof/sentry/../../../src/utils/spanUtils.ts","webpack://@fof/sentry/../../../src/utils/prepareEvent.ts","webpack://@fof/sentry/../../src/exports.ts","webpack://@fof/sentry/../../../src/utils/getRootSpan.ts","webpack://@fof/sentry/../../../src/tracing/dynamicSamplingContext.ts","webpack://@fof/sentry/../../../src/utils/applyScopeDataToEvent.ts","webpack://@fof/sentry/../../src/scope.ts","webpack://@fof/sentry/../../src/version.ts","webpack://@fof/sentry/../../src/hub.ts","webpack://@fof/sentry/../../src/integration.ts","webpack://@fof/sentry/../../../src/integrations/inboundfilters.ts","webpack://@fof/sentry/../../../src/integrations/functiontostring.ts","webpack://@fof/sentry/../../../src/helpers.ts","webpack://@fof/sentry/../../../../src/integrations/trycatch.ts","webpack://@fof/sentry/../../../src/instrument/_handlers.ts","webpack://@fof/sentry/../../../src/instrument/globalError.ts","webpack://@fof/sentry/../../../src/instrument/globalUnhandledRejection.ts","webpack://@fof/sentry/../../../src/eventbuilder.ts","webpack://@fof/sentry/../../../../src/integrations/globalhandlers.ts","webpack://@fof/sentry/../../../src/instrument/console.ts","webpack://@fof/sentry/../../../src/instrument/dom.ts","webpack://@fof/sentry/../../../src/instrument/xhr.ts","webpack://@fof/sentry/../../src/supports.ts","webpack://@fof/sentry/../../../src/instrument/fetch.ts","webpack://@fof/sentry/../../../src/vendor/supportsHistory.ts","webpack://@fof/sentry/../../../src/instrument/history.ts","webpack://@fof/sentry/../../src/severity.ts","webpack://@fof/sentry/../../src/url.ts","webpack://@fof/sentry/../../../../src/integrations/breadcrumbs.ts","webpack://@fof/sentry/../../src/aggregate-errors.ts","webpack://@fof/sentry/../../../../src/integrations/linkederrors.ts","webpack://@fof/sentry/../../../../src/integrations/httpcontext.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://@fof/sentry/../../src/dsn.ts","webpack://@fof/sentry/../../src/envelope.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://@fof/sentry/../../src/error.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://@fof/sentry/../../src/api.ts","webpack://@fof/sentry/../../../src/metrics/envelope.ts","webpack://@fof/sentry/../../../src/metrics/utils.ts","webpack://@fof/sentry/../../src/baseclient.ts","webpack://@fof/sentry/../../../src/client.ts","webpack://@fof/sentry/../../../src/utils/sdkMetadata.ts","webpack://@fof/sentry/../../src/env.ts","webpack://@fof/sentry/../../../src/userfeedback.ts","webpack://@fof/sentry/../../src/clientreport.ts","webpack://@fof/sentry/../../src/ratelimit.ts","webpack://@fof/sentry/../../../src/transports/base.ts","webpack://@fof/sentry/../../src/promisebuffer.ts","webpack://@fof/sentry/../../../../src/transports/utils.ts","webpack://@fof/sentry/../../../../src/transports/fetch.ts","webpack://@fof/sentry/../../../src/stack-parsers.ts","webpack://@fof/sentry/../../../../src/integrations/dedupe.ts","webpack://@fof/sentry/../../../src/sdk.ts","webpack://@fof/sentry/../../../src/captureconsole.ts","webpack://@fof/sentry/./src/forum/index.js"],"sourcesContent":["var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","export const DEFAULT_ENVIRONMENT = 'production';\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // 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)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial | EventHint): hint is Partial {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","export const SDK_VERSION = '7.119.1';\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n IntegrationFnResult,\n Options,\n} from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { addGlobalEventProcessor } from './eventProcessors';\nimport { getClient } from './exports';\nimport { getCurrentHub } from './hub';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Pick): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1) {\n // eslint-disable-next-line deprecation/deprecation\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (client.on && typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (client.addEventProcessor && typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client || !client.addIntegration) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Convert a new integration function to the legacy class syntax.\n * In v8, we can remove this and instead export the integration functions directly.\n *\n * @deprecated This will be removed in v8!\n */\nexport function convertIntegrationFnToClass(\n name: string,\n fn: Fn,\n): IntegrationClass {\n return Object.assign(\n function ConvertedIntegration(...args: Parameters): Integration {\n return fn(...args);\n },\n { id: name },\n ) as unknown as IntegrationClass;\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration(fn: Fn): (...args: Parameters) => IntegrationFnResult {\n return fn;\n}\n","import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/,\n /^Cannot redefine property: googletag$/,\n];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options: Partial = {}) => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\n/**\n * Inbound filters configurable by the user.\n * @deprecated Use `inboundFiltersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const InboundFilters = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n inboundFiltersIntegration,\n) as IntegrationClass void }> & {\n new (\n options?: Partial<{\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n }>,\n ): Integration;\n};\n\nfunction _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if (DEBUG_BUILD && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","import type { Client, Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\nimport { getClient } from '../exports';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nlet originalFunctionToString: () => void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * @deprecated Use `functionToStringIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const FunctionToString = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n functionToStringIntegration,\n) as IntegrationClass void }>;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type FunctionToString = typeof FunctionToString;\n","import type { browserTracingIntegration } from '@sentry-internal/tracing';\nimport { BrowserTracing } from '@sentry-internal/tracing';\nimport { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Integration, Mechanism, WrappedFunction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n *\n * @deprecated This type will be removed in the next major version of the Sentry SDK. `showReportDialog` will still be around, however the `eventId` option will now be required.\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n /** Callback after reportDialog closed */\n onClose?(this: void): void;\n}\n\n/**\n * This is a slim shim of `browserTracingIntegration` for the CDN bundles.\n * Since the actual functional integration uses a different code from `BrowserTracing`,\n * we want to avoid shipping both of them in the CDN bundles, as that would blow up the size.\n * Instead, we provide a functional integration with the same API, but the old implementation.\n * This means that it's not possible to register custom routing instrumentation, but that's OK for now.\n * We also don't expose the utilities for this anyhow in the CDN bundles.\n * For users that need custom routing in CDN bundles, they have to continue using `new BrowserTracing()` until v8.\n */\nexport function bundleBrowserTracingIntegration(\n options: Parameters[0] = {},\n): Integration {\n // Migrate some options from the old integration to the new one\n // eslint-disable-next-line deprecation/deprecation\n const opts: ConstructorParameters[0] = options;\n\n if (typeof options.markBackgroundSpan === 'boolean') {\n opts.markBackgroundTransactions = options.markBackgroundSpan;\n }\n\n if (typeof options.instrumentPageLoad === 'boolean') {\n opts.startTransactionOnPageLoad = options.instrumentPageLoad;\n }\n\n if (typeof options.instrumentNavigation === 'boolean') {\n opts.startTransactionOnLocationChange = options.instrumentNavigation;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return new BrowserTracing(opts);\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'TryCatch';\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\nconst _browserApiErrorsIntegration = ((options: Partial = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n * @deprecated Use `browserApiErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const TryCatch = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n browserApiErrorsIntegration,\n) as IntegrationClass & {\n new (options?: {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n }): Integration;\n};\n\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: VoidFunction,): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n","import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import { getClient } from '@sentry/core';\nimport type {\n Event,\n EventHint,\n Exception,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isParameterizedString,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const client = getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n message: ParameterizedString,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception: Record,\n { isUnhandledRejection }: { isUnhandledRejection?: boolean },\n): string {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n try {\n const prototype: Prototype | null = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { captureEvent, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Primitive,\n StackParser,\n} from '@sentry/types';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record;\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options: Partial = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\n/**\n * Global handlers.\n * @deprecated Use `globalHandlersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const GlobalHandlers = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n globalHandlersIntegration,\n) as IntegrationClass void }> & {\n new (options?: Partial): Integration;\n};\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e as unknown);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = error as any;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n return e.reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n return e.detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable max-lines */\nimport { addBreadcrumb, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event as SentryEvent,\n HandlerDataConsole,\n HandlerDataDom,\n HandlerDataFetch,\n HandlerDataHistory,\n HandlerDataXhr,\n Integration,\n IntegrationClass,\n IntegrationFn,\n} from '@sentry/types';\nimport type {\n Breadcrumb,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n SENTRY_XHR_DATA_KEY,\n addClickKeypressInstrumentationHandler,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n getComponentName,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options: Partial = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry && client.on) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Default Breadcrumbs instrumentations\n *\n * @deprecated Use `breadcrumbsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Breadcrumbs = convertIntegrationFnToClass(INTEGRATION_NAME, breadcrumbsIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (\n options?: Partial<{\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n }>,\n ): Integration;\n};\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client: Client): (handlerData: HandlerDataConsole) => void {\n return function _consoleBreadcrumb(handlerData: HandlerDataConsole): void {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record).target;\n}\n","import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Aggregrate linked errors in an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'HttpContext';\n\nconst _httpContextIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const httpContextIntegration = defineIntegration(_httpContextIntegration);\n\n/**\n * HttpContext integration collects information about HTTP request headers.\n * @deprecated Use `httpContextIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const HttpContext = convertIntegrationFnToClass(INTEGRATION_NAME, httpContextIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event) => void }\n>;\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","import type { ConsoleLevel } from '@sentry/types';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\nimport { serializeMetricBuckets } from './utils';\n\n/**\n * Create envelope from a metric aggregate.\n */\nexport function createMetricEnvelope(\n metricBucketItems: Array,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): StatsdEnvelope {\n const headers: StatsdEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const item = createMetricEnvelopeItem(metricBucketItems);\n return createEnvelope(headers, [item]);\n}\n\nfunction createMetricEnvelopeItem(metricBucketItems: MetricBucketItem[]): StatsdItem {\n const payload = serializeMetricBuckets(metricBucketItems);\n const metricHeaders: StatsdItem[0] = {\n type: 'statsd',\n length: payload.length,\n };\n return [metricHeaders, payload];\n}\n","import type { MeasurementUnit, MetricBucketItem, Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport type { MetricType } from './types';\n\n/**\n * Generate bucket key from metric properties.\n */\nexport function getBucketKey(\n metricType: MetricType,\n name: string,\n unit: MeasurementUnit,\n tags: Record,\n): string {\n const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));\n return `${metricType}${name}${unit}${stringifiedTags}`;\n}\n\n/* eslint-disable no-bitwise */\n/**\n * Simple hash function for strings.\n */\nexport function simpleHash(s: string): number {\n let rv = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n rv = (rv << 5) - rv + c;\n rv &= rv;\n }\n return rv >>> 0;\n}\n/* eslint-enable no-bitwise */\n\n/**\n * Serialize metrics buckets into a string based on statsd format.\n *\n * Example of format:\n * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677\n * Segments:\n * name: metric.name\n * unit: second\n * value: [1, 1.2]\n * type of metric: d (distribution)\n * tags: { a: value, b: anothervalue }\n * timestamp: 12345677\n */\nexport function serializeMetricBuckets(metricBucketItems: MetricBucketItem[]): string {\n let out = '';\n for (const item of metricBucketItems) {\n const tagEntries = Object.entries(item.tags);\n const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';\n out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\\n`;\n }\n return out;\n}\n\n/** Sanitizes units */\nexport function sanitizeUnit(unit: string): string {\n return unit.replace(/[^\\w]+/gi, '_');\n}\n\n/** Sanitizes metric keys */\nexport function sanitizeMetricKey(key: string): string {\n return key.replace(/[^\\w\\-.]+/gi, '_');\n}\n\nfunction sanitizeTagKey(key: string): string {\n return key.replace(/[^\\w\\-./]+/gi, '');\n}\n\nconst tagValueReplacements: [string, string][] = [\n ['\\n', '\\\\n'],\n ['\\r', '\\\\r'],\n ['\\t', '\\\\t'],\n ['\\\\', '\\\\\\\\'],\n ['|', '\\\\u{7c}'],\n [',', '\\\\u{2c}'],\n];\n\nfunction getCharOrReplacement(input: string): string {\n for (const [search, replacement] of tagValueReplacements) {\n if (input === search) {\n return replacement;\n }\n }\n\n return input;\n}\n\nfunction sanitizeTagValue(value: string): string {\n return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), '');\n}\n\n/**\n * Sanitizes tags.\n */\nexport function sanitizeTags(unsanitizedTags: Record): Record {\n const tags: Record = {};\n for (const key in unsanitizedTags) {\n if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {\n const sanitizedKey = sanitizeTagKey(key);\n tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));\n }\n }\n return tags;\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n EventProcessor,\n FeedbackEvent,\n Integration,\n IntegrationClass,\n MetricBucketItem,\n MetricsAggregator,\n Outcome,\n ParameterizedString,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n StartSpanOptions,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n SentryError,\n SyncPromise,\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isParameterizedString,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport { getClient } from './exports';\nimport { getIsolationScope } from './hub';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport { createMetricEnvelope } from './metrics/envelope';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /**\n * A reference to a metrics aggregator\n *\n * @experimental Note this is alpha API. It may experience breaking changes in the future.\n */\n public metricsAggregator?: MetricsAggregator;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n protected _eventProcessors: EventProcessor[];\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(\n this._captureEvent(event, hint, capturedSpanScope || scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n if (this.metricsAggregator) {\n this.metricsAggregator.flush();\n }\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n if (this.metricsAggregator) {\n this.metricsAggregator.close();\n }\n return result;\n });\n }\n\n /** Get all installed event processors. */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * This is an internal function to setup all integrations that should run on the client.\n * @deprecated Use `client.init()` instead.\n */\n public setupIntegrations(forceInitialize?: boolean): void {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._setupIntegrations();\n }\n }\n\n /** @inheritdoc */\n public init(): void {\n if (this._isEnabled()) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this.getIntegrationByName(integrationId);\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n public getIntegrationByName(integrationName: string): T | undefined {\n return this._integrations[integrationName] as T | undefined;\n }\n\n /**\n * Returns the client's instance of the given integration class, it any.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, eventOrCount?: Event | number): void {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /**\n * @inheritDoc\n */\n public captureAggregateMetrics(metricBucketItems: Array): void {\n DEBUG_BUILD && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);\n const metricsEnvelope = createMetricEnvelope(\n metricBucketItems,\n this._dsn,\n this._options._metadata,\n this._options.tunnel,\n );\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(metricsEnvelope);\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n public on(hook: 'startTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'startPageLoadSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'startPageLoadSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: 'startNavigationSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n protected _setupIntegrations(): void {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n\n // TODO v8: We don't need this flag anymore\n this._integrationsInitialized = true;\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope = getIsolationScope(),\n ): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n const propagationContext = {\n ...isolationScope.getPropagationContext(),\n ...(scope ? scope.getPropagationContext() : undefined),\n };\n\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n DEBUG_BUILD && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/**\n * Add an event processor to the current client.\n * This event processor will run for all events processed by this client.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n const client = getClient();\n\n if (!client || !client.addEventProcessor) {\n return;\n }\n\n client.addEventProcessor(callback);\n}\n","import type { Scope } from '@sentry/core';\nimport { applySdkMetadata } from '@sentry/core';\nimport { BaseClient } from '@sentry/core';\nimport type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n ParameterizedString,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(options, 'browser', ['browser'], sdkSource);\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n}\n","import type { Options } from '@sentry/types';\nimport { SDK_VERSION } from '../version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: Options, name: string, names = [name], source = 'npm'): void {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-expect-error __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type { DataCategory, TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = Date.now()): boolean {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n SentryError,\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n DEBUG_BUILD && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/**\n * Deduplication filter.\n * @deprecated Use `dedupeIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Dedupe = convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n>;\n\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport { functionToStringIntegration, inboundFiltersIntegration } from '@sentry/core';\nimport {\n captureSession,\n getClient,\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n startSession,\n} from '@sentry/core';\nimport type { Integration, Options, UserFeedback } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n logger,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs';\nimport { dedupeIntegration } from './integrations/dedupe';\nimport { globalHandlersIntegration } from './integrations/globalhandlers';\nimport { httpContextIntegration } from './integrations/httpcontext';\nimport { linkedErrorsIntegration } from './integrations/linkederrors';\nimport { browserApiErrorsIntegration } from './integrations/trycatch';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\n/** @deprecated Use `getDefaultIntegrations(options)` instead. */\nexport const defaultIntegrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n];\n\n/** Get the default integrations for the browser SDK. */\nexport function getDefaultIntegrations(_options: Options): Integration[] {\n // We return a copy of the defaultIntegrations here to avoid mutating this\n return [\n // eslint-disable-next-line deprecation/deprecation\n ...defaultIntegrations,\n ];\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\ntype NewReportDialogOptions = ReportDialogOptions & { eventId: string }; // eslint-disable-line\n\ninterface ShowReportDialogFunction {\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\n (options: NewReportDialogOptions): void;\n\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n *\n * @deprecated Please always pass an `options` argument with `eventId`. The `hub` argument will not be used in the next version of the SDK.\n */\n // eslint-disable-next-line deprecation/deprecation\n (options?: ReportDialogOptions, hub?: Hub): void;\n}\n\nexport const showReportDialog: ShowReportDialogFunction = (\n // eslint-disable-next-line deprecation/deprecation\n options: ReportDialogOptions = {},\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub = getCurrentHub(),\n) => {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n // eslint-disable-next-line deprecation/deprecation\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event: MessageEvent): void => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n};\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import {\n captureException,\n captureMessage,\n convertIntegrationFnToClass,\n defineIntegration,\n getClient,\n withScope,\n} from '@sentry/core';\nimport type { CaptureContext, Client, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport {\n CONSOLE_LEVELS,\n GLOBAL_OBJ,\n addConsoleInstrumentationHandler,\n addExceptionMechanism,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\ninterface CaptureConsoleOptions {\n levels?: string[];\n}\n\nconst INTEGRATION_NAME = 'CaptureConsole';\n\nconst _captureConsoleIntegration = ((options: CaptureConsoleOptions = {}) => {\n const levels = options.levels || CONSOLE_LEVELS;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.includes(level)) {\n return;\n }\n\n consoleHandler(args, level);\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);\n\n/**\n * Send Console API calls as Sentry Events.\n * @deprecated Use `captureConsoleIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const CaptureConsole = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n captureConsoleIntegration,\n) as IntegrationClass void }> & {\n new (options?: { levels?: string[] }): Integration;\n};\n\nfunction consoleHandler(args: unknown[], level: string): void {\n const captureContext: CaptureContext = {\n level: severityLevelFromString(level),\n extra: {\n arguments: args,\n },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'console';\n\n addExceptionMechanism(event, {\n handled: false,\n type: 'console',\n });\n\n return event;\n });\n\n if (level === 'assert' && args[0] === false) {\n const message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n captureMessage(message, captureContext);\n return;\n }\n\n const error = args.find(arg => arg instanceof Error);\n if (level === 'error' && error) {\n captureException(error, captureContext);\n return;\n }\n\n const message = safeJoin(args, ' ');\n captureMessage(message, captureContext);\n });\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["_typeof","require","_regeneratorRuntime","module","exports","__esModule","Op","Object","prototype","hasOwn","hasOwnProperty","defineProperty","obj","key","desc","value","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","fn","arg","type","call","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","result","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","undefined","done","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","methodName","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","runtime","regeneratorRuntime","accidentalStrictMode","globalThis","Function","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","n","getter","d","a","definition","o","get","g","e","window","prop","r","flarum","core","compat","DEBUG_BUILD","__SENTRY_DEBUG__","isGlobalObj","Math","GLOBAL_OBJ","global","getGlobalObject","getGlobalSingleton","creator","gbl","__SENTRY__","CONSOLE_LEVELS","originalConsoleMethods","consoleSandbox","callback","console","wrappedFuncs","wrappedLevels","level","originalConsoleMethod","enabled","logger","enable","disable","isEnabled","_len","arguments","args","Array","_key","_GLOBAL_OBJ$console","apply","PREFIX","concat","_extends","assign","bind","target","source","objectToString","toString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isParameterizedString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","base","_e","isVueViewModel","__isVue","_isVue","WINDOW","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","options","nextStr","currentElem","out","height","len","keyAttrs","isArray","maxStringLength","_htmlElementAsString","separator","parentNode","join","_oO","el","classes","attr","tagName","HTMLElement","dataset","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","keyAttrPair","id","split","allowedAttrs","truncate","str","max","safeJoin","input","delimiter","output","String","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","fill","replacementFactory","original","wrapped","markFunctionWrapped","addNonEnumerableProperty","o_O","log","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","message","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","isPojo","memoVal","returnValue","set","_i","_Object$keys","item","uuid4","crypto","msCrypto","getRandomByte","random","randomUUID","replace","getRandomValues","typedArray","Uint8Array","_","c","getFirstException","event","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","States","resolvedSyncPromise","SyncPromise","rejectedSyncPromise","reason","executor","__init","__init2","__init3","__init4","_state","PENDING","_handlers","_resolve","_reject","_proto","onfulfilled","onrejected","_this","_executeHandlers","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","_value","_this6","cachedHandlers","handler","getGlobalEventProcessors","addGlobalEventProcessor","notifyEventProcessors","processors","hint","index","processor","final","ONE_SECOND_IN_MS","dateTimestampInSeconds","Date","now","timestampInSeconds","performance","approxStartingTimeOrigin","timeOrigin","createUnixTimestampInSecondsFunc","DEFAULT_ENVIRONMENT","threshold","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","abnormal_mechanism","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","defaultFunctionName","getFunctionName","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","document","isSyntheticEvent","objName","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","toJSON","numAdded","visitable","visitKey","visitValue","TRACE_FLAG_SAMPLED","spanToTraceContext","span","_span$spanContext","spanContext","span_id","spanId","trace_id","traceId","_spanToJSON","spanToJSON","op","parent_span_id","tags","origin","getSpanJSON","spanIsSpanClass","debugIdStackParserCache","WeakMap","captureContextKeys","captureEvent","getCurrentHub","addBreadcrumb","breadcrumb","getClient","getRootSpan","transaction","getDynamicSamplingContextFromClient","client","scope","getOptions","public_key","getDsn","publicKey","user_segment","getUser","segment","dsc","emit","getDynamicSamplingContextFromSpan","getScope","txn","v7FrozenDsc","_frozenDynamicSamplingContext","_txn$metadata","metadata","maybeSampleRate","sampleRate","sample_rate","jsonSpan","description","sampled","traceFlags","spanIsSampled","applyScopeDataToEvent","fingerprint","breadcrumbs","sdkProcessingMetadata","extra","contexts","transactionName","cleanedExtra","cleanedTags","cleanedUser","cleanedContexts","applyDataToEvent","trace","rootSpan","dynamicSamplingContext","applySpanToEvent","maybeArray","applyFingerprintToEvent","mergedBreadcrumbs","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","eventProcessors","attachments","propagationContext","mergeAndOverwriteScopeData","mergeVal","globalScope","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","_propagationContext","generatePropagationContext","clone","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","_client","setClient","addScopeListener","addEventProcessor","setUser","_notifyScopeListeners","getRequestSession","setRequestSession","requestSession","setTags","setTag","_extends2","setExtras","extras","setExtra","_extends3","setFingerprint","setLevel","setTransactionName","setContext","setSpan","getSpan","getTransaction","setSession","getSession","update","captureContext","scopeToMerge","scopeData","getScopeData","scopeContext","clear","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","additionalEventProcessors","setSDKProcessingMetadata","newData","setPropagationContext","getPropagationContext","captureException","warn","syntheticException","originalException","captureMessage","substring","SDK_VERSION","API_VERSION","parseFloat","Hub","isolationScope","_version","assignedScope","assignedIsolationScope","_stack","bindClient","_isolationScope","isOlderThan","version","top","getStackTop","setupIntegrations","pushScope","getStack","popScope","withScope","maybePromiseResult","res","getIsolationScope","_lastEventId","lastEventId","_this$getStackTop","_ref","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","configureScope","_this$getStackTop2","run","oldHub","makeMain","getIntegration","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2","_ref2$environment","navigator","startingTime","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","sentry","getMainCarrier","extensions","hub","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","installedIntegrations","afterSetupIntegrations","integrations","_step","_iterator","_createForOfIteratorHelperLoose","afterAllSetup","setupIntegration","integrationIndex","indexOf","setupOnce","setup","on","preprocessEvent","processEvent","convertIntegrationFnToClass","originalFunctionToString","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","INTEGRATION_NAME","inboundFiltersIntegration","_hint","clientOptions","mergedOptions","internalOptions","allowUrls","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","_isSentryError","lastException","possibleMessages","_getPossibleEventMessages","_isIgnoredError","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","InboundFilters","frames","stacktrace","frame","filename","_getLastValidUrl","oO","SETUP_CLIENTS","functionToStringIntegration","originalFunction","FunctionToString","ignoreOnError","shouldIgnoreOnError","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","ex","setTimeout","rest","hintIsScopeOrFunction","hintIsScopeContext","parseEventHintOrCaptureContext","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","browserApiErrorsIntegration","_options","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","TryCatch","originalCallback","function","originalSend","xhr","wrapOptions","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","handlers","instrumented","addHandler","maybeInstrument","instrumentFn","triggerHandlers","typeHandlers","_oldOnErrorHandler","instrumentError","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","instrumentUnhandledRejection","onunhandledrejection","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","getNonErrorObjectExceptionValue","__serialized__","eventFromPlainObject","synthetic","__sentry_template_string__","__sentry_template_values__","logentry","params","maxLength","sort","includedKeys","serialized","extractExceptionKeysForMessage","captureType","getObjectClassName","globalHandlersIntegration","stackTraceLimit","_getOptions","groups","match","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","_installGlobalOnErrorHandler","globalHandlerLog","_getOptions2","e2","_getUnhandledRejectionError","_installGlobalOnUnhandledRejectionHandler","GlobalHandlers","ev","ev0","ev0s","ev0sf","colno","parseInt","lineno","location","href","getLocationHref","in_app","instrumentConsole","debounceTimerID","lastCapturedEventType","lastCapturedEventTargetId","DEBOUNCE_DURATION","instrumentDOM","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","globalListener","getEventTarget","eventType","isContentEditable","shouldSkipDOMEvent","_sentryId","isSimilarToLastCapturedEvent","clearTimeout","SENTRY_XHR_DATA_KEY","instrumentXHR","xhrproto","originalOpen","startTimestamp","toUpperCase","parseUrl","request_headers","__sentry_own_request__","onreadystatechangeHandler","xhrInfo","readyState","status_code","endTimestamp","onreadystatechange","readyStateArgs","_len3","setRequestHeaderArgs","_key3","header","sentryXhrData","_len4","_key4","body","isNativeFetch","instrumentFetch","EdgeRuntime","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","resource","lastHref","instrumentHistory","isChromePackagedApp","chromeVar","chrome","app","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","from","historyReplacementFunction","originalHistoryFunction","validSeverityLevels","query","fragment","host","path","protocol","search","hash","relative","MAX_ALLOWED_STRING_LENGTH","breadcrumbsIntegration","dom","category","_getConsoleBreadcrumbHandler","addClickKeypressInstrumentationHandler","componentName","serializeAttribute","element","_isEvent","getComponentName","_getDomBreadcrumbHandler","addXhrInstrumentationHandler","_getXhrBreadcrumbHandler","addFetchInstrumentationHandler","_getFetchBreadcrumbHandler","addHistoryInstrumentationHandler","parsedLoc","parsedFrom","parsedTo","_getHistoryBreadcrumbHandler","_getSentryBreadcrumbHandler","Breadcrumbs","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","parser","maxValueLimit","limit","exceptions","maxValueLength","aggregateExceptionsFromError","prevExceptions","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","childError","is_exception_group","exception_id","parentId","parent_id","linkedErrorsIntegration","LinkedErrors","httpContextIntegration","request","referrer","headers","Referer","HttpContext","_setPrototypeOf","p","_inheritsLoose","subClass","superClass","DSN_REGEX","dsnToString","dsn","withPassword","pass","port","projectId","dsnFromComponents","components","makeDsn","exec","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","find","component","isValidProtocol","validateDsn","createEnvelope","items","forEachEnvelopeItem","envelope","envelopeItem","encodeUTF8","textEncoder","TextEncoder","encode","serializeEnvelope","envHeaders","parts","append","_step2","_iterator2","itemHeaders","payload","stringifiedPayload","buffers","_step3","totalLength","reduce","acc","buf","merged","offset","_iterator3","buffer","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","feedback","statsd","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","sdk","_metadataOrEvent$sdk","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","Wrapper","SentryError","_Error","logLevel","ReferenceError","_assertThisInitialized","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","tunnel","sdkInfo","_metadata","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","encodeURIComponent","_encodedAuth","createMetricEnvelope","metricBucketItems","sent_at","tagEntries","entries","maybeTags","unit","metric","metricType","serializeMetricBuckets","createMetricEnvelopeItem","ALREADY_SEEN_ERROR","BaseClient","_integrations","_integrationsInitialized","_numProcessing","_outcomes","_hooks","_dsn","_transport","transport","recordDroppedEvent","transportOptions","_process","eventFromException","_captureEvent","eventMessage","promisedEvent","eventFromMessage","capturedSpanScope","sendSession","getSdkMetadata","getTransport","flush","timeout","metricsAggregator","_isClientDoneProcessing","clientFinished","transportFlushed","close","getEventProcessors","eventProcessor","forceInitialize","_isEnabled","_setupIntegrations","getIntegrationById","integrationId","getIntegrationByName","integrationName","addIntegration","isAlreadyInstalled","sendEvent","newItem","env","packages","enhanceEventWithSdkInfo","envelopeHeaders","createEventEnvelopeHeaders","createEventEnvelope","promise","_sendEnvelope","sendResponse","createSessionEnvelope","eventOrCount","sendClientReports","count","captureAggregateMetrics","metricsEnvelope","hook","_updateSessionFromEvent","crashed","errored","sessionNonTerminal","Number","ticked","interval","clearInterval","_prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","dist","_options$maxValueLeng","applyClientOptions","integrationNames","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","filenameDebugIdMap","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","getFinalScope","clientEventProcessors","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","b","spans","normalizeEvent","prepareEvent","parentSpanId","_processEvent","finalEvent","sentryError","_this7","isTransaction","isTransactionEvent","beforeSendLabel","dataCategory","capturedSpanIsolationScope","__sentry__","beforeSend","beforeSendTransaction","spanCountBefore","spanCountBeforeProcessing","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","spanCount","droppedSpanCount","transactionInfo","transaction_info","_this8","send","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","names","applySdkMetadata","SENTRY_SDK_SOURCE","visibilityState","_flushOutcomes","captureUserFeedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","platform","discarded_events","DEFAULT_RETRY_AFTER","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","remove","task","$","taskProducer","drain","counter","capturedSetTimeout","makePromiseBuffer","bufferSize","rateLimits","filteredEnvelopeItems","limits","all","disabledUntil","isRateLimited","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","trim","_limit$split","retryAfter","categories","namespaces","headerDelay","delay","headerDate","parse","parseRetryAfterHeader","updateRateLimits","__sentry__baseTransport__","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","dedupeIntegration","previousEvent","currentEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","script","crossOrigin","src","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","onClose","reportDialogClosedMessageHandler","removeEventListener","injectionPoint","makeLogger","severityLevelFromString","CaptureConsole","levels","consoleHandler","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","tracesSampleRate","replaysSessionSampleRate","replaysOnErrorSampleRate","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file diff --git a/js/dist/forum.replay.js b/js/dist/forum.replay.js index 00d463f..d09d4d3 100644 --- a/js/dist/forum.replay.js +++ b/js/dist/forum.replay.js @@ -1,3 +1,3 @@ /*! For license information please see forum.replay.js.LICENSE.txt */ -(()=>{var t={476:(t,e,n)=>{"use strict";function r(){return"undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&!!__SENTRY_BROWSER_BUNDLE__}function i(){return"npm"}n.d(e,{S:()=>i,n:()=>r})},538:(t,e,n)=>{"use strict";n.d(e,{KV:()=>i,l$:()=>a});var r=n(476);function i(){return!(0,r.n)()&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}function a(t,e){return t.require(e)}t=n.hmd(t)},910:(t,e,n)=>{"use strict";n.d(e,{Z1:()=>d,ph:()=>l,yW:()=>c});var r=n(538),i=n(899);t=n.hmd(t);var a=(0,i.Rf)(),o={nowSeconds:function(){return Date.now()/1e3}},s=(0,r.KV)()?function(){try{return(0,r.l$)(t,"perf_hooks").performance}catch(t){return}}():function(){var t=a.performance;if(t&&t.now)return{now:function(){return t.now()},timeOrigin:Date.now()-t.now()}}(),u=void 0===s?o:{nowSeconds:function(){return(s.timeOrigin+s.now())/1e3}},c=o.nowSeconds.bind(o),l=u.nowSeconds.bind(u),d=function(){var t=a.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i{"use strict";function r(t){return t&&t.Math==Math?t:void 0}n.d(e,{Rf:()=>a,YO:()=>o,n2:()=>i});var i="object"==typeof globalThis&&r(globalThis)||"object"==typeof window&&r(window)||"object"==typeof self&&r(self)||"object"==typeof n.g&&r(n.g)||function(){return this}()||{};function a(){return i}function o(t,e,n){var r=n||i,a=r.__SENTRY__=r.__SENTRY__||{};return a[t]||(a[t]=e())}},648:(t,e,n)=>{var r=n(288).default;function i(){"use strict";t.exports=i=function(){return e},t.exports.__esModule=!0,t.exports.default=t.exports;var e={},n=Object.prototype,a=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},u=s.iterator||"@@iterator",c=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function d(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{d({},"")}catch(t){d=function(t,e,n){return t[e]=n}}function h(t,e,n,r){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),s=new I(r||[]);return o(a,"_invoke",{value:x(t,n,s)}),a}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=h;var p={};function m(){}function v(){}function _(){}var g={};d(g,u,(function(){return this}));var y=Object.getPrototypeOf,b=y&&y(y(A([])));b&&b!==n&&a.call(b,u)&&(g=b);var w=_.prototype=m.prototype=Object.create(g);function k(t){["next","throw","return"].forEach((function(e){d(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function n(i,o,s,u){var c=f(t[i],t,o);if("throw"!==c.type){var l=c.arg,d=l.value;return d&&"object"==r(d)&&a.call(d,"__await")?e.resolve(d.__await).then((function(t){n("next",t,s,u)}),(function(t){n("throw",t,s,u)})):e.resolve(d).then((function(t){l.value=t,s(l)}),(function(t){return n("throw",t,s,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function a(){return new e((function(e,i){n(t,r,e,i)}))}return i=i?i.then(a,a):a()}})}function x(t,e,n){var r="suspendedStart";return function(i,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw a;return{value:void 0,done:!0}}for(n.method=i,n.arg=a;;){var o=n.delegate;if(o){var s=E(o,n);if(s){if(s===p)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var u=f(t,e,n);if("normal"===u.type){if(r=n.done?"completed":"suspendedYield",u.arg===p)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(r="completed",n.method="throw",n.arg=u.arg)}}}function E(t,e){var n=e.method,r=t.iterator[n];if(void 0===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=void 0,E(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),p;var i=f(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,p;var a=i.arg;return a?a.done?(e[t.resultName]=a.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,p):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,p)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function I(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function A(t){if(t){var e=t[u];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n=0;--r){var i=this.tryEntries[r],o=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=a.call(i,"catchLoc"),u=a.call(i,"finallyLoc");if(s&&u){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&a.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),p}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;C(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:A(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),p}},e}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},288:t=>{function e(n){return t.exports=e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.__esModule=!0,t.exports.default=t.exports,e(n)}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports},357:(t,e,n)=>{var r=n(648)();t.exports=r;try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var a=e[r]={id:r,loaded:!1,exports:{}};return t[r](a,a.exports,n),a.loaded=!0,a.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.hmd=t=>((t=Object.create(t)).children||(t.children=[]),Object.defineProperty(t,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+t.id)}}),t),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=Object.prototype.toString;function a(t){switch(i.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return p(t,Error)}}function o(t,e){return i.call(t)==="[object "+e+"]"}function s(t){return o(t,"ErrorEvent")}function u(t){return o(t,"DOMError")}function c(t){return o(t,"String")}function l(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function d(t){return o(t,"Object")}function h(t){return"undefined"!=typeof Event&&p(t,Event)}function f(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function p(t,e){try{return t instanceof e}catch(t){return!1}}function m(t,e){return void 0===e&&(e=0),"string"!=typeof t||0===e||t.length<=e?t:t.slice(0,e)+"..."}function v(t,e){if(!Array.isArray(t))return"";for(var n=[],r=0;r=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(t){return null}}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&o+3*i.length+n.length>=u);)i.push(n),o+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function I(t,e){var n,r,i,a,o,s=t,u=[];if(!s||!s.tagName)return"";u.push(s.tagName.toLowerCase());var l=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(l&&l.length)l.forEach((function(t){u.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&u.push("#"+s.id),(n=s.className)&&c(n))for(r=n.split(/\s+/),o=0;o"}}function N(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function z(t,e){void 0===e&&(e=40);var n=Object.keys(D(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return m(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:m(i,e)}return""}function U(t){return P(t,new Map)}function P(t,e){if(d(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,a=Object.keys(t);i=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function B(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n>t/4).toString(16)}))}function G(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function K(t){var e=t.message,n=t.event_id;if(e)return e;var r=G(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function Y(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],a=i[0]=i[0]||{};a.value||(a.value=e||""),a.type||(a.type=n||"Error")}function V(t,e){var n=G(t);if(n){var r=n.mechanism;if(n.mechanism=k({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=k({},r&&r.data,e.data);n.mechanism.data=i}}}function X(t){if(t&&t.__sentry_captured__)return!0;try{R(t,"__sentry_captured__",!0)}catch(t){}return!1}var J,$=n(910),Q=["debug","info","warn","error","log","assert","trace"];J={enable:function(){},disable:function(){}},Q.forEach((function(t){J[t]=function(){}}));var tt,et="production";function nt(t){return new it((function(e){e(t)}))}function rt(t){return new it((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(tt||(tt={}));var it=function(){var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this);try{t(this._resolve,this._reject)}catch(t){this._reject(t)}}return t.__init=function(){this._state=tt.PENDING},t.__init2=function(){this._handlers=[]},t.then=function(t,n){var r=this;return new e((function(e,i){r._handlers.push([!1,function(n){if(t)try{e(t(n))}catch(t){i(t)}else e(n)},function(t){if(n)try{e(n(t))}catch(t){i(t)}else i(t)}]),r._executeHandlers()}))},t.catch=function(t){return this.then((function(t){return t}),t)},t.finally=function(t){var n=this;return new e((function(e,r){var i,a;return n.then((function(e){a=!1,i=e,t&&t()}),(function(e){a=!0,i=e,t&&t()})).then((function(){a?r(i):e(i)}))}))},t.__init3=function(){var t=this;this._resolve=function(e){t._setResult(tt.RESOLVED,e)}},t.__init4=function(){var t=this;this._reject=function(e){t._setResult(tt.REJECTED,e)}},t.__init5=function(){var t=this;this._setResult=function(e,n){t._state===tt.PENDING&&(f(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},t.__init6=function(){var t=this;this._executeHandlers=function(){if(t._state!==tt.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===tt.RESOLVED&&e[1](t._value),t._state===tt.REJECTED&&e[2](t._value),e[0]=!0)}))}}},e}();function at(t,e){if(void 0===e&&(e={}),e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||(0,$.ph)(),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:Z()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=""+e.did),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{var n=t.timestamp-t.started;t.duration=n>=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}var ot=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={}}t.clone=function(e){var n=new t;return e&&(n._breadcrumbs=[].concat(e._breadcrumbs),n._tags=k({},e._tags),n._extra=k({},e._extra),n._contexts=k({},e._contexts),n._user=e._user,n._level=e._level,n._span=e._span,n._session=e._session,n._transactionName=e._transactionName,n._fingerprint=e._fingerprint,n._eventProcessors=[].concat(e._eventProcessors),n._requestSession=e._requestSession,n._attachments=[].concat(e._attachments),n._sdkProcessingMetadata=k({},e._sdkProcessingMetadata)),n};var e=t.prototype;return e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{},this._session&&at(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=k({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=k({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=k({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=k({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this.getSpan();return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;if("function"==typeof e){var n=e(this);return n instanceof t?n:this}return e instanceof t?(this._tags=k({},this._tags,e._tags),this._extra=k({},this._extra,e._extra),this._contexts=k({},this._contexts,e._contexts),e._user&&Object.keys(e._user).length&&(this._user=e._user),e._level&&(this._level=e._level),e._fingerprint&&(this._fingerprint=e._fingerprint),e._requestSession&&(this._requestSession=e._requestSession)):d(e)&&(this._tags=k({},this._tags,e.tags),this._extra=k({},this._extra,e.extra),this._contexts=k({},this._contexts,e.contexts),e.user&&(this._user=e.user),e.level&&(this._level=e.level),e.fingerprint&&(this._fingerprint=e.fingerprint),e.requestSession&&(this._requestSession=e.requestSession)),this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=k({timestamp:(0,$.yW)()},t);return this._breadcrumbs=[].concat(this._breadcrumbs,[r]).slice(-n),this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this._attachments},e.clearAttachments=function(){return this._attachments=[],this},e.applyToEvent=function(t,e){if(void 0===e&&(e={}),this._extra&&Object.keys(this._extra).length&&(t.extra=k({},this._extra,t.extra)),this._tags&&Object.keys(this._tags).length&&(t.tags=k({},this._tags,t.tags)),this._user&&Object.keys(this._user).length&&(t.user=k({},this._user,t.user)),this._contexts&&Object.keys(this._contexts).length&&(t.contexts=k({},this._contexts,t.contexts)),this._level&&(t.level=this._level),this._transactionName&&(t.transaction=this._transactionName),this._span){t.contexts=k({trace:this._span.getTraceContext()},t.contexts);var n=this._span.transaction;if(n){t.sdkProcessingMetadata=k({dynamicSamplingContext:n.getDynamicSamplingContext()},t.sdkProcessingMetadata);var r=n.name;r&&(t.tags=k({transaction:r},t.tags))}}return this._applyFingerprint(t),t.breadcrumbs=[].concat(t.breadcrumbs||[],this._breadcrumbs),t.breadcrumbs=t.breadcrumbs.length>0?t.breadcrumbs:void 0,t.sdkProcessingMetadata=k({},t.sdkProcessingMetadata,this._sdkProcessingMetadata),this._notifyEventProcessors([].concat(st(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=k({},this._sdkProcessingMetadata,t),this},e._notifyEventProcessors=function(t,e,n,r){var i=this;return void 0===r&&(r=0),new it((function(a,o){var s=t[r];if(null===e||"function"!=typeof s)a(e);else{var u=s(k({},e),n);f(u)?u.then((function(e){return i._notifyEventProcessors(t,e,n,r+1).then(a)})).then(null,o):i._notifyEventProcessors(t,u,n,r+1).then(a).then(null,o)}}))},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},e._applyFingerprint=function(t){var e;t.fingerprint=t.fingerprint?(e=t.fingerprint,Array.isArray(e)?e:[e]):[],this._fingerprint&&(t.fingerprint=t.fingerprint.concat(this._fingerprint)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint},t}();function st(){return(0,x.YO)("globalEventProcessors",(function(){return[]}))}function ut(t){st().push(t)}var ct=4,lt=function(){function t(t,e,n){void 0===e&&(e=new ot),void 0===n&&(n=ct),this._version=n,this._stack=[{scope:e}],t&&this.bindClient(t)}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;i0}function yt(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return r;if(L(t))return t}catch(e){return t}var i=function(){var r,i=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var a=i.map((function(t){return yt(t,e)}));return t.apply(this,a)}catch(t){throw _t++,setTimeout((function(){_t--})),r=function(n){var r;n.addEventProcessor((function(t){return e.mechanism&&(Y(t,void 0,void 0),V(t,e.mechanism)),t.extra=k({},t.extra,{arguments:i}),t})),r=t,ft().captureException(r,{captureContext:undefined})},ft().withScope(r),t}};try{for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(i[a]=t[a])}catch(t){}O(i,t),R(t,"__sentry_wrapped__",i);try{Object.getOwnPropertyDescriptor(i,"name").configurable&&Object.defineProperty(i,"name",{get:function(){return t.name}})}catch(t){}return i}var bt=["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"],wt=function(){e.__initStatic=function(){this.id="TryCatch"};var t=e.prototype;function e(t){e.prototype.__init.call(this),this._options=k({XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){this._options.setTimeout&&A(vt,"setTimeout",kt),this._options.setInterval&&A(vt,"setInterval",kt),this._options.requestAnimationFrame&&A(vt,"requestAnimationFrame",St),this._options.XMLHttpRequest&&"XMLHttpRequest"in vt&&A(XMLHttpRequest.prototype,"send",xt);var t=this._options.eventTarget;t&&(Array.isArray(t)?t:bt).forEach(Et)},e}();function kt(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n2?n[2]:void 0;if(i){var a=Rt,o=String(i);Rt=o,Ut("history",{from:a,to:o})}return t.apply(this,n)}}}();break;case"error":Wt=Ot.onerror,Ot.onerror=function(t,e,n,r,i){return Ut("error",{column:r,error:i,line:n,msg:t,url:e}),!(!Wt||Wt.__SENTRY_LOADER__)&&Wt.apply(this,arguments)},Ot.onerror.__SENTRY_INSTRUMENTED__=!0;break;case"unhandledrejection":Zt=Ot.onunhandledrejection,Ot.onunhandledrejection=function(t){return Ut("unhandledrejection",t),!(Zt&&!Zt.__SENTRY_LOADER__)||Zt.apply(this,arguments)},Ot.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0;break;default:return}}function zt(t,e){Dt[t]=Dt[t]||[],Dt[t].push(e),Nt(t)}function Ut(t,e){if(t&&Dt[t])for(var n,r=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return At(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?At(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Dt[t]||[]);!(n=r()).done;){var i=n.value;try{i(e)}catch(t){}}}function Pt(t,e){return!!t&&"object"==typeof t&&!!t[e]}function jt(t){return"string"==typeof t?t:t?Pt(t,"url")?t.url:t.toString?t.toString():"":""}var Ft,Bt,Ht=1e3;function qt(t,e){return void 0===e&&(e=!1),function(n){if(n&&Bt!==n&&!function(t){if("keypress"!==t.type)return!1;try{var e=t.target;if(!e||!e.tagName)return!0;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||e.isContentEditable)return!1}catch(t){}return!0}(n)){var r="keypress"===n.type?"input":n.type;(void 0===Ft||function(t,e){if(!t)return!0;if(t.type!==e.type)return!0;try{if(t.target!==e.target)return!0}catch(t){}return!1}(Bt,n))&&(t({event:n,name:r,global:e}),Bt=n),clearTimeout(Ft),Ft=Ot.setTimeout((function(){Ft=void 0}),Ht)}}}var Wt=null,Zt=null;function Gt(t,e,n){void 0===e&&(e=100),void 0===n&&(n=1/0);try{return Yt("",t,e,n)}catch(t){return{ERROR:"**non-serializable** ("+t+")"}}}function Kt(t,e,n){void 0===e&&(e=3),void 0===n&&(n=102400);var r,i=Gt(t,e);return r=i,function(t){return~-encodeURI(t).split(/%..|./).length}(JSON.stringify(r))>n?Kt(t,e-1,n):i}function Yt(t,e,r,i,a){var o,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===a&&(o="function"==typeof WeakSet,s=o?new WeakSet:[],a=[function(t){if(o)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){v[y]="[MaxProperties ~]";break}var b=g[y];v[y]=Yt(y,b,p-1,i,a),_++}return h(e),v}function Vt(t,e){var n=Jt(t,e),r={type:e&&e.name,value:Qt(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Xt(t,e){return{exception:{values:[Vt(t,e)]}}}function Jt(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if($t.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var $t=/Minified React error #\d+;/i;function Qt(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function te(t,e,n,r,i){var c;if(s(e)&&e.error)return Xt(t,e.error);if(u(e)||o(e,"DOMException")){var l=e;if("stack"in e)c=Xt(t,e);else{var f=l.name||(u(l)?"DOMError":"DOMException"),p=l.message?f+": "+l.message:f;Y(c=ee(t,p,n,r),p)}return"code"in l&&(c.tags=k({},c.tags,{"DOMException.code":""+l.code})),c}return a(e)?Xt(t,e):d(e)||h(e)?(c=function(t,e,n,r){var i=ft().getClient(),a=i&&i.getOptions().normalizeDepth,o={exception:{values:[{type:h(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:"Non-Error "+(r?"promise rejection":"exception")+" captured with keys: "+z(e)}]},extra:{__serialized__:Kt(e,a)}};if(n){var s=Jt(t,n);s.length&&(o.exception.values[0].stacktrace={frames:s})}return o}(t,e,n,i),V(c,{synthetic:!0}),c):(Y(c=ee(t,e,n,r),""+e,void 0),V(c,{synthetic:!0}),c)}function ee(t,e,n,r){var i={message:e};if(r&&n){var a=Jt(t,n);a.length&&(i.exception={values:[{value:e,stacktrace:{frames:a}}]})}return i}var ne=function(){e.__initStatic=function(){this.id="GlobalHandlers"};var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),this._options=k({onerror:!0,onunhandledrejection:!0},t)}return t.__init=function(){this.name=e.id},t.__init2=function(){this._installFunc={onerror:re,onunhandledrejection:ie}},t.setupOnce=function(){Error.stackTraceLimit=50;var t=this._options;for(var e in t){var n=this._installFunc[e];n&&t[e]&&(n(),this._installFunc[e]=void 0)}},e}();function re(){zt("error",(function(t){var e=se(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(ne)){var a=t.msg,o=t.url,u=t.line,l=t.column,d=t.error;if(!(gt()||d&&d.__sentry_own_request__)){var h=void 0===d&&c(a)?function(t,e,n,r){var i=s(t)?t.message:t,a="Error",o=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return o&&(a=o[1],i=o[2]),ae({exception:{values:[{type:a,value:i}]}},e,n,r)}(a,o,u,l):ae(te(r,d||a,void 0,i,!1),o,u,l);h.level="error",oe(n,d,h,"onerror")}}}))}function ie(){zt("unhandledrejection",(function(t){var e=se(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(ne)){var a=t;try{"reason"in t?a=t.reason:"detail"in t&&"reason"in t.detail&&(a=t.detail.reason)}catch(t){}if(gt()||a&&a.__sentry_own_request__)return!0;var o=l(a)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(a)}]}}:te(r,a,void 0,i,!0);o.level="error",oe(n,a,o,"onunhandledrejection")}}))}function ae(t,e,n,r){var i=t.exception=t.exception||{},a=i.values=i.values||[],o=a[0]=a[0]||{},s=o.stacktrace=o.stacktrace||{},u=s.frames=s.frames||[],l=isNaN(parseInt(r,10))?void 0:r,d=isNaN(parseInt(n,10))?void 0:n,h=c(e)&&e.length>0?e:function(){try{return E.document.location.href}catch(t){return""}}();return 0===u.length&&u.push({colno:l,filename:h,function:"?",in_app:!0,lineno:d}),t}function oe(t,e,n,r){V(n,{handled:!1,type:r}),t.captureEvent(n,{originalException:e})}function se(){var t=ft(),e=t.getClient(),n=e&&e.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1};return[t,n.stackParser,n.attachStacktrace]}ne.__initStatic();var ue=["fatal","error","warning","log","info","debug"];function ce(t){return"warn"===t?"warning":ue.includes(t)?t:"log"}function le(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var de="Breadcrumbs",he=function(){e.__initStatic=function(){this.id=de};var t=e.prototype;function e(t){e.prototype.__init.call(this),this.options=k({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){var t;this.options.console&&zt("console",fe),this.options.dom&&zt("dom",(t=this.options.dom,function(e){var n,r="object"==typeof t?t.serializeAttribute:void 0,i="object"==typeof t&&"number"==typeof t.maxStringLength?t.maxStringLength:void 0;i&&i>1024&&(i=1024),"string"==typeof r&&(r=[r]);try{var a=e.event;n=function(t){return t&&!!t.target}(a)?C(a.target,{keyAttrs:r,maxStringLength:i}):C(a,{keyAttrs:r,maxStringLength:i})}catch(t){n=""}0!==n.length&&ft().addBreadcrumb({category:"ui."+e.name,message:n},{event:e.event,name:e.name,global:e.global})})),this.options.xhr&&zt("xhr",pe),this.options.fetch&&zt("fetch",me),this.options.history&&zt("history",ve)},t.addSentryBreadcrumb=function(t){this.options.sentry&&ft().addBreadcrumb({category:"sentry."+("transaction"===t.type?"transaction":"event"),event_id:t.event_id,level:t.level,message:K(t)},{event:t})},e}();function fe(t){for(var e=0;e=e)return i;var a=Vt(t,n[r]);return ge(t,e,n[r],r,[a].concat(i))}_e.__initStatic();var ye=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="HttpContext"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(){ut((function(e){if(ft().getIntegration(t)){if(!vt.navigator&&!vt.location&&!vt.document)return e;var n=e.request&&e.request.url||vt.location&&vt.location.href,r=(vt.document||{}).referrer,i=(vt.navigator||{}).userAgent,a=k({},e.request&&e.request.headers,r&&{Referer:r},i&&{"User-Agent":i}),o=k({},e.request,n&&{url:n},{headers:a});return k({},e,{request:o})}return e}))},t}();function be(t,e){return be=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},be(t,e)}function we(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,be(t,e)}function ke(t){return ke=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ke(t)}function Se(t,e,n){return Se=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}()?Reflect.construct.bind():function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&be(i,n.prototype),i},Se.apply(null,arguments)}function xe(t){var e="function"==typeof Map?new Map:void 0;return xe=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return Se(t,arguments,ke(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),be(r,t)},xe(t)}function Ee(t,e,n,r,i,a,o){try{var s=t[a](o),u=s.value}catch(t){return void n(t)}s.done?e(u):Promise.resolve(u).then(r,i)}function Te(t){return function(){var e=this,n=arguments;return new Promise((function(r,i){var a=t.apply(e,n);function o(t){Ee(a,r,i,o,s,"next",t)}function s(t){Ee(a,r,i,o,s,"throw",t)}o(void 0)}))}}function Ce(t){return Ce="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ce(t)}function Ie(t,e){for(var n=0;n0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(u,c),void 0===e.type&&function(t,e){var n,r=x.n2._sentryDebugIds;if(r){var i=De.get(e);i?n=i:(n=new Map,De.set(e,n));var a=Object.keys(r).reduce((function(t,i){var a,o=n.get(i);o?a=o:(a=e(i),n.set(i,a));for(var s=a.length-1;s>=0;s--){var u=a[s];if(u.filename){t[u.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=a[t.filename])}))}))}catch(t){}}}(u,t.stackParser);var l=r;n.captureContext&&(l=ot.clone(l).update(n.captureContext));var d=nt(u);if(l){if(l.getAttachments){var h=[].concat(n.attachments||[],l.getAttachments());h.length&&(n.attachments=h)}d=l.applyToEvent(u,n)}return d.then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof a&&a>0?function(t,e,n){if(!t)return null;var r=k({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return k({},t,t.data&&{data:Gt(t.data,e,n)})}))},t.user&&{user:Gt(t.user,e,n)},t.contexts&&{contexts:Gt(t.contexts,e,n)},t.extra&&{extra:Gt(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=Gt(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){return t.data&&(t.data=Gt(t.data,e,n)),t}))),r}(t,a,s):t}))}var De=new WeakMap,Me=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function Ne(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,a=t.port,o=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(a?":"+a:"")+"/"+(r?r+"/":r)+o}function ze(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function Ue(t){var e="string"==typeof t?function(t){var e=Me.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],a=n[2],o=void 0===a?"":a,s=n[3],u=n[4],c=void 0===u?"":u,l="",d=n[5],h=d.split("/");if(h.length>1&&(l=h.slice(0,-1).join("/"),d=h.pop()),d){var f=d.match(/^\d+/);f&&(d=f[0])}return ze({host:s,pass:o,path:l,projectId:d,port:c,protocol:r,publicKey:i})}console.error("Invalid Sentry Dsn: "+t)}(t):ze(t);if(e)return e}function Pe(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return je(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?je(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function je(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function $e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n-1?t.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,"$1\\$2"):t}var En=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,Tn=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,Cn=/^(data:)([^,]*),(.*)/i;function In(t,e){return(t||"").replace(En,(function(t,n,r,i,a,o){var s,u=r||a||o,c=n||i||"";if(!u)return t;if(!Tn.test(u))return"url("+c+u+c+")";if(Cn.test(u))return"url("+c+u+c+")";if("/"===u[0])return"url("+c+(((s=e).indexOf("//")>-1?s.split("/").slice(0,3).join("/"):s.split("/")[0]).split("?")[0]+u)+c+")";var l=e.split("/"),d=u.split("/");l.pop();for(var h,f=Je(d);!(h=f()).done;){var p=h.value;"."!==p&&(".."===p?l.pop():l.push(p))}return"url("+c+l.join("/")+c+")"}))}var An,Rn,On,Ln,Dn,Mn,Nn=/^[^ \t\n\r\u000c]+/,zn=/^[, \t\n\r\u000c]+/;function Un(t,e){if(!e||""===e.trim())return e;var n=t.createElement("a");return n.href=e,n.href}function Pn(t){return Boolean("svg"===t.tagName||t.ownerSVGElement)}function jn(){var t=document.createElement("a");return t.href="",t.href}function Fn(t,e,n,r,i,a,o,s){if(!i)return i;var u=r.toLowerCase(),c=n.toLowerCase();return"src"===u||"href"===u||"xlink:href"===u&&"#"!==i[0]?Un(t,i):"background"!==u||"table"!==c&&"td"!==c&&"th"!==c?"srcset"===u?function(t,e){if(""===e.trim())return e;var n=0;function r(t){var r,i=t.exec(e.substring(n));return i?(r=i[0],n+=r.length,r):""}for(var i=[];r(zn),!(n>=e.length);){var a=r(Nn);if(","===a.slice(-1))a=Un(t,a.substring(0,a.length-1)),i.push(a);else{var o="";a=Un(t,a);for(var s=!1;;){var u=e.charAt(n);if(""===u){i.push((a+o).trim());break}if(s)")"===u&&(s=!1);else{if(","===u){n+=1,i.push((a+o).trim());break}"("===u&&(s=!0)}o+=u,n+=1}}}return i.join(", ")}(t,i):"style"===u?In(i,jn()):"object"===c&&"data"===u?Un(t,i):a&&function(t,e,n,r){return(!r||!t.matches(r))&&(["placeholder","title","aria-label"].indexOf(e)>-1||"input"===n&&"value"===e&&t.hasAttribute("type")&&["submit","button"].indexOf(t.getAttribute("type").toLowerCase())>-1)}(e,u,c,o)?s?s(i):wn(i):i:Un(t,i)}function Bn(t,e,n,r,i){if(!t)return!1;if(t.nodeType!==t.ELEMENT_NODE)return Bn(t.parentNode,e,n,r,i);if(r&&(t.matches(r)||t.closest(r)))return!1;if(i)return!0;if("string"==typeof e){if(t.classList.contains(e))return!0}else for(var a=0;ae?(r&&(clearTimeout(r),r=null),i=o,t.apply(u,c)):r||!1===n.trailing||(r=setTimeout((function(){i=!1===n.leading?0:Date.now(),r=null,t.apply(u,c)}),s))}}function Vn(t,e,n,r,i){void 0===i&&(i=window);var a=i.Object.getOwnPropertyDescriptor(t,e);return i.Object.defineProperty(t,e,r?n:{set:function(t){var e=this;setTimeout((function(){n.set.call(e,t)}),0),a&&a.set&&a.set.call(this,t)}}),function(){return Vn(t,e,a||{},!0)}}function Xn(t,e,n){try{if(!(e in t))return function(){};var r=t[e],i=n(r);return"function"==typeof i&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:r}})),t[e]=i,function(){t[e]=r}}catch(t){return function(){}}}function Jn(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function $n(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Qn(t,e,n,r){if(!t)return!1;if(t.nodeType===t.ELEMENT_NODE){var i=!1,a=r&&t.matches(r);return"string"==typeof e?i=void 0!==t.closest?!a&&null!==t.closest("."+e):!a&&t.classList.contains(e):!a&&t.classList.forEach((function(t){e.test(t)&&(i=!0)})),!i&&n&&(i=t.matches(n)),!a&&i||Qn(t.parentNode,e,n,r)}return t.nodeType,t.TEXT_NODE,Qn(t.parentNode,e,n,r)}function tr(t){return"__sn"in t&&t.__sn.id===bn}function er(t,e){if(ln(t))return!1;var n=e.getId(t);return!e.has(n)||(!t.parentNode||t.parentNode.nodeType!==t.DOCUMENT_NODE)&&(!t.parentNode||er(t.parentNode,e))}function nr(t){return Boolean(t.changedTouches)}function rr(t){return"__sn"in t&&t.__sn.type===Qe.Element&&"iframe"===t.__sn.tagName}function ir(t){return Boolean(null==t?void 0:t.shadowRoot)}function ar(t){return"__ln"in t}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Kn=new Proxy(Kn,{get:function(t,e,n){return"map"===e&&console.error(Gn),Reflect.get(t,e,n)}}));var or=function(){function t(){this.length=0,this.head=null}var e=t.prototype;return e.get=function(t){if(t>=this.length)throw new Error("Position outside of list range");for(var e=this.head,n=0;n=0;m--){var v=n.get(m);if(v){var _=t.mirror.getId(v.value.parentNode),g=r(v.value);if(-1!==_&&-1!==g){h=v;break}}}if(!h){for(;n.head;)n.removeNode(n.head.value);break}d=h.previous,n.removeNode(h.value),i(h.value)}var y={texts:t.texts.map((function(e){return{id:t.mirror.getId(e.node),value:e.value}})).filter((function(e){return t.mirror.has(e.id)})),attributes:t.attributes.map((function(e){return{id:t.mirror.getId(e.node),attributes:e.attributes}})).filter((function(e){return t.mirror.has(e.id)})),removes:t.removes,adds:e};(y.texts.length||y.attributes.length||y.removes.length||y.adds.length)&&(t.texts=[],t.attributes=[],t.removes=[],t.addedSet=new Set,t.movedSet=new Set,t.droppedSet=new Set,t.movedMap={},t.mutationCb(y))}},this.processMutation=function(e){if(!tr(e.target))switch(e.type){case"characterData":var n=e.target.textContent;Qn(e.target,t.blockClass,t.blockSelector,t.unblockSelector)||n===e.oldValue||t.texts.push({value:Bn(e.target,t.maskTextClass,t.maskTextSelector,t.unmaskTextSelector,t.maskAllText)&&n?t.maskTextFn?t.maskTextFn(n):n.replace(/[\S]/g,"*"):n,node:e.target});break;case"attributes":var r=e.target,i=r.getAttribute(e.attributeName);if("value"===e.attributeName&&(i=hn({input:r,maskInputSelector:t.maskInputSelector,unmaskInputSelector:t.unmaskInputSelector,maskInputOptions:t.maskInputOptions,tagName:r.tagName,type:r.getAttribute("type"),value:i,maskInputFn:t.maskInputFn})),Qn(e.target,t.blockClass,t.blockSelector,t.unblockSelector)||i===e.oldValue)return;var a=t.attributes.find((function(t){return t.node===e.target}));if(a||(a={node:e.target,attributes:{}},t.attributes.push(a)),"type"===e.attributeName&&"INPUT"===r.tagName&&"password"===(e.oldValue||"").toLowerCase()&&r.setAttribute("data-rr-is-password","true"),"style"===e.attributeName){var o=t.doc.createElement("span");e.oldValue&&o.setAttribute("style",e.oldValue),void 0!==a.attributes.style&&null!==a.attributes.style||(a.attributes.style={});try{for(var s=a.attributes.style,u=0,c=Array.from(r.style);u>2],i+=Cr[(3&n[e])<<4|n[e+1]>>4],i+=Cr[(15&n[e+1])<<2|n[e+2]>>6],i+=Cr[63&n[e+2]];return r%3==2?i=i.substring(0,i.length-1)+"=":r%3==1&&(i=i.substring(0,i.length-2)+"=="),i}(t);return{rr_type:r,base64:i}}return t instanceof DataView?{rr_type:t.constructor.name,args:[Lr(t.buffer,e,n),t.byteOffset,t.byteLength]}:t instanceof HTMLImageElement?{rr_type:t.constructor.name,src:t.src}:t instanceof ImageData?{rr_type:t.constructor.name,args:[Lr(t.data,e,n),t.width,t.height]}:Mr(t,e)||"object"==typeof t?{rr_type:t.constructor.name,index:Or(t,e,n)}:t}var Dr=function(t,e,n){return[].concat(t).map((function(t){return Lr(t,e,n)}))},Mr=function(t,e){var n=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter((function(t){return"function"==typeof e[t]}));return Boolean(n.find((function(n){return t instanceof e[n]})))};function Nr(t,e,n,r,i,a,o,s){for(var u,c=[],l=function(){var l=u.value;try{if("function"!=typeof t[l])return"continue";var d=Xn(t,l,(function(u){return function(){for(var c=arguments.length,d=new Array(c),h=0;h1?a-1:0),s=1;s=i,s=r&&t.timestamp-$.timestamp>r;(o||s)&&Ur(!0)}};var nt=function(t){zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.Mutation},t)}))},rt=function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.Scroll},t)}))},it=function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.CanvasMutation},t)}))},at=new Er({mutationCb:nt}),ot=new Pr({recordCanvas:F,mutationCb:it,win:window,blockClass:o,blockSelector:u,unblockSelector:l,mirror:Fr}),st=new Tr({mutationCb:nt,scrollCb:rt,bypassOptions:{onMutation:X,blockClass:o,blockSelector:u,unblockSelector:l,maskTextClass:v,maskTextSelector:g,unmaskTextSelector:k,maskInputSelector:b,unmaskInputSelector:x,inlineStylesheet:T,maskAllText:I,maskInputOptions:Q,maskTextFn:D,maskInputFn:L,recordCanvas:F,inlineImages:G,sampling:U,slimDOMOptions:tt,iframeManager:at,canvasManager:ot},mirror:Fr});Ur=function(t){var e,n,r,i;void 0===t&&(t=!1),zr(jr({type:An.Meta,data:{href:window.location.href,width:$n(),height:Jn()}}),t),pr.forEach((function(t){return t.lock()}));var a=function(t,e){var n=e||{},r=n.blockClass,i=n.blockSelector,a=n.unblockSelector,o=n.maskTextClass,s=n.maskTextSelector,u=n.unmaskTextSelector,c=n.inlineStylesheet,l=n.inlineImages,d=n.recordCanvas,h=n.maskInputSelector,f=n.unmaskInputSelector,p=n.maskAllText,m=n.maskAllInputs,v=void 0!==m&&m,_=n.slimDOM,g=void 0!==_&&_,y=n.keepIframeSrcFn,b={};return[qn(t,{doc:t,map:b,blockClass:void 0===r?"rr-block":r,blockSelector:void 0===i?null:i,unblockSelector:void 0===a?null:a,maskTextClass:void 0===o?"rr-mask":o,maskTextSelector:void 0===s?null:s,unmaskTextSelector:void 0===u?null:u,skipChild:!1,inlineStylesheet:void 0===c||c,maskInputSelector:void 0===h?null:h,unmaskInputSelector:void 0===f?null:f,maskAllText:void 0!==p&&p,maskInputOptions:!0===v?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0}:!1===v?{}:v,maskTextFn:n.maskTextFn,maskInputFn:n.maskInputFn,slimDOMOptions:!0===g||"all"===g?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===g,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===g?{}:g,dataURLOptions:n.dataURLOptions,inlineImages:void 0!==l&&l,recordCanvas:void 0!==d&&d,preserveWhiteSpace:n.preserveWhiteSpace,onSerialize:n.onSerialize,onIframeLoad:n.onIframeLoad,iframeLoadTimeout:n.iframeLoadTimeout,keepIframeSrcFn:void 0===y?function(){return!1}:y}),b]}(document,{blockClass:o,blockSelector:u,unblockSelector:l,maskTextClass:v,maskTextSelector:g,unmaskTextSelector:k,maskInputSelector:b,unmaskInputSelector:x,inlineStylesheet:T,maskAllText:I,maskAllInputs:Q,maskTextFn:D,slimDOM:tt,recordCanvas:F,inlineImages:G,onSerialize:function(t){rr(t)&&at.addIframe(t),ir(t)&&st.addShadowRoot(t.shadowRoot,document)},onIframeLoad:function(t,e){at.attachIframe(t,e),st.observeAttachShadow(t)},keepIframeSrcFn:V}),s=a[0],c=a[1];if(!s)return console.warn("Failed to snapshot the document");Fr.map=c,zr(jr({type:An.FullSnapshot,data:{node:s,initialOffset:{left:void 0!==window.pageXOffset?window.pageXOffset:(null===document||void 0===document?void 0:document.documentElement.scrollLeft)||(null===(n=null===(e=null===document||void 0===document?void 0:document.body)||void 0===e?void 0:e.parentElement)||void 0===n?void 0:n.scrollLeft)||(null===document||void 0===document?void 0:document.body.scrollLeft)||0,top:void 0!==window.pageYOffset?window.pageYOffset:(null===document||void 0===document?void 0:document.documentElement.scrollTop)||(null===(i=null===(r=null===document||void 0===document?void 0:document.body)||void 0===r?void 0:r.parentElement)||void 0===i?void 0:i.scrollTop)||(null===document||void 0===document?void 0:document.body.scrollTop)||0}}})),pr.forEach((function(t){return t.unlock()}))};try{var ut=[];ut.push(Zn("DOMContentLoaded",(function(){zr(jr({type:An.DomContentLoaded,data:{}}))})));var ct=function(t){var e;return fr(kr)({onMutation:X,mutationCb:nt,mousemoveCb:function(t,e){return zr(jr({type:An.IncrementalSnapshot,data:{source:e,positions:t}}))},mouseInteractionCb:function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.MouseInteraction},t)}))},scrollCb:rt,viewportResizeCb:function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.ViewportResize},t)}))},inputCb:function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.Input},t)}))},mediaInteractionCb:function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.MediaInteraction},t)}))},styleSheetRuleCb:function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.StyleSheetRule},t)}))},styleDeclarationCb:function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.StyleDeclaration},t)}))},canvasMutationCb:it,fontCb:function(t){return zr(jr({type:An.IncrementalSnapshot,data:Object.assign({source:Rn.Font},t)}))},blockClass:o,ignoreClass:h,ignoreSelector:p,maskTextClass:v,maskTextSelector:g,unmaskTextSelector:k,maskInputSelector:b,unmaskInputSelector:x,maskInputOptions:Q,inlineStylesheet:T,sampling:U,recordCanvas:F,inlineImages:G,userTriggeredOnInput:H,collectFonts:W,doc:t,maskAllText:I,maskInputFn:L,maskTextFn:D,blockSelector:u,unblockSelector:l,slimDOMOptions:tt,mirror:Fr,iframeManager:at,shadowDomManager:st,canvasManager:ot,plugins:(null===(e=null==K?void 0:K.filter((function(t){return t.observer})))||void 0===e?void 0:e.map((function(t){return{observer:t.observer,options:t.options,callback:function(e){return zr(jr({type:An.Plugin,data:{plugin:t.name,payload:e}}))}}})))||[]},M)};at.addLoadListener((function(t){try{ut.push(ct(t.contentDocument))}catch(t){console.warn(t)}}));var lt=function(){Ur(),ut.push(ct(document))};return"interactive"===document.readyState||"complete"===document.readyState?lt():ut.push(Zn("load",(function(){zr(jr({type:An.Load,data:{}})),lt()}),window)),function(){ut.forEach((function(t){return t()}))}}catch(t){console.warn(t)}}function Hr(t,e){"sentry.transaction"!==e.category&&(["ui.click","ui.input"].includes(e.category)?t.triggerUserActivity():t.checkAndHandleExpiredSession(),t.addUpdate((function(){return t.throttledAddEvent({type:An.Custom,timestamp:1e3*(e.timestamp||0),data:{tag:"breadcrumb",payload:Gt(e,10,1e3)}}),"console"===e.category})))}Br.addCustomEvent=function(t,e){if(!zr)throw new Error("please add custom event after start recording");zr(jr({type:An.Custom,data:{tag:t,payload:e}}))},Br.freezePage=function(){pr.forEach((function(t){return t.freeze()}))},Br.takeFullSnapshot=function(t){if(!Ur)throw new Error("please take full snapshot after start recording");Ur(t)},Br.mirror=Fr;var qr;function Wr(t){var e=Zr(t);return e&&e instanceof Element&&e.closest("button,a")||e}function Zr(t){return function(t){return"object"==typeof t&&!!t&&"target"in t}(t)?t.target:t}var Gr,Kr=function(){var t=e.prototype;function e(t,n,r){void 0===r&&(r=Hr),e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),this._timeout=n.timeout/1e3,this._multiClickTimeout=n.multiClickTimeout/1e3,this._threshold=n.threshold/1e3,this._scollTimeout=n.scrollTimeout/1e3,this._replay=t,this._ignoreSelector=n.ignoreSelector,this._addBreadcrumbEvent=r}return t.__init=function(){this._lastMutation=0},t.__init2=function(){this._lastScroll=0},t.__init3=function(){this._clicks=[]},t.addListeners=function(){var t,e=this,n=function(){e._lastScroll=Vr()},r=(t=function(){e._lastMutation=Vr()},qr||(qr=[],A(tn,"open",(function(t){return function(){if(qr)try{qr.forEach((function(t){return t()}))}catch(t){}for(var e=arguments.length,n=new Array(e),r=0;r-1&&qr.splice(e,1)}),i=function(t){if(t.target){var n=Wr(t);n&&e._handleMultiClick(n)}},a=new MutationObserver((function(){e._lastMutation=Vr()}));a.observe(tn.document.documentElement,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),tn.addEventListener("scroll",n,{passive:!0}),tn.addEventListener("click",i,{passive:!0}),this._teardown=function(){tn.removeEventListener("scroll",n),tn.removeEventListener("click",i),r(),a.disconnect(),e._clicks=[],e._lastMutation=0,e._lastScroll=0}},t.removeListeners=function(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)},t.handleClick=function(t,e){if(!function(t,e){return!Yr.includes(t.tagName)||("INPUT"===t.tagName&&!["submit","button"].includes(t.getAttribute("type")||"")||(!("A"!==t.tagName||!(t.hasAttribute("download")||t.hasAttribute("target")&&"_self"!==t.getAttribute("target")))||!(!e||!t.matches(e))))}(e,this._ignoreSelector)&&function(t){return!(!t.data||"number"!=typeof t.data.nodeId||!t.timestamp)}(t)&&!this._getClick(e)){var n={timestamp:t.timestamp,clickBreadcrumb:t,clickCount:0,node:e};this._clicks.push(n),1===this._clicks.length&&this._scheduleCheckClicks()}},t._handleMultiClick=function(t){var e=this._getClick(t);e&&e.clickCount++},t._getClick=function(t){var e=this,n=Vr();return this._clicks.find((function(r){return r.node===t&&n-r.timestamp=t._multiClickTimeout||r.timestamp+t._timeout<=n)&&e.push(r)}));for(var r=0,i=e;r1){var l={type:"default",message:o.message,timestamp:o.timestamp,category:"ui.multiClick",data:k({},o.data,{url:tn.location.href,route:e.getCurrentRoute(),clickCount:a,metric:!0})};this._addBreadcrumbEvent(e,l)}},t._scheduleCheckClicks=function(){var t=this;this._checkClickTimeout=setTimeout((function(){return t._checkClicks()}),1e3)},e}(),Yr=["A","BUTTON","INPUT"];function Vr(){return Date.now()/1e3}function Xr(t){return k({timestamp:Date.now()/1e3,type:"default"},t)}!function(t){t[t.Document=0]="Document",t[t.DocumentType=1]="DocumentType",t[t.Element=2]="Element",t[t.Text=3]="Text",t[t.CDATA=4]="CDATA",t[t.Comment=5]="Comment"}(Gr||(Gr={}));var Jr=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled"]);function $r(t){var e={};for(var n in t)if(Jr.has(n)){var r=n;"data-testid"!==n&&"data-test-id"!==n||(r="testId"),e[r]=t[n]}return e}function Qr(t,e){var n=t&&"__sn"in t&&t.__sn.type===Gr.Element?t.__sn:null;return{message:e,data:n?{nodeId:n.id,node:{id:n.id,tagName:n.tagName,textContent:t?Array.from(t.childNodes).map((function(t){return"__sn"in t&&t.__sn.type===Gr.Text&&t.__sn.textContent})).filter(Boolean).map((function(t){return t.trim()})).join(""):"",attributes:$r(n.attributes)}}:{}}}var ti=["name","type","startTime","transferSize","duration"];function ei(t){return function(e){return ti.every((function(n){return t[n]===e[n]}))}}function ni(t){return t>9999999999?t:1e3*t}var ri=function(){var t=e.prototype;function e(){e.prototype.__init.call(this),this.events=[]}return t.__init=function(){this._totalSize=0},t.destroy=function(){this.events=[]},t.addEvent=function(){var t=Te(Oe().mark((function t(e){var n;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=JSON.stringify(e).length,this._totalSize+=n,!(this._totalSize>cn)){t.next=4;break}throw new si;case 4:this.events.push(e);case 5:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),t.finish=function(){var t=this;return new Promise((function(e){var n=t.events;t.clear(),e(JSON.stringify(n))}))},t.clear=function(){this.events=[],this._totalSize=0},t.getEarliestTimestamp=function(){var t=this.events.map((function(t){return t.timestamp})).sort()[0];return t?ni(t):null},Ae(e,[{key:"hasEvents",get:function(){return this.events.length>0}},{key:"type",get:function(){return"sync"}}]),e}(),ii=function(){function t(t){this._worker=t,this._id=0}var e=t.prototype;return e.ensureReady=function(){var t=this;return this._ensureReadyPromise||(this._ensureReadyPromise=new Promise((function(e,n){t._worker.addEventListener("message",(function(t){t.data.success?e():n()}),{once:!0}),t._worker.addEventListener("error",(function(t){n(t)}),{once:!0})}))),this._ensureReadyPromise},e.destroy=function(){this._worker.terminate()},e.postMessage=function(t,e){var n=this,r=this._getAndIncrementId();return new Promise((function(i,a){n._worker.addEventListener("message",(function e(o){var s=o.data;s.method===t&&s.id===r&&(n._worker.removeEventListener("message",e),s.success?i(s.response):a(new Error("Error in compression worker")))})),n._worker.postMessage({id:r,method:t,arg:e})}))},e._getAndIncrementId=function(){return this._id++},t}(),ai=function(){var t=e.prototype;function e(t){e.prototype.__init.call(this),this._worker=new ii(t),this._earliestTimestamp=null}return t.__init=function(){this._totalSize=0},t.ensureReady=function(){return this._worker.ensureReady()},t.destroy=function(){this._worker.destroy()},t.addEvent=function(t){var e=ni(t.timestamp);(!this._earliestTimestamp||ecn?Promise.reject(new si):this._sendEventToWorker(n)},t.finish=function(){return this._finishRequest()},t.clear=function(){this._earliestTimestamp=null,this._totalSize=0,this._worker.postMessage("clear")},t.getEarliestTimestamp=function(){return this._earliestTimestamp},t._sendEventToWorker=function(t){return this._worker.postMessage("addEvent",t)},t._finishRequest=function(){var t=Te(Oe().mark((function t(){var e;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this._worker.postMessage("finish");case 2:return e=t.sent,this._earliestTimestamp=null,this._totalSize=0,t.abrupt("return",e);case 6:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),Ae(e,[{key:"hasEvents",get:function(){return!!this._earliestTimestamp}},{key:"type",get:function(){return"worker"}}]),e}(),oi=function(){function t(t){this._fallback=new ri,this._compression=new ai(t),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}var e=t.prototype;return e.destroy=function(){this._fallback.destroy(),this._compression.destroy()},e.clear=function(){return this._used.clear()},e.getEarliestTimestamp=function(){return this._used.getEarliestTimestamp()},e.addEvent=function(t){return this._used.addEvent(t)},e.finish=function(){var t=Te(Oe().mark((function t(){return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.ensureWorkerIsLoaded();case 2:return t.abrupt("return",this._used.finish());case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),e.ensureWorkerIsLoaded=function(){return this._ensureWorkerIsLoadedPromise},e._ensureWorkerIsLoaded=function(){var t=Te(Oe().mark((function t(){return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this._compression.ensureReady();case 3:t.next=9;break;case 5:return t.prev=5,t.t0=t.catch(0),t.abrupt("return");case 9:return t.next=11,this._switchToCompressionWorker();case 11:case"end":return t.stop()}}),t,this,[[0,5]])})));return function(){return t.apply(this,arguments)}}(),e._switchToCompressionWorker=function(){var t=Te(Oe().mark((function t(){var e,n,r,i,a;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:for(e=this._fallback.events,n=[],r=Je(e);!(i=r()).done;)a=i.value,n.push(this._compression.addEvent(a));return this._used=this._compression,t.prev=4,t.next=7,Promise.all(n);case 7:t.next=12;break;case 9:t.prev=9,t.t0=t.catch(4);case 12:case"end":return t.stop()}}),t,this,[[4,9]])})));return function(){return t.apply(this,arguments)}}(),Ae(t,[{key:"type",get:function(){return this._used.type}},{key:"hasEvents",get:function(){return this._used.hasEvents}}]),t}();var si=function(t){function e(){return t.call(this,"Event buffer exceeded maximum size of "+cn+".")||this}return we(e,t),e}(xe(Error));function ui(t,e,n){return void 0===n&&(n=+new Date),null===t||void 0===e||e<0||0!==e&&t+e<=n}function ci(t,e,n){return void 0===n&&(n=+new Date),ui(t.started,e.maxSessionLife,n)||ui(t.lastActivity,e.sessionIdleExpire,n)}function li(t){return void 0!==t&&Math.random()=300)||(yi(n)&&n.contexts&&n.contexts.trace&&n.contexts.trace.trace_id?t.getContext().traceIds.add(n.contexts.trace.trace_id):gi(n)&&(n.event_id&&t.getContext().errorIds.add(n.event_id),"buffer"===t.recordingMode&&n.tags&&n.tags.replayId&&setTimeout((function(){t.sendBufferedReplayOrFlush()}))))}}}function wi(t,e){return e.map((function(e){var n=e.type,r=e.start,i=e.end,a=e.name,o=e.data,s=t.throttledAddEvent({type:An.Custom,timestamp:r,data:{tag:"performanceSpan",payload:{op:n,description:a,startTimestamp:r,endTimestamp:i,data:o}}});return"string"==typeof s?Promise.resolve(null):s}))}function ki(t,e){t.isEnabled()&&null!==e&&(function(t){var e=ft().getClient(),n=e&&e.getDsn();return!!n&&t.includes(n.host)}(e.name)||t.addUpdate((function(){return wi(t,[e]),!0})))}var Si=10,xi=11,Ei=12,Ti=13,Ci=14,Ii=15,Ai=20,Ri=21,Oi=22,Li=23,Di=["true","false","null"];function Mi(t,e,n){var r=t[t.length-1],i=e[n];if(!/\s/.test(i))if('"'!==i||Ni(e,n))switch(i){case"{":!function(t,e){e&&e!==Ti?(e===Ri&&t.push(Si),e===Ai&&t.push(Si)):t.push(Si)}(t,r);break;case"[":!function(t,e){e?e===Ti?(t.push(Ai),t.push(Ri)):(e===Ri&&(t.push(Ai),t.push(Ri)),e===Ai&&(t.push(Ai),t.push(Ri))):(t.push(Ai),t.push(Ri))}(t,r);break;case":":!function(t,e){e===xi&&(t.pop(),t.push(Ti))}(t,r);break;case",":!function(t,e){if(e!==Ti)return e===Ii?(t.pop(),void t.pop()):void(e!==Ri&&e===Li&&t.pop());t.pop()}(t,r);break;case"}":!function(t,e){e===Si&&t.pop(),e===Ti&&(t.pop(),t.pop()),e===Ii&&(t.pop(),t.pop(),t.pop()),t[t.length-1]===Ti&&t.push(Ii),t[t.length-1]===Ri&&t.push(Li)}(t,r);break;case"]":!function(t,e){e===Ai&&t.pop(),e===Ri&&(t.pop(),t.pop()),e===Li&&(t.pop(),t.pop(),t.pop()),t[t.length-1]===Ti&&t.push(Ii),t[t.length-1]===Ri&&t.push(Li)}(t,r)}else!function(t,e){e===Ci?(t.pop(),t.push(Ii)):e===Oi?(t.pop(),t.push(Li)):e!==Ti?e!==Ri?e!==Si?e===Ei&&(t.pop(),t.push(xi)):t.push(Ei):t.push(Oi):t.push(Ci)}(t,r)}function Ni(t,e){return"\\"===t[e-1]&&!Ni(t,e-1)}function zi(t){return function(t,e){if(!e.length)return t;var n=t,r=e.length-1;n=function(t,e){switch(e){case Si:return t+'"~~":"~~"';case xi:return t+':"~~"';case Ei:return t+'~~":"~~"';case Ti:return function(t){var e=t.lastIndexOf(":"),n=t.slice(e+1);return Di.includes(n.trim())?t+',"~~":"~~"':t.slice(0,e+1)+'"~~"'}(t);case Ci:return t+'~~"';case Ii:return t+',"~~":"~~"';case Ai:return t+'"~~"';case Ri:return function(t){var e=function(t){for(var e=t.length-1;e>=0;e--){var n=t[e];if(","===n||"["===n)return e}return-1}(t);if(e>-1){var n=t.slice(e+1);return Di.includes(n.trim())?t+',"~~"':t.slice(0,e+1)+'"~~"'}return t}(t);case Oi:return t+'~~"';case Li:return t+',"~~"'}return t}(n,e[r]);for(var i=r;i>=0;i--)switch(e[i]){case Si:n+="}";break;case Ai:n+="]"}return n}(t,function(t){for(var e=[],n=0;nsn;if(n=(e=t)[0],r=e[e.length-1],"["===n&&"]"===r||"{"===n&&"}"===r)try{var a=i?zi(t.slice(0,sn)):t;return{body:JSON.parse(a),warnings:i?["JSON_TRUNCATED"]:[]}}catch(e){return{body:i?t.slice(0,sn)+"…":t,warnings:i?["INVALID_JSON","TEXT_TRUNCATED"]:["INVALID_JSON"]}}return{body:i?t.slice(0,sn)+"…":t,warnings:i?["TEXT_TRUNCATED"]:[]}}(n),a=i.body,o=i.warnings;return r.body=a,o.length>0&&(r._meta={warnings:o}),r}}function qi(t,e){return Object.keys(t).reduce((function(n,r){var i=r.toLowerCase();return e.includes(i)&&t[r]&&(n[i]=t[r]),n}),{})}function Wi(t){return new URLSearchParams(t).toString()}function Zi(t,e){var n=function(t,e){if(void 0===e&&(e=tn.document.baseURI),t.startsWith("http://")||t.startsWith("https://")||t.startsWith(tn.location.origin))return t;var n=new URL(t,e);if(n.origin!==new URL(e).origin)return t;var r=n.href;return!t.endsWith("/")&&r.endsWith("/")?r.slice(0,-1):r}(t);return _(n,e)}function Gi(){return(Gi=Te(Oe().mark((function t(e,n,r){var i,a;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,Ki(e,n,r);case 3:i=t.sent,a=Fi("resource.fetch",i),ki(r.replay,a),t.next=11;break;case 8:t.prev=8,t.t0=t.catch(0);case 11:case"end":return t.stop()}}),t,null,[[0,8]])})))).apply(this,arguments)}function Ki(t,e,n){return Yi.apply(this,arguments)}function Yi(){return(Yi=Te(Oe().mark((function t(e,n,r){var i,a,o,s,u,c,l,d,h,f,p,m;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=n.startTimestamp,a=n.endTimestamp,o=e.data,s=o.url,u=o.method,c=o.status_code,l=void 0===c?0:c,d=o.request_body_size,h=o.response_body_size,f=Zi(s,r.networkDetailAllowUrls),p=f?Vi(r,n.input,d):Bi(d),t.next=6,Xi(f,r,n.response,h);case 6:return m=t.sent,t.abrupt("return",{startTimestamp:i,endTimestamp:a,url:s,method:u,statusCode:l,request:p,response:m});case 8:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function Vi(t,e,n){var r,i,a=t.networkCaptureBodies;return Hi((r=e,i=t.networkRequestHeaders,1===r.length&&"string"!=typeof r[0]?na(r[0],i):2===r.length?na(r[1],i):{}),n,a?ji(ta(e)):void 0)}function Xi(t,e,n,r){return Ji.apply(this,arguments)}function Ji(){return(Ji=Te(Oe().mark((function t(e,n,r,i){var a,o,s,u,c,l,d;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(a=n.networkCaptureBodies,o=n.textEncoder,s=n.networkResponseHeaders,e||void 0===i){t.next=3;break}return t.abrupt("return",Bi(i));case 3:if(u=ea(r.headers,s),a||void 0===i){t.next=6;break}return t.abrupt("return",Hi(u,i,void 0));case 6:return t.prev=6,c=r.clone(),t.next=10,$i(c);case 10:if(l=t.sent,d=l&&l.length&&void 0===i?Ui(l,o):i,e){t.next=14;break}return t.abrupt("return",Bi(d));case 14:if(!a){t.next=16;break}return t.abrupt("return",Hi(u,d,l));case 16:return t.abrupt("return",Hi(u,d,void 0));case 19:return t.prev=19,t.t0=t.catch(6),t.abrupt("return",Hi(u,i,void 0));case 22:case"end":return t.stop()}}),t,null,[[6,19]])})))).apply(this,arguments)}function $i(t){return Qi.apply(this,arguments)}function Qi(){return(Qi=Te(Oe().mark((function t(e){return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.text();case 3:return t.abrupt("return",t.sent);case 6:return t.prev=6,t.t0=t.catch(0),t.abrupt("return",void 0);case 9:case"end":return t.stop()}}),t,null,[[0,6]])})))).apply(this,arguments)}function ta(t){if(void 0===t&&(t=[]),2===t.length&&"object"==typeof t[1])return t[1].body}function ea(t,e){var n={};return e.forEach((function(e){t.get(e)&&(n[e]=t.get(e))})),n}function na(t,e){if(!t)return{};var n=t.headers;return n?n instanceof Headers?ea(n,e):Array.isArray(n)?{}:qi(n,e):{}}function ra(){return(ra=Te(Oe().mark((function t(e,n,r){var i,a;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:try{i=ia(e,n,r),a=Fi("resource.xhr",i),ki(r.replay,a)}catch(t){}case 1:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function ia(t,e,n){var r=e.startTimestamp,i=e.endTimestamp,a=e.input,o=e.xhr,s=t.data,u=s.url,c=s.method,l=s.status_code,d=void 0===l?0:l,h=s.request_body_size,f=s.response_body_size;if(!u)return null;if(!Zi(u,n.networkDetailAllowUrls))return{startTimestamp:r,endTimestamp:i,url:u,method:c,statusCode:d,request:Bi(h),response:Bi(f)};var p=o[Lt],m=p?qi(p.request_headers,n.networkRequestHeaders):{},v=qi(function(t){var e=t.getAllResponseHeaders();return e?e.split("\r\n").reduce((function(t,e){var n=e.split(": "),r=n[0],i=n[1];return t[r.toLowerCase()]=i,t}),{}):{}}(o),n.networkResponseHeaders);return{startTimestamp:r,endTimestamp:i,url:u,method:c,statusCode:d,request:Hi(m,h,n.networkCaptureBodies?ji(a):void 0),response:Hi(v,f,n.networkCaptureBodies?e.xhr.responseText:void 0)}}function aa(t){var e=ft().getClient();try{var n=new TextEncoder,r=t.getOptions(),i={replay:t,textEncoder:n,networkDetailAllowUrls:r.networkDetailAllowUrls,networkCaptureBodies:r.networkCaptureBodies,networkRequestHeaders:r.networkRequestHeaders,networkResponseHeaders:r.networkResponseHeaders};e&&e.on?e.on("beforeAddBreadcrumb",(function(t,e){return function(t,e,n){if(e.data)try{(function(t){return"xhr"===t.category})(e)&&function(t){return t&&t.xhr}(n)&&(function(t,e,n){var r=e.xhr,i=Ui(e.input,n.textEncoder),a=r.getResponseHeader("content-length")?Pi(r.getResponseHeader("content-length")):Ui(r.response,n.textEncoder);void 0!==i&&(t.data.request_body_size=i),void 0!==a&&(t.data.response_body_size=a)}(e,n,t),function(t,e,n){ra.apply(this,arguments)}(e,n,t)),function(t){return"fetch"===t.category}(e)&&function(t){return t&&t.response}(n)&&(function(t,e,n){var r=e.input,i=e.response,a=Ui(ta(r),n.textEncoder),o=i?Pi(i.headers.get("content-length")):void 0;void 0!==a&&(t.data.request_body_size=a),void 0!==o&&(t.data.response_body_size=o)}(e,n,t),function(t,e,n){Gi.apply(this,arguments)}(e,n,t))}catch(t){}}(i,t,e)})):(zt("fetch",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.fetchData,i=t.response;if(!n)return null;var a=r.method;return{type:"resource.fetch",start:e/1e3,end:n/1e3,name:r.url,data:{method:a,statusCode:i&&i.status}}}(e);ki(t,n)}}}(t)),zt("xhr",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.xhr[Lt];if(!e||!n||!r)return null;var i=r.method,a=r.url,o=r.status_code;return void 0===a?null:{type:"resource.xhr",name:a,start:e/1e3,end:n/1e3,data:{method:i,statusCode:o}}}(e);ki(t,n)}}}(t)))}catch(t){}}var oa=null;function sa(t){return!(!t||!t.on)}function ua(t){return ca.apply(this,arguments)}function ca(){return(ca=Te(Oe().mark((function t(e){return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.abrupt("return",Promise.all(wi(e,[(n=tn.performance.memory,void 0,void 0,void 0,void 0,r=n.jsHeapSizeLimit,i=n.totalJSHeapSize,a=n.usedJSHeapSize,o=Date.now()/1e3,{type:"memory",name:"memory",start:o,end:o,data:{memory:{jsHeapSizeLimit:r,totalJSHeapSize:i,usedJSHeapSize:a}}})])));case 4:return t.prev=4,t.t0=t.catch(0),t.abrupt("return",[]);case 7:case"end":return t.stop()}var n,r,i,a,o}),t,null,[[0,4]])})))).apply(this,arguments)}var la=((Ve={resource:function(t){var e=t.entryType,n=t.initiatorType,r=t.name,i=t.responseEnd,a=t.startTime,o=t.decodedBodySize,s=t.encodedBodySize,u=t.responseStatus,c=t.transferSize;return["fetch","xmlhttprequest"].includes(n)?null:{type:e+"."+n,start:ha(a),end:ha(i),name:r,data:{size:c,statusCode:u,decodedBodySize:o,encodedBodySize:s}}},paint:function(t){var e=t.duration,n=t.entryType,r=t.name,i=ha(t.startTime);return{type:n,name:r,start:i,end:i+e,data:void 0}},navigation:function(t){var e=t.entryType,n=t.name,r=t.decodedBodySize,i=t.duration,a=t.domComplete,o=t.encodedBodySize,s=t.domContentLoadedEventStart,u=t.domContentLoadedEventEnd,c=t.domInteractive,l=t.loadEventStart,d=t.loadEventEnd,h=t.redirectCount,f=t.startTime,p=t.transferSize,m=t.type;return 0===i?null:{type:e+"."+m,start:ha(f),end:ha(a),name:n,data:{size:p,decodedBodySize:r,encodedBodySize:o,duration:i,domInteractive:c,domContentLoadedEventStart:s,domContentLoadedEventEnd:u,loadEventStart:l,loadEventEnd:d,domComplete:a,redirectCount:h}}}})["largest-contentful-paint"]=function(t){var e=t.entryType,n=t.startTime,r=t.size,i=0;if(tn.performance){var a=tn.performance.getEntriesByType("navigation")[0];i=a&&a.activationStart||0}var o=Math.max(n-i,0),s=ha(i)+o/1e3;return{type:e,name:e,start:s,end:s,data:{value:o,size:r,nodeId:Br.mirror.getId(t.element)}}},Ve);function da(t){return void 0===la[t.entryType]?null:la[t.entryType](t)}function ha(t){return(($.Z1||tn.performance.timeOrigin)+t)/1e3}function fa(t,e,n,r){return Fe(Ye(t,Ke(t),r,n),[[{type:"replay_event"},t],[{type:"replay_recording",length:"string"==typeof e?(new TextEncoder).encode(e).length:e.length},e]])}function pa(t){var e,n=t.recordingData,r=t.headers,i=JSON.stringify(r)+"\n";if("string"==typeof n)e=""+i+n;else{var a=(new TextEncoder).encode(i);(e=new Uint8Array(a.length+n.length)).set(a),e.set(n,a.length)}return e}function ma(t){return va.apply(this,arguments)}function va(){return va=Te(Oe().mark((function t(e){var n,r,i,a,o,s,u,c,l,d;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=e.client,r=e.scope,i=e.replayId,a=e.event,o="object"!=typeof n._integrations||null===n._integrations||Array.isArray(n._integrations)?void 0:Object.keys(n._integrations),t.next=4,Le(n.getOptions(),a,{event_id:i,integrations:o},r);case 4:if(s=t.sent){t.next=7;break}return t.abrupt("return",null);case 7:return s.platform=s.platform||"javascript",u=n.getSdkMetadata&&n.getSdkMetadata(),c=u&&u.sdk||{},l=c.name,d=c.version,s.sdk=k({},s.sdk,{name:l||"sentry.javascript.unknown",version:d||"0.0.0"}),t.abrupt("return",s);case 12:case"end":return t.stop()}}),t)}))),va.apply(this,arguments)}function _a(t){return ga.apply(this,arguments)}function ga(){return(ga=Te(Oe().mark((function t(e){var n,r,i,a,o,s,u,c,l,d,h,f,p,m,v,_,g,y,b,w,k;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.recordingData,r=e.replayId,i=e.segmentId,a=e.eventContext,o=e.timestamp,s=e.session,u=pa({recordingData:n,headers:{segment_id:i}}),c=a.urls,l=a.errorIds,d=a.traceIds,h=a.initialTimestamp,f=ft(),p=f.getClient(),m=f.getScope(),v=p&&p.getTransport(),_=p&&p.getDsn(),p&&m&&v&&_&&s.sampled){t.next=10;break}return t.abrupt("return");case 10:return g={type:nn,replay_start_timestamp:h/1e3,timestamp:o/1e3,error_ids:l,trace_ids:d,urls:c,replay_id:r,segment_id:i,replay_type:s.sampled},t.next=13,ma({scope:m,client:p,replayId:r,event:g});case 13:if(y=t.sent){t.next=18;break}return p.recordDroppedEvent("event_processor","replay",g),t.abrupt("return");case 18:return b=fa(y,u,_,p.getOptions().tunnel),t.prev=19,t.next=22,v.send(b);case 22:w=t.sent,t.next=30;break;case 25:t.prev=25,t.t0=t.catch(19),k=new Error(rn);try{k.cause=t.t0}catch(t){}throw k;case 30:if(w){t.next=32;break}return t.abrupt("return",w);case 32:if("number"!=typeof w.statusCode||!(w.statusCode<200||w.statusCode>=300)){t.next=34;break}throw new ya(w.statusCode);case 34:return t.abrupt("return",w);case 35:case"end":return t.stop()}}),t,null,[[19,25]])})))).apply(this,arguments)}var ya=function(t){function e(e){return t.call(this,"Transport returned status code "+e)||this}return we(e,t),e}(xe(Error));function ba(t,e){return wa.apply(this,arguments)}function wa(){return(wa=Te(Oe().mark((function t(e,n){var r,i;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(void 0===n&&(n={count:0,interval:an}),r=e.recordingData,e.options,r.length){t.next=4;break}return t.abrupt("return");case 4:return t.prev=4,t.next=7,_a(e);case 7:return t.abrupt("return",!0);case 10:if(t.prev=10,t.t0=t.catch(4),!(t.t0 instanceof ya)){t.next=14;break}throw t.t0;case 14:if("Replays",a={_retryCount:n.count},ft().setContext("Replays",a),!(n.count>=on)){t.next=20;break}i=new Error(rn+" - max retries exceeded");try{i.cause=t.t0}catch(t){}throw i;case 20:return n.interval*=++n.count,t.next=23,new Promise((function(t,r){setTimeout(Te(Oe().mark((function i(){return Oe().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return i.prev=0,i.next=3,ba(e,n);case 3:t(!0),i.next=9;break;case 6:i.prev=6,i.t0=i.catch(0),r(i.t0);case 9:case"end":return i.stop()}}),i,null,[[0,6]])}))),n.interval)}));case 23:return t.abrupt("return",t.sent);case 24:case"end":return t.stop()}var a}),t,null,[[4,10]])})))).apply(this,arguments)}var ka="__THROTTLED";var Sa=function(){var t=e.prototype;function e(t){var n,r,i,a,o,s=this,u=t.options,c=t.recordingOptions;e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this),e.prototype.__init7.call(this),e.prototype.__init8.call(this),e.prototype.__init9.call(this),e.prototype.__init10.call(this),e.prototype.__init11.call(this),e.prototype.__init12.call(this),e.prototype.__init13.call(this),e.prototype.__init14.call(this),e.prototype.__init15.call(this),e.prototype.__init16.call(this),e.prototype.__init17.call(this),e.prototype.__init18.call(this),this._recordingOptions=c,this._options=u,this._debouncedFlush=function(t,e,n){var r,i,a,o=n&&n.maxWait?Math.max(n.maxWait,e):0;function s(){return u(),r=t()}function u(){void 0!==i&&clearTimeout(i),void 0!==a&&clearTimeout(a),i=a=void 0}function c(){return i&&clearTimeout(i),i=setTimeout(s,e),o&&void 0===a&&(a=setTimeout(s,o)),r}return c.cancel=u,c.flush=function(){return void 0!==i||void 0!==a?s():r},c}((function(){return s._flush()}),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=(n=function(t,e){return vi(s,t,e)},r=300,i=5,a=new Map,o=!1,function(){var t=Math.floor(Date.now()/1e3);if(function(t){var e=t-i;a.forEach((function(t,n){n=r){var e=o;return o=!0,e?"__SKIPPED":ka}o=!1;var s=a.get(t)||0;return a.set(t,s+1),n.apply(void 0,arguments)});var l=this.getOptions(),d=l.slowClickTimeout,h=l.slowClickIgnoreSelectors,f=d?{threshold:Math.min(3e3,d),timeout:d,scrollTimeout:300,ignoreSelector:h?h.join(","):"",multiClickTimeout:1e3}:void 0;f&&(this.clickDetector=new Kr(this,f))}return t.__init=function(){this.eventBuffer=null},t.__init2=function(){this.performanceEvents=[]},t.__init3=function(){this.recordingMode="session"},t.__init4=function(){this.timeouts={sessionIdlePause:3e5,sessionIdleExpire:9e5,maxSessionLife:36e5}},t.__init5=function(){this._performanceObserver=null},t.__init6=function(){this._flushLock=null},t.__init7=function(){this._lastActivity=Date.now()},t.__init8=function(){this._isEnabled=!1},t.__init9=function(){this._isPaused=!1},t.__init10=function(){this._hasInitializedCoreListeners=!1},t.__init11=function(){this._stopRecording=null},t.__init12=function(){this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""}},t.getContext=function(){return this._context},t.isEnabled=function(){return this._isEnabled},t.isPaused=function(){return this._isPaused},t.getOptions=function(){return this._options},t.initializeSampling=function(){var t=this._options,e=t.errorSampleRate,n=t.sessionSampleRate;e<=0&&n<=0||this._loadAndCheckSession()&&(this.session?(this.session.sampled&&"session"!==this.session.sampled&&(this.recordingMode="buffer"),this._initializeRecording()):this._handleException(new Error("Unable to initialize and create session")))},t.start=function(){if(this._isEnabled&&"session"===this.recordingMode)throw new Error("Replay recording is already in progress");if(this._isEnabled&&"buffer"===this.recordingMode)throw new Error("Replay buffering is in progress, call `flush()` to save the replay");var t=this.session&&this.session.id,e=pi({timeouts:this.timeouts,stickySession:Boolean(this._options.stickySession),currentSession:this.session,sessionSampleRate:1,allowBuffering:!1}).session;e.previousSessionId=t,this.session=e,this._initializeRecording()},t.startBuffering=function(){if(this._isEnabled)throw new Error("Replay recording is already in progress");var t=this.session&&this.session.id,e=pi({timeouts:this.timeouts,stickySession:Boolean(this._options.stickySession),currentSession:this.session,sessionSampleRate:0,allowBuffering:!0}).session;e.previousSessionId=t,this.session=e,this.recordingMode="buffer",this._initializeRecording()},t.startRecording=function(){try{this._stopRecording=Br(k({},this._recordingOptions,"buffer"===this.recordingMode&&{checkoutEveryNms:6e4},{emit:(t=this,e=!1,function(n,r){if(t.checkAndHandleExpiredSession()){var i=r||!e;e=!0,t.addUpdate((function(){if("buffer"===t.recordingMode&&i&&t.setInitialState(),vi(t,n,i),!i)return!1;if(function(t,e){if(!e||!t.session||0!==t.session.segmentId)return Promise.resolve(null);vi(t,function(t){var e=t.getOptions();return{type:An.Custom,timestamp:Date.now(),data:{tag:"options",payload:{sessionSampleRate:e.sessionSampleRate,errorSampleRate:e.errorSampleRate,useCompressionOption:e.useCompression,blockAllMedia:e.blockAllMedia,maskAllText:e.maskAllText,maskAllInputs:e.maskAllInputs,useCompression:!!t.eventBuffer&&"worker"===t.eventBuffer.type,networkDetailHasUrls:e.networkDetailAllowUrls.length>0,networkCaptureBodies:e.networkCaptureBodies,networkRequestHasHeaders:e.networkRequestHeaders.length>0,networkResponseHasHeaders:e.networkResponseHeaders.length>0}}}}(t),!1)}(t,i),t.session&&t.session.previousSessionId)return!0;if("buffer"===t.recordingMode&&t.session&&t.eventBuffer){var e=t.eventBuffer.getEarliestTimestamp();e&&(t.session.started=e,t.getOptions().stickySession&&di(t.session))}var r=t.getOptions();return r._experiments.delayFlushOnCheckout?(setTimeout((function(){return t.conditionalFlush()}),r._experiments.delayFlushOnCheckout),t.cancelFlush(),!0):("session"===t.recordingMode&&t.flushImmediate(),!0)}))}}),onMutation:this._onMutationHandler}))}catch(t){this._handleException(t)}var t,e},t.stopRecording=function(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(t){return this._handleException(t),!1}},t.stop=function(){var t=Te(Oe().mark((function t(e){return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._isEnabled){t.next=2;break}return t.abrupt("return");case 2:if(t.prev=2,this._isEnabled=!1,this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),"session"!==this.recordingMode){t.next=11;break}return t.next=11,this._flush({force:!0});case 11:this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,e=this,function(){if("sessionStorage"in tn)try{tn.sessionStorage.removeItem(en)}catch(t){}}(),e.session=void 0,t.next=19;break;case 16:t.prev=16,t.t0=t.catch(2),this._handleException(t.t0);case 19:case"end":return t.stop()}var e}),t,this,[[2,16]])})));return function(e){return t.apply(this,arguments)}}(),t.pause=function(){this._isPaused=!0,this.stopRecording()},t.resume=function(){this._loadAndCheckSession()&&(this._isPaused=!1,this.startRecording())},t.sendBufferedReplayOrFlush=function(){var t=Te(Oe().mark((function t(e){var n,r,i,a;return Oe().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=(void 0===e?{}:e).continueRecording,r=void 0===n||n,"session"!==this.recordingMode){t.next=3;break}return t.abrupt("return",this.flushImmediate());case 3:return i=Date.now(),t.next=6,this.flushImmediate();case 6:if(a=this.stopRecording(),r&&a){t.next=9;break}return t.abrupt("return");case 9:this.recordingMode="session",this.session&&(this.session.shouldRefresh=!1,this._updateUserActivity(i),this._updateSessionActivity(i),this.session.started=i,this._maybeSaveSession()),this.startRecording();case 12:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),t.addUpdate=function(t){var e=t();"buffer"!==this.recordingMode&&!0!==e&&this._debouncedFlush()},t.triggerUserActivity=function(){if(this._updateUserActivity(),this._stopRecording)this.checkAndHandleExpiredSession(),this._updateSessionActivity();else{if(!this._loadAndCheckSession())return;this.resume()}},t.updateUserActivity=function(){this._updateUserActivity(),this._updateSessionActivity()},t.conditionalFlush=function(){return"buffer"===this.recordingMode?Promise.resolve():this.flushImmediate()},t.flushImmediate=function(){return this._debouncedFlush(),this._debouncedFlush.flush()},t.cancelFlush=function(){this._debouncedFlush.cancel()},t.getSessionId=function(){return this.session&&this.session.id},t.checkAndHandleExpiredSession=function(){var t=this.getSessionId();if(this._lastActivity&&ui(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&"session"===this.session.sampled)this.pause();else if(this._loadAndCheckSession())return t===this.getSessionId()||(this._triggerFullSnapshot(),!1)},t.setInitialState=function(){var t=""+tn.location.pathname+tn.location.hash+tn.location.search,e=""+tn.location.origin+t;this.performanceEvents=[],this._clearContext(),this._context.initialUrl=e,this._context.initialTimestamp=Date.now(),this._context.urls.push(e)},t.throttledAddEvent=function(t,e){var n=this,r=this._throttledAddEvent(t,e);if(r===ka){var i=Xr({category:"replay.throttled"});this.addUpdate((function(){vi(n,{type:An.Custom,timestamp:i.timestamp||0,data:{tag:"breadcrumb",payload:i,metric:!0}})}))}return r},t.getCurrentRoute=function(){var t=this.lastTransaction||ft().getScope().getTransaction();if(t&&["route","custom"].includes(t.metadata.source))return t.name},t._initializeRecording=function(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=function(t){if(t.useCompression&&window.Worker)try{var e=(r=new Blob(['/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\nfunction t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const m=t=>t<256?o[t]:o[256+(t>>>7)],b=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},g=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<{g(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)r=r+a[n-1]<<1,i[n]=r;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},x=t=>{t.bi_valid>8?b(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n{let s,r,o,_,f=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+f++],s+=(255&t.pending_buf[t.sym_buf+f++])<<8,r=t.pending_buf[t.sym_buf+f++],0===s?p(t,r,i):(o=l[r],p(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],g(t,r,_)),s--,o=m(s),p(t,o,n),_=a[o],0!==_&&(s-=d[o],g(t,s,_)))}while(f{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o{g(t,0+(i?1:0),3),x(t),b(t,a),b(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var T=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(g(t,2+(i?1:0),3),E(t,s,r)):(g(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(g(t,e-257,5),g(t,a-1,5),g(t,i-4,4),s=0;s{S||((()=>{let t,n,w,m,b;const g=new Array(16);for(w=0,m=0;m<28;m++)for(h[m]=w,t=0;t<1<>=7;m<30;m++)for(d[m]=b<<7,t=0;t<1<(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=a,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{g(t,2,3),p(t,256,s),(t=>{16===t.bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var F=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const L=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var N=(t,e,a,i)=>{const n=L,s=i+a;t^=-1;for(let a=i;a>>8^n[255&(t^e[a])];return-1^t},I={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=O,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:W,Z_OK:q,Z_STREAM_END:J,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>2*t-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_t=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let ft=(t,e,a)=>(e<{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ut=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ct(t.strm)},wt=(t,e)=>{t.pending_buf[t.pending++]=e},mt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=F(t.adler,e,n,a):2===t.state.wrap&&(t.adler=N(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&sr){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_t(t),i+=e),0===t.strm.avail_in)break;if(a=bt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ft(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ft(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},kt=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_outi+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,ct(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(bt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_watern&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(bt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===X)&&e!==P&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===X&&0===t.strm.avail_in&&a===i?1:0,H(t,t.block_start,a,r),t.block_start+=a,ct(t.strm)),r?3:1)},vt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ft(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2},yt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ut(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ut(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2};function xt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const zt=[new xt(0,0,0,0,kt),new xt(4,4,8,4,vt),new xt(4,5,16,8,vt),new xt(4,6,32,32,vt),new xt(4,4,16,16,yt),new xt(8,16,32,32,yt),new xt(8,16,128,128,yt),new xt(8,32,128,256,yt),new xt(32,128,258,1024,yt),new xt(32,258,258,4096,yt)];function At(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Et=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||42!==e.status&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&113!==e.status&&666!==e.status?1:0},Rt=t=>{if(Et(t))return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=-2,C(e),q},Zt=t=>{const e=Rt(t);var a;return e===q&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=zt[a.level].max_lazy,a.good_match=zt[a.level].good_length,a.nice_match=zt[a.level].nice_length,a.max_chain_length=zt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},Ut=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt||8===i&&1!==r)return lt(t,Q);8===i&&(i=9);const o=new At;return t.state=o,o.strm=t,o.status=42,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<Ut(t,e,ot,15,8,st),deflateInit2:Ut,deflateReset:Zt,deflateResetKeep:Rt,deflateSetHeader:(t,e)=>Et(t)||2!==t.state.wrap?Q:(t.state.gzhead=e,q),deflate:(t,e)=>{if(Et(t)||e>W||e<0)return t?lt(t,Q):Q;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||666===a.status&&e!==X)return lt(t,0===t.avail_out?$:Q);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(ct(t),0===t.avail_out)return a.last_flush=-1,q}else if(0===t.avail_in&&ht(e)<=ht(i)&&e!==X)return lt(t,$);if(666===a.status&&0!==t.avail_in)return lt(t,$);if(42===a.status&&0===a.wrap&&(a.status=113),42===a.status){let e=ot+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=at||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,mt(a,e),0!==a.strstart&&(mt(a,t.adler>>>16),mt(a,65535&t.adler)),t.adler=1,a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(57===a.status)if(t.adler=0,wt(a,31),wt(a,139),wt(a,8),a.gzhead)wt(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),wt(a,255&a.gzhead.time),wt(a,a.gzhead.time>>8&255),wt(a,a.gzhead.time>>16&255),wt(a,a.gzhead.time>>24&255),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(wt(a,255&a.gzhead.extra.length),wt(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=N(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,3),a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,ct(t),0!==a.pending)return a.last_flush=-1,q;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(ct(t),0!==a.pending))return a.last_flush=-1,q;wt(a,255&t.adler),wt(a,t.adler>>8&255),t.adler=0}if(a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(0!==t.avail_in||0!==a.lookahead||e!==P&&666!==a.status){let i=0===a.level?kt(a,e):a.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):zt[a.level].func(a,e);if(3!==i&&4!==i||(a.status=666),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),q;if(2===i&&(e===Y?K(a):e!==W&&(H(a,0,0,!1),e===G&&(dt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),ct(t),0===t.avail_out))return a.last_flush=-1,q}return e!==X?q:a.wrap<=0?J:(2===a.wrap?(wt(a,255&t.adler),wt(a,t.adler>>8&255),wt(a,t.adler>>16&255),wt(a,t.adler>>24&255),wt(a,255&t.total_in),wt(a,t.total_in>>8&255),wt(a,t.total_in>>16&255),wt(a,t.total_in>>24&255)):(mt(a,t.adler>>>16),mt(a,65535&t.adler)),ct(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?q:J)},deflateEnd:t=>{if(Et(t))return Q;const e=t.state.status;return t.state=null,113===e?lt(t,V):q},deflateSetDictionary:(t,e)=>{let a=e.length;if(Et(t))return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=F(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=ft(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,q},deflateInfo:"pako deflate (from Nodeca project)"};const Dt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Tt=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(const e in a)Dt(a,e)&&(t[e]=a[e])}}return t},Ot=t=>{let e=0;for(let a=0,i=t.length;a=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Lt[254]=Lt[254]=1;var Nt=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},It=(t,e)=>{const a=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Ft)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a="";for(let i=0;i{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Lt[t[a]]>e?a:e};var Ct=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const Ht=Object.prototype.toString,{Z_NO_FLUSH:Mt,Z_SYNC_FLUSH:jt,Z_FULL_FLUSH:Kt,Z_FINISH:Pt,Z_OK:Yt,Z_STREAM_END:Gt,Z_DEFAULT_COMPRESSION:Xt,Z_DEFAULT_STRATEGY:Wt,Z_DEFLATED:qt}=B;function Jt(t){this.options=Tt({level:Xt,method:qt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Wt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=St.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==Yt)throw new Error(I[a]);if(e.header&&St.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Nt(e.dictionary):"[object ArrayBuffer]"===Ht.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=St.deflateSetDictionary(this.strm,t),a!==Yt)throw new Error(I[a]);this._dict_set=!0}}function Qt(t,e){const a=new Jt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}Jt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Pt:Mt,"string"==typeof t?a.input=Nt(t):"[object ArrayBuffer]"===Ht.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===jt||s===Kt)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=St.deflate(a,s),n===Gt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=St.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Yt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},Jt.prototype.onData=function(t){this.chunks.push(t)},Jt.prototype.onEnd=function(t){t===Yt&&(this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Vt={Deflate:Jt,deflate:Qt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Qt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Qt(t,e)},constants:B};var $t=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg="invalid distance too far back",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg="invalid distance too far back",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a>3,a-=k,c-=k<<3,f&=(1<{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,U,S,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0}while(0!==d);for(h=1<>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whavexe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=me;break}if((15&h)!==we){t.msg="unknown compression method",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg="invalid window size",a.mode=me;break}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=N(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=N(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg="invalid block type",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid code lengths set",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg="invalid bit length repeat",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid literal/lengths set",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg="invalid distances set",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg="invalid literal/length code",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg="invalid distance code",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=F(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:"pako inflate (from Nodeca project)"};var Se=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Te,Z_FINISH:Oe,Z_OK:Fe,Z_STREAM_END:Le,Z_NEED_DICT:Ne,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Tt({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ue.inflateInit2(this.strm,e.windowBits);if(a!==Fe)throw new Error(I[a]);if(this.header=new Se,Ue.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Nt(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Ue.inflateSetDictionary(this.strm,e.dictionary),a!==Fe)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Oe:Te,"[object ArrayBuffer]"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Ue.inflate(a,r),s===Ne&&n&&(s=Ue.inflateSetDictionary(a,n),s===Fe?s=Ue.inflate(a,r):s===Be&&(s=Ne));a.avail_in>0&&s===Le&&a.state.wrap>0&&0!==t[a.next_in];)Ue.inflateReset(a),s=Ue.inflate(a,r);switch(s){case Ie:case Be:case Ne:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Le))if("string"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Fe||0!==o){if(s===Le)return s=Ue.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Fe&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=je,Xe=B;const We=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const e=this._hasEvents?",":"";this.deflate.push(e+t,Xe.Z_SYNC_FLUSH),this._hasEvents=!0}finish(){if(this.deflate.push("]",Xe.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this._init(),t}_init(){this._hasEvents=!1,this.deflate=new Ye,this.deflate.push("[",Xe.Z_NO_FLUSH)}},qe={clear:()=>{We.clear()},addEvent:t=>We.addEvent(t),finish:()=>We.finish(),compress:t=>function(t){return Ge(t)}(t)};addEventListener("message",(function(t){const e=t.data.method,a=t.data.id,i=t.data.arg;if(e in qe&&"function"==typeof qe[e])try{const t=qe[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});']),URL.createObjectURL(r)),n=new Worker(e);return new oi(n)}catch(t){}var r;return new ri}({useCompression:this._options.useCompression}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this.startRecording()},t._handleException=function(t){},t._loadAndCheckSession=function(){var t=pi({timeouts:this.timeouts,stickySession:Boolean(this._options.stickySession),currentSession:this.session,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:this._options.errorSampleRate>0||"buffer"===this.recordingMode}),e=t.type,n=t.session;"new"===e&&this.setInitialState();var r=this.getSessionId();return n.id!==r&&(n.previousSessionId=r),this.session=n,!!this.session.sampled||(this.stop("session unsampled"),!1)},t._addListeners=function(){try{tn.document.addEventListener("visibilitychange",this._handleVisibilityChange),tn.addEventListener("blur",this._handleWindowBlur),tn.addEventListener("focus",this._handleWindowFocus),tn.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(t=this,e=ft().getScope(),n=ft().getClient(),e&&e.addScopeListener(function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.getLastBreadcrumb&&t.getLastBreadcrumb();return oa!==e&&e?(oa=e,!e.category||["fetch","xhr","sentry.event","sentry.transaction"].includes(e.category)||e.category.startsWith("ui.")?null:"console"===e.category?function(t){var e=t.data&&t.data.arguments;if(!Array.isArray(e)||0===e.length)return Xr(t);var n=!1,r=e.map((function(t){if(!t)return t;if("string"==typeof t)return t.length>un?(n=!0,t.slice(0,un)+"…"):t;if("object"==typeof t)try{var e=Gt(t,7),r=JSON.stringify(e);if(r.length>un){var i=zi(r.slice(0,un)),a=JSON.parse(i);return n=!0,a}return e}catch(t){}return t}));return Xr(k({},t,{data:k({},t.data,{arguments:r},n?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{})}))}(e):Xr(e)):null}(e);n&&Hr(t,n)}}}(t)),zt("dom",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=function(t){var e,n="click"===t.name,r=null;try{e=C(r=n?Wr(t.event):Zr(t.event),{maxStringLength:200})||""}catch(t){e=""}return{target:r,message:e}}(t),n=e.target,r=e.message;return Xr(k({category:"ui."+t.name},Qr(n,r)))}(e);if(n){var r="click"===e.name,i=r&&e.event;r&&t.clickDetector&&i&&!i.altKey&&!i.metaKey&&!i.ctrlKey&&(a=t.clickDetector,o=n,s=Wr(e.event),a.handleClick(o,s)),Hr(t,n)}}var a,o,s}}(t)),zt("history",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.from,n=t.to,r=Date.now()/1e3;return{type:"navigation.push",start:r,end:r,name:n,data:{previous:e}}}(e);null!==n&&(t.getContext().urls.push(n.name),t.triggerUserActivity(),t.addUpdate((function(){return wi(t,[n]),!1})))}}}(t)),aa(t),ut(function(t,e){void 0===e&&(e=!1);var n=e?bi(t):void 0;return function(e,r){if(function(t){return"replay_event"===t.type}(e))return delete e.breadcrumbs,e;if(!gi(e)&&!yi(e))return e;if(function(t,e){return!(t.type||!t.exception||!t.exception.values||!t.exception.values.length)&&(!(!e.originalException||!e.originalException.__rrweb__)||t.exception.values.some((function(t){return!!(t.stacktrace&&t.stacktrace.frames&&t.stacktrace.frames.length)&&t.stacktrace.frames.some((function(t){return t.filename&&t.filename.includes("/rrweb/src/")}))})))}(e,r)&&!t.getOptions()._experiments.captureExceptions)return null;var i=function(t,e){return"buffer"===t.recordingMode&&e.message!==rn&&!(!e.exception||e.type)&&li(t.getOptions().errorSampleRate)}(t,e);return(i||"session"===t.recordingMode)&&(e.tags=k({},e.tags,{replayId:t.getSessionId()})),n&&n(e,{statusCode:200}),e}}(t,!sa(n))),sa(n)&&(n.on("afterSendEvent",bi(t)),n.on("createDsc",(function(e){var n=t.getSessionId();n&&t.isEnabled()&&"session"===t.recordingMode&&(e.replay_id=n)})),n.on("startTransaction",(function(e){t.lastTransaction=e})),n.on("finishTransaction",(function(e){t.lastTransaction=e}))),this._hasInitializedCoreListeners=!0)}catch(t){this._handleException(t)}var t,e,n;"PerformanceObserver"in tn&&(this._performanceObserver=function(t){var e=new PerformanceObserver((function(e){var n,r,i,a,o,s,u,c,l,d=(n=t.performanceEvents,r=e.getEntries(),i=n.reduce((function(t,e){return"navigation"===e.entryType?t[0].push(e):"largest-contentful-paint"===e.entryType?t[1].push(e):t[2].push(e),t}),[[],[],[]]),a=i[0],o=i[1],s=i[2],u=[],c=[],l=o.length?o[o.length-1]:void 0,r.forEach((function(t){if("largest-contentful-paint"!==t.entryType)if("navigation"!==t.entryType)u.push(t);else{var e=t;t.duration>0&&!a.find(ei(e))&&!c.find(ei(e))&&c.push(e)}else(!l||l.startTime";return Xr({category:"ui.keyDown",message:c,data:k({},Qr(o,c).data,{metaKey:e,shiftKey:n,ctrlKey:r,altKey:i,key:a})})}(e);n&&Hr(t,n)}}(t,e)}},t._doChangeToBackgroundTasks=function(t){if(this.session){var e=ci(this.session,this.timeouts);t&&!e&&this._createCustomBreadcrumb(t),this.conditionalFlush()}},t._doChangeToForegroundTasks=function(t){this.session&&this.checkAndHandleExpiredSession()&&t&&this._createCustomBreadcrumb(t)},t._triggerFullSnapshot=function(t){void 0===t&&(t=!0);try{Br.takeFullSnapshot(t)}catch(t){this._handleException(t)}},t._updateUserActivity=function(t){void 0===t&&(t=Date.now()),this._lastActivity=t},t._updateSessionActivity=function(t){void 0===t&&(t=Date.now()),this.session&&(this.session.lastActivity=t,this._maybeSaveSession())},t._createCustomBreadcrumb=function(t){var e=this;this.addUpdate((function(){e.throttledAddEvent({type:An.Custom,timestamp:t.timestamp||0,data:{tag:"breadcrumb",payload:t}})}))},t._addPerformanceEntries=function(){var t=[].concat(this.performanceEvents);return this.performanceEvents=[],Promise.all(wi(this,function(t){return t.map(da).filter(Boolean)}(t)))},t._clearContext=function(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]},t._updateInitialTimestampFromEventBuffer=function(){var t=this.session,e=this.eventBuffer;if(t&&e&&!t.segmentId){var n=e.getEarliestTimestamp();n&&nr;if(n>t._options.mutationBreadcrumbLimit||i){var a=Xr({category:"replay.mutations",data:{count:n,limit:i}});t._createCustomBreadcrumb(a)}return!i||(t.stop("mutationLimit"),!1)}},e}();function xa(t,e,n,r){var i="string"==typeof r?r.split(","):[],a=[].concat(t,i,e);return void 0!==n&&("string"==typeof n&&a.push("."+n),console.warn("[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.")),a.join(",")}function Ea(){return"undefined"!=typeof window&&(!(0,Xe.KV)()||"undefined"!=typeof process&&"renderer"===process.type)}var Ta='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',Ca=["content-length","content-type","accept"],Ia=!1,Aa=function(){e.__initStatic=function(){this.id="Replay"};var t=e.prototype;function e(t){var n=void 0===t?{}:t,r=n.flushMinDelay,i=void 0===r?5e3:r,a=n.flushMaxDelay,o=void 0===a?5500:a,s=n.stickySession,u=void 0===s||s,c=n.useCompression,l=void 0===c||c,d=n._experiments,h=void 0===d?{}:d,f=n.sessionSampleRate,p=n.errorSampleRate,m=n.maskAllText,v=void 0===m||m,_=n.maskAllInputs,g=void 0===_||_,y=n.blockAllMedia,b=void 0===y||y,w=n.mutationBreadcrumbLimit,S=void 0===w?750:w,x=n.mutationLimit,E=void 0===x?1e4:x,T=n.slowClickTimeout,C=void 0===T?7e3:T,I=n.slowClickIgnoreSelectors,A=void 0===I?[]:I,R=n.networkDetailAllowUrls,O=void 0===R?[]:R,L=n.networkCaptureBodies,D=void 0===L||L,M=n.networkRequestHeaders,N=void 0===M?[]:M,z=n.networkResponseHeaders,U=void 0===z?[]:z,P=n.mask,j=void 0===P?[]:P,F=n.unmask,B=void 0===F?[]:F,H=n.block,q=void 0===H?[]:H,W=n.unblock,Z=void 0===W?[]:W,G=n.ignore,K=void 0===G?[]:G,Y=n.maskFn,V=n.beforeAddRecordingEvent,X=n.blockClass,J=n.blockSelector,$=n.maskInputOptions,Q=n.maskTextClass,tt=n.maskTextSelector,et=n.ignoreClass;if(e.prototype.__init.call(this),this._recordingOptions=k({maskAllInputs:g,maskAllText:v,maskInputOptions:k({},$||{},{password:!0}),maskTextFn:Y,maskInputFn:Y},function(t){var e=t.unmask,n=t.block,r=t.unblock,i=t.ignore,a=t.blockClass,o=t.blockSelector,s=t.maskTextClass,u=t.ignoreClass,c=xa(t.mask,[".sentry-mask","[data-sentry-mask]"],s,t.maskTextSelector),l=xa(e,[".sentry-unmask","[data-sentry-unmask]"]),d={maskTextSelector:c,unmaskTextSelector:l,maskInputSelector:c,unmaskInputSelector:l,blockSelector:xa(n,[".sentry-block","[data-sentry-block]"].concat(['base[href="/"]']),a,o),unblockSelector:xa(r,[".sentry-unblock","[data-sentry-unblock]"]),ignoreSelector:xa(i,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'],u)};return a instanceof RegExp&&(d.blockClass=a),s instanceof RegExp&&(d.maskTextClass=s),d}({mask:j,unmask:B,block:q,unblock:Z,ignore:K,blockClass:X,blockSelector:J,maskTextClass:Q,maskTextSelector:tt,ignoreClass:et}),{slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0}),this._initialOptions={flushMinDelay:i,flushMaxDelay:o,stickySession:u,sessionSampleRate:f,errorSampleRate:p,useCompression:l,blockAllMedia:b,maskAllInputs:g,maskAllText:v,mutationBreadcrumbLimit:S,mutationLimit:E,slowClickTimeout:C,slowClickIgnoreSelectors:A,networkDetailAllowUrls:O,networkCaptureBodies:D,networkRequestHeaders:Ra(N),networkResponseHeaders:Ra(U),beforeAddRecordingEvent:V,_experiments:h},"number"==typeof f&&(console.warn("[Replay] You are passing `sessionSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysSessionSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: "+f+" })"),this._initialOptions.sessionSampleRate=f),"number"==typeof p&&(console.warn("[Replay] You are passing `errorSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysOnErrorSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: "+p+" })"),this._initialOptions.errorSampleRate=p),this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?this._recordingOptions.blockSelector+","+Ta:Ta),this._isInitialized&&Ea())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}return t.__init=function(){this.name=e.id},t.setupOnce=function(){var t=this;Ea()&&(this._setup(),setTimeout((function(){return t._initialize()})))},t.start=function(){this._replay&&this._replay.start()},t.startBuffering=function(){this._replay&&this._replay.startBuffering()},t.stop=function(){return this._replay?this._replay.stop():Promise.resolve()},t.flush=function(t){return this._replay&&this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(t):Promise.resolve()},t.getReplayId=function(){if(this._replay&&this._replay.isEnabled())return this._replay.getSessionId()},t._initialize=function(){this._replay&&this._replay.initializeSampling()},t._setup=function(){var t=function(t){var e=ft().getClient(),n=e&&e.getOptions(),r=k({sessionSampleRate:0,errorSampleRate:0},U(t));return n?(null==t.sessionSampleRate&&null==t.errorSampleRate&&null==n.replaysSessionSampleRate&&null==n.replaysOnErrorSampleRate&&console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set."),"number"==typeof n.replaysSessionSampleRate&&(r.sessionSampleRate=n.replaysSessionSampleRate),"number"==typeof n.replaysOnErrorSampleRate&&(r.errorSampleRate=n.replaysOnErrorSampleRate),r):(console.warn("SDK client is not available."),r)}(this._initialOptions);this._replay=new Sa({options:t,recordingOptions:this._recordingOptions})},Ae(e,[{key:"_isInitialized",get:function(){return Ia},set:function(t){Ia=t}}]),e}();function Ra(t){return[].concat(Ca,t.map((function(t){return t.toLowerCase()})))}Aa.__initStatic();var Oa="7.56.0",La=function(t){function e(n,r){var i;return void 0===r&&(r="warn"),(i=t.call(this,n)||this).message=n,i.name=(this instanceof e?this.constructor:void 0).prototype.constructor.name,Object.setPrototypeOf(function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(i),(this instanceof e?this.constructor:void 0).prototype),i.logLevel=r,i}return we(e,t),e}(xe(Error)),Da="7";function Ma(t){var e=t.protocol?t.protocol+":":"",n=t.port?":"+t.port:"";return e+"//"+t.host+n+(t.path?"/"+t.path:"")+"/api/"}function Na(t,e){void 0===e&&(e={});var n="string"==typeof e?e:e.tunnel,r="string"!=typeof e&&e._metadata?e._metadata.sdk:void 0;return n||function(t){return""+Ma(t)+t.projectId+"/envelope/"}(t)+"?"+function(t,e){return n=k({sentry_key:t.publicKey,sentry_version:Da},e&&{sentry_client:e.name+"/"+e.version}),Object.keys(n).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])})).join("&");var n}(t,r)}var za=[];function Ua(t,e){e[t.name]=t,-1===za.indexOf(t.name)&&(t.setupOnce(ut,ft),za.push(t.name))}function Pa(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return ja(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ja(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function ja(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},t._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._dsn},t._prepareEvent=function(t,e,n){var r=this.getOptions(),i=Object.keys(this._integrations);return!e.integrations&&i.length>0&&(e.integrations=i),Le(r,t,e,n)},t._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){}))},t._processEvent=function(t,e,n){var r=this,i=this.getOptions(),a=i.sampleRate;if(!this._isEnabled())return rt(new La("SDK not enabled, will not capture event.","log"));var o=Ha(t),s=Ba(t),u=t.type||"error",c="before send for type `"+u+"`";if(s&&"number"==typeof a&&Math.random()>a)return this.recordDroppedEvent("sample_rate","error",t),rt(new La("Discarding event because it's not included in the random sample (sampling rate = "+a+")","log"));var l="replay_event"===u?"replay":u;return this._prepareEvent(t,e,n).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",l,t),new La("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var a=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;return Ba(e)&&r?r(e,n):Ha(e)&&i?i(e,n):e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(f(t))return t.then((function(t){if(!d(t)&&null!==t)throw new La(n);return t}),(function(t){throw new La(e+" rejected with "+t)}));if(!d(t)&&null!==t)throw new La(n);return t}(a,c)})).then((function(i){if(null===i)throw r.recordDroppedEvent("before_send",l,t),new La(c+" returned `null`, will not send event.","log");var a=n&&n.getSession();!o&&a&&r._updateSessionFromEvent(a,i);var s=i.transaction_info;return o&&s&&i.transaction!==t.transaction&&(i.transaction_info=k({},s,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof La)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new La("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},t._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},t._sendEnvelope=function(t){if(this._transport&&this._dsn)return this.emit("beforeEnvelope",t),this._transport.send(t).then(null,(function(t){}))},t._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},e}();function Ba(t){return void 0===t.type}function Ha(t){return"transaction"===t.type}var qa=n(476),Wa=function(t){function e(e){var n,r=vt.SENTRY_SDK_SOURCE||(0,qa.S)();return e._metadata=e._metadata||{},e._metadata.sdk=e._metadata.sdk||{name:"sentry.javascript.browser",packages:[{name:r+":@sentry/browser",version:Oa}],version:Oa},n=t.call(this,e)||this,e.sendClientReports&&vt.document&&vt.document.addEventListener("visibilitychange",(function(){"hidden"===vt.document.visibilityState&&n._flushOutcomes()})),n}we(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=te(t,e,n&&n.syntheticException||void 0,r);return V(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),nt(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var a=ee(t,e,r&&r.syntheticException||void 0,i);return a.level=n,r&&r.event_id&&(a.event_id=r.event_id),nt(a)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.sendEvent=function(e,n){var r=this.getIntegrationById(de);r&&r.addSentryBreadcrumb&&r.addSentryBreadcrumb(e),t.prototype.sendEvent.call(this,e,n)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,a=k({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:Ne(i)}),o=function(t){return[{type:"user_report"},t]}(t);return Fe(a,[o])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,Fe((n=this._options.tunnel&&Ne(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:(0,$.yW)(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(Fa);function Za(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Ga(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ga(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Ga(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){nt(t).then((function(){--i||(clearTimeout(a),n(!0))}),r)}))}))}}}(t.bufferSize||Ya));var r={};function i(i){var a=[];if(Be(i,(function(e,n){var i,o,s,u=Ge(n);if(i=r,o=u,void 0===s&&(s=Date.now()),function(t,e){return t[e]||t.all||0}(i,o)>s){var c=Xa(e,n);t.recordDroppedEvent("ratelimit_backoff",u,c)}else a.push(e)})),0===a.length)return nt();var o=Fe(i[0],a),s=function(e){Be(o,(function(n,r){var i=Xa(n,r);t.recordDroppedEvent(e,Ge(r),i)}))};return n.add((function(){return e({body:qe(o,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var a=k({},t),o=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(o)for(var u,c=Za(o.trim().split(","));!(u=c()).done;){var l=u.value.split(":",2),d=l[0],h=l[1],f=parseInt(d,10),p=1e3*(isNaN(f)?60:f);if(h)for(var m,v=Za(h.split(";"));!(m=v()).done;)a[m.value]=n+p;else a.all=n+p}else s?a.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?Ka:r-e}(s,n):429===r&&(a.all=n+6e4);return a}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof La)return s("queue_overflow"),nt();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function Xa(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var Ja=void 0;function $a(t,e){void 0===e&&(e=function(){if(Ja)return Ja;if(Ct(vt.fetch))return Ja=vt.fetch.bind(vt);var t=vt.document,e=vt.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return Ja=e.bind(vt)}());var n=0,r=0;return Va(t,(function(i){var a=i.body.length;n+=a,r++;var o=k({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,o).then((function(t){return n-=a,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return Ja=void 0,n-=a,r--,rt(t)}}))}var Qa="?";function to(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var eo=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,no=/\((\S*)(?::(\d+))(?::(\d+))\)/,ro=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,io=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ao=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,oo=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=H.test(o)?o.replace(H,"$1"):o;if(!s.match(/\S*Error: /)){for(var u,c=F(r);!(u=c()).done;){var l=(0,u.value)(s);if(l){n.push(l);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=t.slice(0,50),n=e[e.length-1].function;n&&/sentryWrapped/.test(n)&&e.pop(),e.reverse();var r=e[e.length-1].function;return r&&/captureMessage|captureException/.test(r)&&e.pop(),e.map((function(t){return k({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=eo.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=no.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=so(e[1]||Qa,e[2]),i=r[0];return to(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=ro.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=io.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||Qa,a=so(i,r);return i=a[0],to(r=a[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=ao.exec(t);return e?to(e[2],e[1]||Qa,+e[3],e[4]?+e[4]:void 0):void 0}]]),so=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:Qa,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},uo=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="Dedupe"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(e,n){var r=function(e){if(e.type)return e;var r=n().getIntegration(t);if(r){try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!lo(t,e)&&!!co(t,e))))}(t,e)||!!function(t,e){var n=ho(e),r=ho(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!lo(t,e)&&!!co(t,e)))}(t,e))}(e,r._previousEvent))return null}catch(t){return r._previousEvent=e}return r._previousEvent=e}return e};r.id=this.name,e(r)},t}();function co(t,e){var n=fo(t),r=fo(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i{var t={495:(t,e,n)=>{"use strict";function r(){return!("undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&__SENTRY_BROWSER_BUNDLE__)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}n.d(e,{KV:()=>r}),t=n.hmd(t)},648:(t,e,n)=>{var r=n(288).default;function i(){"use strict";t.exports=i=function(){return e},t.exports.__esModule=!0,t.exports.default=t.exports;var e={},n=Object.prototype,o=n.hasOwnProperty,a=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",u=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function d(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{d({},"")}catch(t){d=function(t,e,n){return t[e]=n}}function f(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,o=Object.create(i.prototype),s=new C(r||[]);return a(o,"_invoke",{value:w(t,n,s)}),o}function p(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=f;var h={};function v(){}function m(){}function g(){}var y={};d(y,c,(function(){return this}));var _=Object.getPrototypeOf,b=_&&_(_(M([])));b&&b!==n&&o.call(b,c)&&(y=b);var S=g.prototype=v.prototype=Object.create(y);function k(t){["next","throw","return"].forEach((function(e){d(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){function n(i,a,s,c){var u=p(t[i],t,a);if("throw"!==u.type){var l=u.arg,d=l.value;return d&&"object"==r(d)&&o.call(d,"__await")?e.resolve(d.__await).then((function(t){n("next",t,s,c)}),(function(t){n("throw",t,s,c)})):e.resolve(d).then((function(t){l.value=t,s(l)}),(function(t){return n("throw",t,s,c)}))}c(u.arg)}var i;a(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,i){n(t,r,e,i)}))}return i=i?i.then(o,o):o()}})}function w(t,e,n){var r="suspendedStart";return function(i,o){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw o;return{value:void 0,done:!0}}for(n.method=i,n.arg=o;;){var a=n.delegate;if(a){var s=E(a,n);if(s){if(s===h)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var c=p(t,e,n);if("normal"===c.type){if(r=n.done?"completed":"suspendedYield",c.arg===h)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r="completed",n.method="throw",n.arg=c.arg)}}}function E(t,e){var n=e.method,r=t.iterator[n];if(void 0===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=void 0,E(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),h;var i=p(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function I(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function C(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function M(t){if(t){var e=t[c];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n=0;--r){var i=this.tryEntries[r],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=o.call(i,"catchLoc"),c=o.call(i,"finallyLoc");if(s&&c){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),I(n),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;I(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:M(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),h}},e}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},288:t=>{function e(n){return t.exports=e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.__esModule=!0,t.exports.default=t.exports,e(n)}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports},357:(t,e,n)=>{var r=n(648)();t.exports=r;try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var o=e[r]={id:r,loaded:!1,exports:{}};return t[r](o,o.exports,n),o.loaded=!0,o.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.hmd=t=>((t=Object.create(t)).children||(t.children=[]),Object.defineProperty(t,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+t.id)}}),t),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=!1;function o(t){return t&&t.Math==Math?t:void 0}var a="object"==typeof globalThis&&o(globalThis)||"object"==typeof window&&o(window)||"object"==typeof self&&o(self)||"object"==typeof n.g&&o(n.g)||function(){return this}()||{};function s(){return a}function c(t,e,n){var r=n||a,i=r.__SENTRY__=r.__SENTRY__||{};return i[t]||(i[t]=e())}var u=["debug","info","warn","error","log","assert","trace"],l={};function d(t){if(!("console"in a))return t();var e=a.console,n={},r=Object.keys(l);r.forEach((function(t){var r=l[t];n[t]=e[t],e[t]=r}));try{return t()}finally{r.forEach((function(t){e[t]=n[t]}))}}var f,p,h=(f=!1,p={enable:function(){f=!0},disable:function(){f=!1},isEnabled:function(){return f}},i?u.forEach((function(t){p[t]=function(){for(var e=arguments.length,n=new Array(e),r=0;r";try{for(var n,r=t,i=[],o=0,a=0,s=Array.isArray(e)?e:e.keyAttrs,c=!Array.isArray(e)&&e.maxStringLength||O;r&&o++<5&&!("html"===(n=A(r,s))||o>1&&a+3*i.length+n.length>=c);)i.push(n),a+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function A(t,e){var n,r,i,o,a,s=t,c=[];if(!s||!s.tagName)return"";if(M.HTMLElement&&s instanceof HTMLElement&&s.dataset&&s.dataset.sentryComponent)return s.dataset.sentryComponent;c.push(s.tagName.toLowerCase());var u=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(u&&u.length)u.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&c.push("#"+s.id),(n=s.className)&&S(n))for(r=n.split(/\s+/),a=0;a"}}function H(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function q(t){return W(t,new Map)}function W(t,e){if(function(t){if(!w(t))return!1;try{var e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,o=Object.keys(t);i>t/4).toString(16)}))}function Y(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function J(t){var e=t.message,n=t.event_id;if(e)return e;var r=Y(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function K(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],o=i[0]=i[0]||{};o.value||(o.value=e||""),o.type||(o.type=n||"Error")}function G(t,e){var n=Y(t);if(n){var r=n.mechanism;if(n.mechanism=v({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=v({},r&&r.data,e.data);n.mechanism.data=i}}}function $(t){if(t&&t.__sentry_captured__)return!0;try{j(t,"__sentry_captured__",!0)}catch(t){}return!1}var X,Q=!1;function Z(t){return new et((function(e){e(t)}))}function tt(t){return new et((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(X||(X={}));var et=function(){function t(e){t.prototype.__init.call(this),t.prototype.__init2.call(this),t.prototype.__init3.call(this),t.prototype.__init4.call(this),this._state=X.PENDING,this._handlers=[];try{e(this._resolve,this._reject)}catch(t){this._reject(t)}}var e=t.prototype;return e.then=function(e,n){var r=this;return new t((function(t,i){r._handlers.push([!1,function(n){if(e)try{t(e(n))}catch(t){i(t)}else t(n)},function(e){if(n)try{t(n(e))}catch(t){i(t)}else i(e)}]),r._executeHandlers()}))},e.catch=function(t){return this.then((function(t){return t}),t)},e.finally=function(e){var n=this;return new t((function(t,r){var i,o;return n.then((function(t){o=!1,i=t,e&&e()}),(function(t){o=!0,i=t,e&&e()})).then((function(){o?r(i):t(i)}))}))},e.__init=function(){var t=this;this._resolve=function(e){t._setResult(X.RESOLVED,e)}},e.__init2=function(){var t=this;this._reject=function(e){t._setResult(X.REJECTED,e)}},e.__init3=function(){var t=this;this._setResult=function(e,n){t._state===X.PENDING&&(T(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},e.__init4=function(){var t=this;this._executeHandlers=function(){if(t._state!==X.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===X.RESOLVED&&e[1](t._value),t._state===X.REJECTED&&e[2](t._value),e[0]=!0)}))}}},t}();function nt(){return c("globalEventProcessors",(function(){return[]}))}function rt(t){nt().push(t)}function it(t,e,n,r){return void 0===r&&(r=0),new et((function(i,o){var a=t[r];if(null===e||"function"!=typeof a)i(e);else{var s=a(v({},e),n);Q&&a.id&&null===s&&h.log('Event processor "'+a.id+'" dropped event'),T(s)?s.then((function(e){return it(t,e,n,r+1).then(i)})).then(null,o):it(t,s,n,r+1).then(i).then(null,o)}}))}var ot=1e3;function at(){return Date.now()/ot}var st=function(){var t=a.performance;if(!t||!t.now)return at;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/ot}}(),ct=(function(){var t=a.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}var lt=n(357),dt=n.n(lt);function ft(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return pt(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?pt(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function pt(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nn?_t(t,e-1,n):i}function bt(t,e,r,i,o){var a,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===o&&(a="function"==typeof WeakSet,s=a?new WeakSet:[],o=[function(t){if(a)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){v[y]="[MaxProperties ~]";break}var _=g[y];v[y]=bt(y,_,p-1,i,o),m++}return d(e),v}var St=1;function kt(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=xt(t);return q({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function xt(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}var wt=new WeakMap;var Et=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function Tt(t,e){return qt().captureEvent(t,e)}function It(t,e){qt().addBreadcrumb(t,e)}function Ct(){return qt().getClient()}function Mt(t){return t.transaction}function Ot(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=q({environment:r.environment||ct,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}function Rt(t){var e=Ct();if(!e)return{};var n=Ot(xt(t).trace_id||"",e,qt().getScope()),r=Mt(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=xt(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&St)}(r)),e.emit&&e.emit("createDsc",n),n}function At(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=q(n);c&&Object.keys(c).length&&(t.extra=v({},c,t.extra));var u=q(r);u&&Object.keys(u).length&&(t.tags=v({},u,t.tags));var l=q(i);l&&Object.keys(l).length&&(t.user=v({},l,t.user));var d=q(o);d&&Object.keys(d).length&&(t.contexts=v({},d,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=v({trace:kt(e)},t.contexts);var n=Mt(e);if(n){t.sdkProcessingMetadata=v({dynamicSamplingContext:Rt(e)},t.sdkProcessingMetadata);var r=xt(n).description;r&&(t.tags=v({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=v({},t.sdkProcessingMetadata,e)}(t,o)}function Dt(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.sdkProcessingMetadata,c=e.breadcrumbs,u=e.fingerprint,l=e.eventProcessors,d=e.attachments,f=e.propagationContext,p=e.transactionName,h=e.span;Nt(t,"extra",n),Nt(t,"tags",r),Nt(t,"user",i),Nt(t,"contexts",o),Nt(t,"sdkProcessingMetadata",s),a&&(t.level=a),p&&(t.transactionName=p),h&&(t.span=h),c.length&&(t.breadcrumbs=[].concat(t.breadcrumbs,c)),u.length&&(t.fingerprint=[].concat(t.fingerprint,u)),l.length&&(t.eventProcessors=[].concat(t.eventProcessors,l)),d.length&&(t.attachments=[].concat(t.attachments,d)),t.propagationContext=v({},t.propagationContext,f)}function Nt(t,e,n){if(n&&Object.keys(n).length)for(var r in t[e]=v({},t[e]),n)Object.prototype.hasOwnProperty.call(n,r)&&(t[e][r]=n[r])}var Lt,Pt=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=jt()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=v({},this._tags),e._extra=v({},this._extra),e._contexts=v({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=v({},this._sdkProcessingMetadata),e._propagationContext=v({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&ut(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=v({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=v({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=v({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=v({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=v({},this._tags,r.tags),this._extra=v({},this._extra,r.extra),this._contexts=v({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(w(n)){var i=e;this._tags=v({},this._tags,i.tags),this._extra=v({},this._extra,i.extra),this._contexts=v({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=jt(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=v({timestamp:at()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),At(t,this.getScopeData()),it([].concat(n,nt(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=v({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:V();if(!this._client)return h.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,v({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:V();if(!this._client)return h.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,v({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:V();return this._client?(this._client.captureEvent(t,v({},e,{event_id:n}),this),n):(h.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function jt(){return{traceId:V(),spanId:V().substring(16)}}var Ut="7.119.1",Ft=parseFloat(Ut),Bt=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=Ft),this._version=r,e?i=e:(i=new Pt).setClient(t),n?o=n:(o=new Pt).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(n=r()).done;){var i=n.value;i&&i.afterAllSetup&&i.afterAllSetup(t)}}function Gt(t,e,n){if(n[e.name])Q&&h.log("Integration skipped because it was already installed: "+e.name);else{if(n[e.name]=e,-1===Jt.indexOf(e.name)&&(e.setupOnce(rt,qt),Jt.push(e.name)),e.setup&&"function"==typeof e.setup&&e.setup(t),t.on&&"function"==typeof e.preprocessEvent){var r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(function(e,n){return r(e,n,t)}))}if(t.addEventProcessor&&"function"==typeof e.processEvent){var i=e.processEvent.bind(e),o=Object.assign((function(e,n){return i(e,n,t)}),{id:e.name});t.addEventProcessor(o)}Q&&h.log("Integration installed: "+e.name)}}function $t(t,e){return Object.assign((function(){return e.apply(void 0,arguments)}),{id:t})}var Xt,Qt=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/],Zt=[/^.*\/healthcheck$/,/^.*\/healthy$/,/^.*\/live$/,/^.*\/ready$/,/^.*\/heartbeat$/,/^.*\/health$/,/^.*\/healthz$/],te="InboundFilters",ee=function(t){return void 0===t&&(t={}),{name:te,setupOnce:function(){},processEvent:function(e,n,r){var i=r.getOptions(),o=function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),{allowUrls:[].concat(t.allowUrls||[],e.allowUrls||[]),denyUrls:[].concat(t.denyUrls||[],e.denyUrls||[]),ignoreErrors:[].concat(t.ignoreErrors||[],e.ignoreErrors||[],t.disableErrorDefaults?[]:Qt),ignoreTransactions:[].concat(t.ignoreTransactions||[],e.ignoreTransactions||[],t.disableTransactionDefaults?[]:Zt),ignoreInternal:void 0===t.ignoreInternal||t.ignoreInternal}}(t,i);return function(t,e){return e.ignoreInternal&&function(t){try{return"SentryError"===t.exception.values[0].type}catch(t){}return!1}(t)?(Q&&h.warn("Event dropped due to being internal Sentry Error.\nEvent: "+J(t)),!0):function(t,e){return!(t.type||!e||!e.length)&&function(t){var e,n=[];t.message&&n.push(t.message);try{e=t.exception.values[t.exception.values.length-1]}catch(t){}return e&&e.value&&(n.push(e.value),e.type&&n.push(e.type+": "+e.value)),Q&&0===n.length&&h.error("Could not extract message for event "+J(t)),n}(t).some((function(t){return L(t,e)}))}(t,e.ignoreErrors)?(Q&&h.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: "+J(t)),!0):function(t,e){if("transaction"!==t.type||!e||!e.length)return!1;var n=t.transaction;return!!n&&L(n,e)}(t,e.ignoreTransactions)?(Q&&h.warn("Event dropped due to being matched by `ignoreTransactions` option.\nEvent: "+J(t)),!0):function(t,e){if(!e||!e.length)return!1;var n=re(t);return!!n&&L(n,e)}(t,e.denyUrls)?(Q&&h.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: "+J(t)+".\nUrl: "+re(t)),!0):!function(t,e){if(!e||!e.length)return!0;var n=re(t);return!n||L(n,e)}(t,e.allowUrls)&&(Q&&h.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: "+J(t)+".\nUrl: "+re(t)),!0)}(e,o)?null:e}}},ne=$t(te,ee);function re(t){try{var e;try{e=t.exception.values[0].stacktrace.frames}catch(t){}return e?function(t){void 0===t&&(t=[]);for(var e=t.length-1;e>=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(e){return Q&&h.error("Cannot extract url for event "+J(t)),null}}var ie="FunctionToString",oe=new WeakMap,ae=function(){return{name:ie,setupOnce:function(){Xt=Function.prototype.toString;try{Function.prototype.toString=function(){for(var t=F(this),e=oe.has(Ct())&&void 0!==t?t:this,n=arguments.length,r=new Array(n),i=0;i0}function de(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return"function"==typeof r?r:t;if(F(t))return t}catch(e){return t}var i=function(){var r=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var i=r.map((function(t){return de(t,e)}));return t.apply(this,i)}catch(t){throw ue++,setTimeout((function(){ue--})),function(){for(var t=qt(),e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=o()).done;){var a=r.value;try{a(e)}catch(e){i&&h.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+gt(a)+"\nError:",e)}}}var Te=null;function Ie(){Te=a.onerror,a.onerror=function(t,e,n,r,i){return Ee("error",{column:r,error:i,line:n,msg:t,url:e}),!(!Te||Te.__SENTRY_LOADER__)&&Te.apply(this,arguments)},a.onerror.__SENTRY_INSTRUMENTED__=!0}var Ce=null;function Me(){Ce=a.onunhandledrejection,a.onunhandledrejection=function(t){return Ee("unhandledrejection",t),!(Ce&&!Ce.__SENTRY_LOADER__)||Ce.apply(this,arguments)},a.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function Oe(t,e){var n=Ae(t,e),r={type:e&&e.name,value:Ne(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Re(t,e){return{exception:{values:[Oe(t,e)]}}}function Ae(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(De.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var De=/Minified React error #\d+;/i;function Ne(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function Le(t,e,n,r,i){var o;if(_(e)&&e.error)return Re(t,e.error);if(b(e)||y(e,"DOMException")){var a=e;if("stack"in e)o=Re(t,e);else{var s=a.name||(b(a)?"DOMError":"DOMException"),c=a.message?s+": "+a.message:s;K(o=Pe(t,c,n,r),c)}return"code"in a&&(o.tags=v({},o.tags,{"DOMException.code":""+a.code})),o}return g(e)?Re(t,e):w(e)||E(e)?(o=function(t,e,n,r){var i=Ct(),o=i&&i.getOptions().normalizeDepth,a={exception:{values:[{type:E(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:je(e,{isUnhandledRejection:r})}]},extra:{__serialized__:_t(e,o)}};if(n){var s=Ae(t,n);s.length&&(a.exception.values[0].stacktrace={frames:s})}return a}(t,e,n,i),G(o,{synthetic:!0}),o):(K(o=Pe(t,e,n,r),""+e,void 0),G(o,{synthetic:!0}),o)}function Pe(t,e,n,r){var i={};if(r&&n){var o=Ae(t,n);o.length&&(i.exception={values:[{value:e,stacktrace:{frames:o}}]})}if(k(e)){var a=e.__sentry_template_string__,s=e.__sentry_template_values__;return i.logentry={message:a,params:s},i}return i.message=e,i}function je(t,e){var n=e.isUnhandledRejection,r=function(t,e){void 0===e&&(e=40);var n=Object.keys(B(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return D(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:D(i,e)}return""}(t),i=n?"promise rejection":"exception";return _(t)?"Event `ErrorEvent` captured as "+i+" with message `"+t.message+"`":E(t)?"Event `"+function(t){try{var e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch(t){}}(t)+"` (type="+t.type+") captured as "+i:"Object captured as "+i+" with keys: "+r}var Ue="GlobalHandlers",Fe=function(t){void 0===t&&(t={});var e=v({onerror:!0,onunhandledrejection:!0},t);return{name:Ue,setupOnce:function(){Error.stackTraceLimit=50},setup:function(t){e.onerror&&(function(t){var e,n;e=function(e){var n=qe(),r=n.stackParser,i=n.attachStacktrace;if(Ct()===t&&!le()){var o=e.msg,a=e.url,s=e.line,c=e.column,u=e.error,l=void 0===u&&S(o)?function(t,e,n,r){var i=_(t)?t.message:t,o="Error",a=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return a&&(o=a[1],i=a[2]),ze({exception:{values:[{type:o,value:i}]}},e,n,r)}(o,a,s,c):ze(Le(r,u||o,void 0,i,!1),a,s,c);l.level="error",Tt(l,{originalException:u,mechanism:{handled:!1,type:"onerror"}})}},xe(n="error",e),we(n,Ie)}(t),He("onerror")),e.onunhandledrejection&&(function(t){var e;xe(e="unhandledrejection",(function(e){var n=qe(),r=n.stackParser,i=n.attachStacktrace;if(Ct()===t&&!le()){var o=function(t){if(x(t))return t;var e=t;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch(t){}return t}(e),a=x(o)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(o)}]}}:Le(r,o,void 0,i,!0);a.level="error",Tt(a,{originalException:o,mechanism:{handled:!1,type:"onunhandledrejection"}})}})),we(e,Me)}(t),He("onunhandledrejection"))}}},Be=$t(Ue,Fe);function ze(t,e,n,r){var i=t.exception=t.exception||{},o=i.values=i.values||[],a=o[0]=o[0]||{},s=a.stacktrace=a.stacktrace||{},c=s.frames=s.frames||[],u=isNaN(parseInt(r,10))?void 0:r,l=isNaN(parseInt(n,10))?void 0:n,d=S(e)&&e.length>0?e:function(){try{return M.document.location.href}catch(t){return""}}();return 0===c.length&&c.push({colno:u,filename:d,function:"?",in_app:!0,lineno:l}),t}function He(t){}function qe(){var t=Ct();return t&&t.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1}}function We(){"console"in a&&u.forEach((function(t){t in a.console&&P(a.console,t,(function(e){return l[t]=e,function(){for(var e=arguments.length,n=new Array(e),r=0;r2?n[2]:void 0;if(i){var o=sn,a=String(i);sn=a,Ee("history",{from:o,to:a})}return t.apply(this,n)}}}var dn=["fatal","error","warning","log","info","debug"];function fn(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var pn=1024,hn="Breadcrumbs",vn=function(t){void 0===t&&(t={});var e=v({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t);return{name:hn,setupOnce:function(){},setup:function(t){var n;e.console&&(n=function(t){return function(e){if(Ct()===t){var n={category:"console",data:{arguments:e.args,logger:"console"},level:(r=e.level,"warn"===r?"warning":dn.includes(r)?r:"log"),message:N(e.args," ")};if("assert"===e.level){if(!1!==e.args[0])return;n.message="Assertion failed: "+(N(e.args.slice(1)," ")||"console.assert"),n.data.arguments=e.args.slice(1)}It(n,{input:e.args,level:e.level})}var r}}(t),xe("console",n),we("console",We)),e.dom&&function(t){xe("dom",t),we("dom",$e)}(function(t,e){return function(n){if(Ct()===t){var r,i,o="object"==typeof e?e.serializeAttribute:void 0,a="object"==typeof e&&"number"==typeof e.maxStringLength?e.maxStringLength:void 0;a&&a>pn&&(a=pn),"string"==typeof o&&(o=[o]);try{var s=n.event,c=function(t){return!!t&&!!t.target}(s)?s.target:s;r=R(c,{keyAttrs:o,maxStringLength:a}),i=function(t){if(!M.HTMLElement)return null;for(var e=t,n=0;n<5;n++){if(!e)return null;if(e instanceof HTMLElement&&e.dataset.sentryComponent)return e.dataset.sentryComponent;e=e.parentNode}return null}(c)}catch(t){r=""}if(0!==r.length){var u={category:"ui."+n.name,message:r};i&&(u.data={"ui.component_name":i}),It(u,{event:n.event,name:n.name,global:n.global})}}}}(t,e.dom)),e.xhr&&function(t){xe("xhr",t),we("xhr",tn)}(function(t){return function(e){if(Ct()===t){var n=e.startTimestamp,r=e.endTimestamp,i=e.xhr[Ze];if(n&&r&&i){var o=i.method,a=i.url,s=i.status_code,c=i.body;It({category:"xhr",data:{method:o,url:a,status_code:s},type:"http"},{xhr:e.xhr,input:c,startTimestamp:n,endTimestamp:r})}}}}(t)),e.fetch&&function(t){var e="fetch";xe(e,t),we(e,rn)}(function(t){return function(e){if(Ct()===t){var n=e.startTimestamp,r=e.endTimestamp;if(r&&(!e.fetchData.url.match(/sentry_key/)||"POST"!==e.fetchData.method))if(e.error)It({category:"fetch",data:e.fetchData,level:"error",type:"http"},{data:e.error,input:e.args,startTimestamp:n,endTimestamp:r});else{var i=e.response;It({category:"fetch",data:v({},e.fetchData,{status_code:i&&i.status}),type:"http"},{input:e.args,response:i,startTimestamp:n,endTimestamp:r})}}}}(t)),e.history&&function(t){var e="history";xe(e,t),we(e,ln)}(function(t){return function(e){if(Ct()===t){var n=e.from,r=e.to,i=fn(ce.location.href),o=n?fn(n):void 0,a=fn(r);o&&o.path||(o=i),i.protocol===a.protocol&&i.host===a.host&&(r=a.relative),i.protocol===o.protocol&&i.host===o.host&&(n=o.relative),It({category:"navigation",data:{from:n,to:r}})}}}(t)),e.sentry&&t.on&&t.on("beforeSendEvent",function(t){return function(e){Ct()===t&&It({category:"sentry."+("transaction"===e.type?"transaction":"event"),event_id:e.event_id,level:e.level,message:J(e)},{event:e})}}(t))}}},mn=$t(hn,vn);function gn(t,e,n,r,i,o,a){if(void 0===n&&(n=250),o.exception&&o.exception.values&&a&&I(a.originalException,Error)){var s,c,u=o.exception.values.length>0?o.exception.values[o.exception.values.length-1]:void 0;u&&(o.exception.values=(s=yn(t,e,i,a.originalException,r,o.exception.values,u,0),c=n,s.map((function(t){return t.value&&(t.value=D(t.value,c)),t}))))}}function yn(t,e,n,r,i,o,a,s){if(o.length>=n+1)return o;var c=[].concat(o);if(I(r[i],Error)){_n(a,s);var u=t(e,r[i]),l=c.length;bn(u,i,l,s),c=yn(t,e,n,r[i],i,[u].concat(c),u,l)}return Array.isArray(r.errors)&&r.errors.forEach((function(r,o){if(I(r,Error)){_n(a,s);var u=t(e,r),l=c.length;bn(u,"errors["+o+"]",l,s),c=yn(t,e,n,r,i,[u].concat(c),u,l)}})),c}function _n(t,e){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=v({},t.mechanism,"AggregateError"===t.type&&{is_exception_group:!0},{exception_id:e})}function bn(t,e,n,r){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=v({},t.mechanism,{type:"chained",source:e,exception_id:n,parent_id:r})}var Sn="LinkedErrors",kn=function(t){void 0===t&&(t={});var e=t.limit||5,n=t.key||"cause";return{name:Sn,setupOnce:function(){},preprocessEvent:function(t,r,i){var o=i.getOptions();gn(Oe,o.stackParser,o.maxValueLength,n,e,t,r)}}},xn=$t(Sn,kn),wn="HttpContext",En=function(){return{name:wn,setupOnce:function(){},preprocessEvent:function(t){if(ce.navigator||ce.location||ce.document){var e=t.request&&t.request.url||ce.location&&ce.location.href,n=(ce.document||{}).referrer,r=(ce.navigator||{}).userAgent,i=v({},t.request&&t.request.headers,n&&{Referer:n},r&&{"User-Agent":r}),o=v({},t.request,e&&{url:e},{headers:i});t.request=o}}}},Tn=$t(wn,En);function In(t,e,n,r,i,o,a){try{var s=t[o](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(r,i)}function Cn(t){return function(){var e=this,n=arguments;return new Promise((function(r,i){var o=t.apply(e,n);function a(t){In(o,r,i,a,s,"next",t)}function s(t){In(o,r,i,a,s,"throw",t)}a(void 0)}))}}function Mn(t){return Mn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Mn(t)}function On(t,e){for(var n=0;n>t/4).toString(16)}))}var Gn=1e3;function $n(){return Date.now()/Gn}var Xn=function(){var t=Vn.performance;if(!t||!t.now)return $n;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/Gn}}(),Qn=function(){var t=Vn.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i";try{for(var n,r=t,i=[],o=0,a=0,s=Array.isArray(e)?e:e.keyAttrs,c=!Array.isArray(e)&&e.maxStringLength||dr;r&&o++<5&&!("html"===(n=pr(r,s))||o>1&&a+3*i.length+n.length>=c);)i.push(n),a+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function pr(t,e){var n,r,i,o,a,s=t,c=[];if(!s||!s.tagName)return"";if(lr.HTMLElement&&s instanceof HTMLElement&&s.dataset&&s.dataset.sentryComponent)return s.dataset.sentryComponent;c.push(s.tagName.toLowerCase());var u=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(u&&u.length)u.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&c.push("#"+s.id),(n=s.className)&&Bn(n))for(r=n.split(/\s+/),a=0;a"}}function gr(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function yr(t){return _r(t,new Map)}function _r(t,e){if(function(t){if(!zn(t))return!1;try{var e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,o=Object.keys(t);i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function Sr(t){return t.transaction}var kr=1;function xr(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=wr(t);return yr({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function wr(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function Er(t){var e=Kr();if(!e)return{};var n=function(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=yr({environment:r.environment||or,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}(wr(t).trace_id||"",e,Gr()),r=Sr(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=wr(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&kr)}(r)),e.emit&&e.emit("createDsc",n),n}function Tr(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=yr(n);c&&Object.keys(c).length&&(t.extra=v({},c,t.extra));var u=yr(r);u&&Object.keys(u).length&&(t.tags=v({},u,t.tags));var l=yr(i);l&&Object.keys(l).length&&(t.user=v({},l,t.user));var d=yr(o);d&&Object.keys(d).length&&(t.contexts=v({},d,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=v({trace:xr(e)},t.contexts);var n=Sr(e);if(n){t.sdkProcessingMetadata=v({dynamicSamplingContext:Er(e)},t.sdkProcessingMetadata);var r=wr(n).description;r&&(t.tags=v({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=v({},t.sdkProcessingMetadata,e)}(t,o)}function Ir(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.sdkProcessingMetadata,c=e.breadcrumbs,u=e.fingerprint,l=e.eventProcessors,d=e.attachments,f=e.propagationContext,p=e.transactionName,h=e.span;Cr(t,"extra",n),Cr(t,"tags",r),Cr(t,"user",i),Cr(t,"contexts",o),Cr(t,"sdkProcessingMetadata",s),a&&(t.level=a),p&&(t.transactionName=p),h&&(t.span=h),c.length&&(t.breadcrumbs=[].concat(t.breadcrumbs,c)),u.length&&(t.fingerprint=[].concat(t.fingerprint,u)),l.length&&(t.eventProcessors=[].concat(t.eventProcessors,l)),d.length&&(t.attachments=[].concat(t.attachments,d)),t.propagationContext=v({},t.propagationContext,f)}function Cr(t,e,n){if(n&&Object.keys(n).length)for(var r in t[e]=v({},t[e]),n)Object.prototype.hasOwnProperty.call(n,r)&&(t[e][r]=n[r])}var Mr,Or=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=Rr()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=v({},this._tags),e._extra=v({},this._extra),e._contexts=v({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=v({},this._sdkProcessingMetadata),e._propagationContext=v({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&br(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=v({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=v({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=v({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=v({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=v({},this._tags,r.tags),this._extra=v({},this._extra,r.extra),this._contexts=v({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(zn(n)){var i=e;this._tags=v({},this._tags,i.tags),this._extra=v({},this._extra,i.extra),this._contexts=v({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=Rr(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=v({timestamp:$n()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),Tr(t,this.getScopeData()),ur([].concat(n,cr(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=v({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:Kn();if(!this._client)return ir.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,v({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:Kn();if(!this._client)return ir.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,v({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:Kn();return this._client?(this._client.captureEvent(t,v({},e,{event_id:n}),this),n):(ir.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function Rr(){return{traceId:Kn(),spanId:Kn().substring(16)}}var Ar=parseFloat("7.119.1"),Dr=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=Ar),this._version=r,e?i=e:(i=new Or).setClient(t),n?o=n:(o=new Or).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;i=i){m[_]="[MaxProperties ~]";break}var b=y[_];m[_]=qr(_,b,p-1,i,o),g++}return d(e),m}function Wr(t,e,n,r,i,o){var a=t.normalizeDepth,s=void 0===a?3:a,c=t.normalizeMaxBreadth,u=void 0===c?1e3:c,l=v({},e,{event_id:e.event_id||n.event_id||Kn(),timestamp:e.timestamp||$n()}),d=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,o=e.maxValueLength,a=void 0===o?250:o;"environment"in t||(t.environment="environment"in e?n:or),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=Fr(t.message,a));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=Fr(s.value,a));var c=t.request;c&&c.url&&(c.url=Fr(c.url,a))}(l,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(l,d),void 0===e.type&&function(t,e){var n,r=Vn._sentryDebugIds;if(r){var i=Vr.get(e);i?n=i:(n=new Map,Vr.set(e,n));var o=Object.keys(r).reduce((function(t,i){var o,a=n.get(i);a?o=a:(o=e(i),n.set(i,o));for(var s=o.length-1;s>=0;s--){var c=o[s];if(c.filename){t[c.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=o[t.filename])}))}))}catch(t){}}}(l,t.stackParser);var f=function(t,e){if(!e)return t;var n=t?t.clone():new Or;return n.update(e),n}(r,n.captureContext);n.mechanism&&function(t,e){var n=function(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}(t);if(n){var r=n.mechanism;if(n.mechanism=v({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=v({},r&&r.data,e.data);n.mechanism.data=i}}}(l,n.mechanism);var p=i&&i.getEventProcessors?i.getEventProcessors():[],h=(Mr||(Mr=new Or),Mr).getScopeData();o&&Ir(h,o.getScopeData()),f&&Ir(h,f.getScopeData());var m=[].concat(n.attachments||[],h.attachments);return m.length&&(n.attachments=m),Tr(l,h),ur([].concat(p,cr(),h.eventProcessors),l,n).then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof s&&s>0?function(t,e,n){if(!t)return null;var r=v({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return v({},t,t.data&&{data:Hr(t.data,e,n)})}))},t.user&&{user:Hr(t.user,e,n)},t.contexts&&{contexts:Hr(t.contexts,e,n)},t.extra&&{extra:Hr(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=Hr(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){var r=wr(t).data;return r&&(t.data=Hr(r,e,n)),t}))),r}(t,s,u):t}))}var Vr=new WeakMap;var Yr=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function Jr(t,e){return Pr().captureException(t,function(t){if(t)return function(t){return t instanceof Or||"function"==typeof t}(t)||function(t){return Object.keys(t).some((function(t){return Yr.includes(t)}))}(t)?{captureContext:t}:t}(e))}function Kr(){return Pr().getClient()}function Gr(){return Pr().getScope()}function $r(t){return"/"===t[t.length-1]?t.slice(0,-1):t}function Xr(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){Zn&&ir.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+zr(o)+"\nError:",e)}}}var ri=Vn,ii="__sentry_xhr_v3__";function oi(){if(ri.XMLHttpRequest){var t=XMLHttpRequest.prototype;hr(t,"open",(function(t){return function(){for(var e=this,n=Date.now(),r=arguments.length,i=new Array(r),o=0;o2?n[2]:void 0;if(i){var o=yi,a=String(i);yi=a,ni("history",{from:o,to:a})}return t.apply(this,n)}}}function ki(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,o=t.port,a=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(o?":"+o:"")+"/"+(r?r+"/":r)+a}function xi(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return wi(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function wi(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0?"prerender":e.type.replace(/_/g,"-")),{name:"LCP",value:-1,rating:"good",delta:0,entries:[],id:"v3-"+Date.now()+"-"+(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}),a=function(t){var e=t[t.length-1];if(e){var n=Math.max(e.startTime-Ai(),0);n=0&&n&&((i=e.value-(r||0))||void 0===r)&&(r=e.value,e.delta=i,t(e))}}(t,o);var c=function(){Pi[o.id]||(a(s.takeRecords()),s.disconnect(),Pi[o.id]=!0,r(!0))};return["keydown","click"].forEach((function(t){Oi.document&&addEventListener(t,c,{once:!0,capture:!0})})),Di(c,!0),c}};function Ui(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){Mi&&ir.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+zr(o)+"\nError:",e)}}}function qi(){return ji((function(t){Hi("lcp",{metric:t}),Fi=t}))}function Wi(t,e){Bi[t]=Bi[t]||[],Bi[t].push(e)}function Vi(t,e,n){return function(){n&&n();var r=Bi[t];if(r){var i=r.indexOf(e);-1!==i&&r.splice(i,1)}}}function Yi(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Ji(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ji(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Ji(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n-1?s.split("/").slice(0,3).join("/"):s.split("/")[0]).split("?")[0]+c)+u+")";var l=e.split("/"),d=c.split("/");l.pop();for(var f,p=Yi(d);!(f=p()).done;){var h=f.value;"."!==h&&(".."===h?l.pop():l.push(h))}return"url("+u+l.join("/")+u+")"}))}var Oo=/^[^ \t\n\r\u000c]+/,Ro=/^[, \t\n\r\u000c]+/;function Ao(t,e){if(!e||""===e.trim())return e;var n=t.createElement("a");return n.href=e,n.href}function Do(t){return Boolean("svg"===t.tagName||t.ownerSVGElement)}function No(){var t=document.createElement("a");return t.href="",t.href}function Lo(t,e,n,r,i,o){return r?"src"===n||"href"===n&&("use"!==e||"#"!==r[0])||"xlink:href"===n&&"#"!==r[0]?Ao(t,r):"background"!==n||"table"!==e&&"td"!==e&&"th"!==e?"srcset"===n?function(t,e){if(""===e.trim())return e;var n=0;function r(t){var r,i=t.exec(e.substring(n));return i?(r=i[0],n+=r.length,r):""}for(var i=[];r(Ro),!(n>=e.length);){var o=r(Oo);if(","===o.slice(-1))o=Ao(t,o.substring(0,o.length-1)),i.push(o);else{var a="";o=Ao(t,o);for(var s=!1;;){var c=e.charAt(n);if(""===c){i.push((o+a).trim());break}if(s)")"===c&&(s=!1);else{if(","===c){n+=1,i.push((o+a).trim());break}"("===c&&(s=!0)}a+=c,n+=1}}}return i.join(", ")}(t,r):"style"===n?Mo(r,No()):"object"===e&&"data"===n?Ao(t,r):"function"==typeof o?o(n,r,i):r:Ao(t,r):r}function Po(t,e,n){return("video"===t||"audio"===t)&&"autoplay"===e}function jo(t,e,n,r){return void 0===n&&(n=1/0),void 0===r&&(r=0),t?t.nodeType!==t.ELEMENT_NODE||r>n?-1:e(t)?r:jo(t.parentNode,e,n,r+1):-1}function Uo(t,e){return function(n){var r=n;if(null===r)return!1;try{if(t)if("string"==typeof t){if(r.matches("."+t))return!0}else if(function(t,e){for(var n=t.classList.length;n--;){var r=t.classList[n];if(e.test(r))return!0}return!1}(r,t))return!0;return!(!e||!r.matches(e))}catch(t){return!1}}}function Fo(t,e,n,r,i,o){try{var a=t.nodeType===t.ELEMENT_NODE?t:t.parentElement;if(null===a)return!1;if("INPUT"===a.tagName){var s=a.getAttribute("autocomplete");if(["current-password","new-password","cc-number","cc-exp","cc-exp-month","cc-exp-year","cc-csc"].includes(s))return!0}var c=-1,u=-1;if(o){if((u=jo(a,Uo(r,i)))<0)return!0;c=jo(a,Uo(e,n),u>=0?u:1/0)}else{if((c=jo(a,Uo(e,n)))<0)return!1;u=jo(a,Uo(r,i),c>=0?c:1/0)}return c>=0?!(u>=0)||c<=u:!(u>=0||!o)}catch(t){}return!!o}function Bo(t){return null==t?"":t.toLowerCase()}function zo(t,e){var n,r=e.doc,i=e.mirror,o=e.blockClass,a=e.blockSelector,s=e.unblockSelector,c=e.maskAllText,u=e.maskTextClass,l=e.unmaskTextClass,d=e.maskTextSelector,f=e.unmaskTextSelector,p=e.skipChild,h=void 0!==p&&p,v=e.inlineStylesheet,m=void 0===v||v,g=e.maskInputOptions,y=void 0===g?{}:g,_=e.maskAttributeFn,b=e.maskTextFn,S=e.maskInputFn,k=e.slimDOMOptions,x=e.dataURLOptions,w=void 0===x?{}:x,E=e.inlineImages,T=void 0!==E&&E,I=e.recordCanvas,C=void 0!==I&&I,M=e.onSerialize,O=e.onIframeLoad,R=e.iframeLoadTimeout,A=void 0===R?5e3:R,D=e.onStylesheetLoad,N=e.stylesheetLoadTimeout,L=void 0===N?5e3:N,P=e.keepIframeSrcFn,j=void 0===P?function(){return!1}:P,U=e.newlyAddedElement,F=void 0!==U&&U,B=e.preserveWhiteSpace,z=void 0===B||B,H=function(t,e){var n=e.doc,r=e.mirror,i=e.blockClass,o=e.blockSelector,a=e.unblockSelector,s=e.maskAllText,c=e.maskAttributeFn,u=e.maskTextClass,l=e.unmaskTextClass,d=e.maskTextSelector,f=e.unmaskTextSelector,p=e.inlineStylesheet,h=e.maskInputOptions,v=void 0===h?{}:h,m=e.maskTextFn,g=e.maskInputFn,y=e.dataURLOptions,_=void 0===y?{}:y,b=e.inlineImages,S=e.recordCanvas,k=e.keepIframeSrcFn,x=e.newlyAddedElement,w=void 0!==x&&x,E=function(t,e){if(e.hasNode(t)){var n=e.getId(t);return 1===n?void 0:n}}(n,r);switch(t.nodeType){case t.DOCUMENT_NODE:return"CSS1Compat"!==t.compatMode?{type:Ki.Document,childNodes:[],compatMode:t.compatMode}:{type:Ki.Document,childNodes:[]};case t.DOCUMENT_TYPE_NODE:return{type:Ki.DocumentType,name:t.name,publicId:t.publicId,systemId:t.systemId,rootId:E};case t.ELEMENT_NODE:return function(t,e){for(var n,r=e.doc,i=e.inlineStylesheet,o=e.maskInputOptions,a=void 0===o?{}:o,s=e.maskAttributeFn,c=e.maskInputFn,u=e.dataURLOptions,l=void 0===u?{}:u,d=e.inlineImages,f=e.recordCanvas,p=e.keepIframeSrcFn,h=e.newlyAddedElement,v=void 0!==h&&h,m=e.rootId,g=e.maskTextClass,y=e.unmaskTextClass,_=e.maskTextSelector,b=e.unmaskTextSelector,S=function(t,e,n,r){try{if(r&&t.matches(r))return!1;if("string"==typeof e){if(t.classList.contains(e))return!0}else for(var i=t.classList.length;i--;){var o=t.classList[i];if(e.test(o))return!0}if(n)return t.matches(n)}catch(t){}return!1}(t,e.blockClass,e.blockSelector,e.unblockSelector),k=function(t){if(t instanceof HTMLFormElement)return"form";var e=ho(t.tagName);return ko.test(e)?"div":e}(t),x={},w=t.attributes.length,E=0;Ee?(r&&(function(){da("clearTimeout").apply(void 0,arguments)}(r),r=null),i=c,t.apply(l,a)):r||!1===n.trailing||(r=fa((function(){i=!1===n.leading?0:Date.now(),r=null,t.apply(l,a)}),u))}}function Jo(t,e,n,r,i){void 0===i&&(i=window);var o=i.Object.getOwnPropertyDescriptor(t,e);return i.Object.defineProperty(t,e,r?n:{set:function(t){var e=this;fa((function(){n.set.call(e,t)}),0),o&&o.set&&o.set.call(this,t)}}),function(){return Jo(t,e,o||{},!0)}}function Ko(t,e,n){try{if(!(e in t))return function(){};var r=t[e],i=n(r);return"function"==typeof i&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:r}})),t[e]=i,function(){t[e]=r}}catch(t){return function(){}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Vo=new Proxy(Vo,{get:function(t,e,n){return"map"===e&&console.error(Wo),Reflect.get(t,e,n)}}));var Go=Date.now;function $o(t){var e=t.document;return{left:e.scrollingElement?e.scrollingElement.scrollLeft:void 0!==t.pageXOffset?t.pageXOffset:Ho([e,"optionalAccess",function(t){return t.documentElement},"access",function(t){return t.scrollLeft}])||Ho([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.parentElement},"optionalAccess",function(t){return t.scrollLeft}])||Ho([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.scrollLeft}])||0,top:e.scrollingElement?e.scrollingElement.scrollTop:void 0!==t.pageYOffset?t.pageYOffset:Ho([e,"optionalAccess",function(t){return t.documentElement},"access",function(t){return t.scrollTop}])||Ho([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.parentElement},"optionalAccess",function(t){return t.scrollTop}])||Ho([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.scrollTop}])||0}}function Xo(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Qo(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Zo(t){return t?t.nodeType===t.ELEMENT_NODE?t:t.parentElement:null}function ta(t,e,n,r,i){if(!t)return!1;var o=Zo(t);if(!o)return!1;var a=Uo(e,n);if(!i){var s=r&&o.matches(r);return a(o)&&!s}var c=jo(o,a),u=-1;return!(c<0)&&(r&&(u=jo(o,Uo(null,r))),c>-1&&u<0||c=this.length)throw new Error("Position outside of list range");for(var e=this.head,n=0;n0&&this.stylesheetManager.adoptStyleSheets(t.contentDocument.adoptedStyleSheets,this.mirror.getId(t.contentDocument))},e.handleMessage=function(t){var e=t;if("rrweb"===e.data.type&&e.origin===e.data.origin&&t.source){var n=this.crossOriginIframeMap.get(t.source);if(n){var r=this.transformCrossOriginEvent(n,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}},e.transformCrossOriginEvent=function(t,e){var n=this;switch(e.type){case pa.FullSnapshot:this.crossOriginIframeMirror.reset(t),this.crossOriginIframeStyleMirror.reset(t),this.replaceIdOnNode(e.data.node,t);var r=e.data.node.id;return this.crossOriginIframeRootIdMap.set(t,r),this.patchRootIdOnNode(e.data.node,r),{timestamp:e.timestamp,type:pa.IncrementalSnapshot,data:{source:ha.Mutation,adds:[{parentId:this.mirror.getId(t),nextId:null,node:e.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case pa.Meta:case pa.Load:case pa.DomContentLoaded:return!1;case pa.Plugin:return e;case pa.Custom:return this.replaceIds(e.data.payload,t,["id","parentId","previousId","nextId"]),e;case pa.IncrementalSnapshot:switch(e.data.source){case ha.Mutation:return e.data.adds.forEach((function(e){n.replaceIds(e,t,["parentId","nextId","previousId"]),n.replaceIdOnNode(e.node,t);var r=n.crossOriginIframeRootIdMap.get(t);r&&n.patchRootIdOnNode(e.node,r)})),e.data.removes.forEach((function(e){n.replaceIds(e,t,["parentId","id"])})),e.data.attributes.forEach((function(e){n.replaceIds(e,t,["id"])})),e.data.texts.forEach((function(e){n.replaceIds(e,t,["id"])})),e;case ha.Drag:case ha.TouchMove:case ha.MouseMove:return e.data.positions.forEach((function(e){n.replaceIds(e,t,["id"])})),e;case ha.ViewportResize:return!1;case ha.MediaInteraction:case ha.MouseInteraction:case ha.Scroll:case ha.CanvasMutation:case ha.Input:return this.replaceIds(e.data,t,["id"]),e;case ha.StyleSheetRule:case ha.StyleDeclaration:return this.replaceIds(e.data,t,["id"]),this.replaceStyleIds(e.data,t,["styleId"]),e;case ha.Font:return e;case ha.Selection:return e.data.ranges.forEach((function(e){n.replaceIds(e,t,["start","end"])})),e;case ha.AdoptedStyleSheet:return this.replaceIds(e.data,t,["id"]),this.replaceStyleIds(e.data,t,["styleIds"]),Ya([e,"access",function(t){return t.data},"access",function(t){return t.styles},"optionalAccess",function(t){return t.forEach},"call",function(e){return e((function(e){n.replaceStyleIds(e,t,["styleId"])}))}]),e}}return!1},e.replace=function(t,e,n,r){for(var i,o=Yi(r);!(i=o()).done;){var a=i.value;(Array.isArray(e[a])||"number"==typeof e[a])&&(Array.isArray(e[a])?e[a]=t.getIds(n,e[a]):e[a]=t.getId(n,e[a]))}return e},e.replaceIds=function(t,e,n){return this.replace(this.crossOriginIframeMirror,t,e,n)},e.replaceStyleIds=function(t,e,n){return this.replace(this.crossOriginIframeStyleMirror,t,e,n)},e.replaceIdOnNode=function(t,e){var n=this;this.replaceIds(t,e,["id","rootId"]),"childNodes"in t&&t.childNodes.forEach((function(t){n.replaceIdOnNode(t,e)}))},e.patchRootIdOnNode=function(t,e){var n=this;t.type===Ki.Document||t.rootId||(t.rootId=e),"childNodes"in t&&t.childNodes.forEach((function(t){n.patchRootIdOnNode(t,e)}))},t}(),Xa=function(){function t(){}var e=t.prototype;return e.init=function(){},e.addShadowRoot=function(){},e.observeAttachShadow=function(){},e.reset=function(){},t}(),Qa=function(){function t(t){this.shadowDoms=new WeakSet,this.restoreHandlers=[],this.mutationCb=t.mutationCb,this.scrollCb=t.scrollCb,this.bypassOptions=t.bypassOptions,this.mirror=t.mirror,this.init()}var e=t.prototype;return e.init=function(){this.reset(),this.patchAttachShadow(Element,document)},e.addShadowRoot=function(t,e){var n=this;if(so(t)&&!this.shadowDoms.has(t)){this.shadowDoms.add(t);var r=Na(v({},this.bypassOptions,{doc:e,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),t);this.restoreHandlers.push((function(){return r.disconnect()})),this.restoreHandlers.push(La(v({},this.bypassOptions,{scrollCb:this.scrollCb,doc:t,mirror:this.mirror}))),fa((function(){t.adoptedStyleSheets&&t.adoptedStyleSheets.length>0&&n.bypassOptions.stylesheetManager.adoptStyleSheets(t.adoptedStyleSheets,n.mirror.getId(t.host)),n.restoreHandlers.push(za({mirror:n.mirror,stylesheetManager:n.bypassOptions.stylesheetManager},t))}),0)}},e.observeAttachShadow=function(t){t.contentWindow&&t.contentDocument&&this.patchAttachShadow(t.contentWindow.Element,t.contentDocument)},e.patchAttachShadow=function(t,e){var n=this;this.restoreHandlers.push(Ko(t.prototype,"attachShadow",(function(t){return function(r){var i=t.call(this,r);return this.shadowRoot&&ua(this)&&n.addShadowRoot(this.shadowRoot,e),i}})))},e.reset=function(){this.restoreHandlers.forEach((function(t){try{t()}catch(t){}})),this.restoreHandlers=[],this.shadowDoms=new WeakSet},t}(),Za=function(){function t(){}var e=t.prototype;return e.reset=function(){},e.freeze=function(){},e.unfreeze=function(){},e.lock=function(){},e.unlock=function(){},e.snapshot=function(){},t}(),ts=function(){function t(t){this.trackedLinkElements=new WeakSet,this.styleMirror=new sa,this.mutationCb=t.mutationCb,this.adoptedStyleSheetCb=t.adoptedStyleSheetCb}var e=t.prototype;return e.attachLinkElement=function(t,e){"_cssText"in e.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:e.id,attributes:e.attributes}]}),this.trackLinkElement(t)},e.trackLinkElement=function(t){this.trackedLinkElements.has(t)||(this.trackedLinkElements.add(t),this.trackStylesheetInLinkElement(t))},e.adoptStyleSheets=function(t,e){if(0!==t.length){for(var n,r={id:e,styleIds:[]},i=[],o=Yi(t);!(n=o()).done;){var a=n.value,s=void 0;this.styleMirror.has(a)?s=this.styleMirror.getId(a):(s=this.styleMirror.add(a),i.push({styleId:s,rules:Array.from(a.rules||CSSRule,(function(t,e){return{rule:uo(t),index:e}}))})),r.styleIds.push(s)}i.length>0&&(r.styles=i),this.adoptedStyleSheetCb(r)}},e.reset=function(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet},e.trackStylesheetInLinkElement=function(t){},t}(),es=function(){function t(){this.nodeMap=new WeakMap,this.loop=!0,this.periodicallyClear()}var e=t.prototype;return e.periodicallyClear=function(){var t=this;!function(){da("requestAnimationFrame").apply(void 0,arguments)}((function(){t.clear(),t.loop&&t.periodicallyClear()}))},e.inOtherBuffer=function(t,e){var n=this.nodeMap.get(t);return n&&Array.from(n).some((function(t){return t!==e}))},e.add=function(t,e){this.nodeMap.set(t,(this.nodeMap.get(t)||new Set).add(e))},e.clear=function(){this.nodeMap=new WeakMap},e.destroy=function(){this.loop=!1},t}(),ns=new lo;function rs(t){void 0===t&&(t={});var e=t,n=e.emit,r=e.checkoutEveryNms,i=e.checkoutEveryNth,o=e.blockClass,a=void 0===o?"rr-block":o,s=e.blockSelector,c=void 0===s?null:s,u=e.unblockSelector,l=void 0===u?null:u,d=e.ignoreClass,f=void 0===d?"rr-ignore":d,p=e.ignoreSelector,h=void 0===p?null:p,m=e.maskAllText,g=void 0!==m&&m,y=e.maskTextClass,_=void 0===y?"rr-mask":y,b=e.unmaskTextClass,S=void 0===b?null:b,k=e.maskTextSelector,x=void 0===k?null:k,w=e.unmaskTextSelector,E=void 0===w?null:w,T=e.inlineStylesheet,I=void 0===T||T,C=e.maskAllInputs,M=e.maskInputOptions,O=e.slimDOMOptions,R=e.maskAttributeFn,A=e.maskInputFn,D=e.maskTextFn,N=e.maxCanvasSize,L=void 0===N?null:N,P=e.packFn,j=e.sampling,U=void 0===j?{}:j,F=e.dataURLOptions,B=void 0===F?{}:F,z=e.mousemoveWait,H=e.recordCanvas,q=void 0!==H&&H,W=e.recordCrossOriginIframes,V=void 0!==W&&W,Y=e.recordAfter,J=void 0===Y?"DOMContentLoaded"===t.recordAfter?t.recordAfter:"load":Y,K=e.userTriggeredOnInput,G=void 0!==K&&K,$=e.collectFonts,X=void 0!==$&&$,Q=e.inlineImages,Z=void 0!==Q&&Q,tt=e.plugins,et=e.keepIframeSrcFn,nt=void 0===et?function(){return!1}:et,rt=e.ignoreCSSAttributes,it=void 0===rt?new Set([]):rt,ot=e.errorHandler,at=e.onMutation,st=e.getCanvasManager;Ca(ot);var ct=!V||window.parent===window,ut=!1;if(!ct)try{window.parent.document&&(ut=!1)}catch(t){ut=!0}if(ct&&!n)throw new Error("emit function is required");void 0!==z&&void 0===U.mousemove&&(U.mousemove=z),ns.reset();var lt,dt=!0===C?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,radio:!0,checkbox:!0}:void 0!==M?M:{},ft=!0===O||"all"===O?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===O,headMetaDescKeywords:"all"===O}:O||{};!function(t){var e=this;void 0===t&&(t=window),"NodeList"in t&&!t.NodeList.prototype.forEach&&(t.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in t&&!t.DOMTokenList.prototype.forEach&&(t.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=function(){for(var t=arguments.length,n=new Array(t),r=0;r=i,c=r&<&&o.timestamp-lt.timestamp>r;(s||c)&&Tt(!0)}};for(var vt,mt=function(t){Ja({type:pa.IncrementalSnapshot,data:v({source:ha.Mutation},t)})},gt=function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.Scroll},t)})},yt=function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.CanvasMutation},t)})},_t=new ts({mutationCb:mt,adoptedStyleSheetCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.AdoptedStyleSheet},t)})}}),bt="boolean"==typeof __RRWEB_EXCLUDE_IFRAME__&&__RRWEB_EXCLUDE_IFRAME__?new Ga:new $a({mirror:ns,mutationCb:mt,stylesheetManager:_t,recordCrossOriginIframes:V,wrappedEmit:Ja}),St=Yi(tt||[]);!(vt=St()).done;){var kt=vt.value;kt.getMirror&&kt.getMirror({nodeMirror:ns,crossOriginIframeMirror:bt.crossOriginIframeMirror,crossOriginIframeStyleMirror:bt.crossOriginIframeStyleMirror})}var xt=new es,wt=function(t,e){try{return t?t(e):new Za}catch(t){return console.warn("Unable to initialize CanvasManager"),new Za}}(st,{mirror:ns,win:window,mutationCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.CanvasMutation},t)})},recordCanvas:q,blockClass:a,blockSelector:c,unblockSelector:l,maxCanvasSize:L,sampling:U.canvas,dataURLOptions:B,errorHandler:ot}),Et="boolean"==typeof __RRWEB_EXCLUDE_SHADOW_DOM__&&__RRWEB_EXCLUDE_SHADOW_DOM__?new Xa:new Qa({mutationCb:mt,scrollCb:gt,bypassOptions:{onMutation:at,blockClass:a,blockSelector:c,unblockSelector:l,maskAllText:g,maskTextClass:_,unmaskTextClass:S,maskTextSelector:x,unmaskTextSelector:E,inlineStylesheet:I,maskInputOptions:dt,dataURLOptions:B,maskAttributeFn:R,maskTextFn:D,maskInputFn:A,recordCanvas:q,inlineImages:Z,sampling:U,slimDOMOptions:ft,iframeManager:bt,stylesheetManager:_t,canvasManager:wt,keepIframeSrcFn:nt,processedNodeManager:xt},mirror:ns}),Tt=function(t){void 0===t&&(t=!1),Ja({type:pa.Meta,data:{href:window.location.href,width:Qo(),height:Xo()}},t),_t.reset(),Et.init(),Aa.forEach((function(t){return t.lock()}));var e=function(t,e){var n=e||{},r=n.mirror,i=void 0===r?new lo:r,o=n.blockClass,a=n.blockSelector,s=n.unblockSelector,c=n.maskAllText,u=n.maskTextClass,l=n.unmaskTextClass,d=n.maskTextSelector,f=n.unmaskTextSelector,p=n.inlineStylesheet,h=n.inlineImages,v=n.recordCanvas,m=n.maskAllInputs,g=void 0!==m&&m,y=n.slimDOM,_=void 0!==y&&y,b=n.keepIframeSrcFn;return zo(t,{doc:t,mirror:i,blockClass:void 0===o?"rr-block":o,blockSelector:void 0===a?null:a,unblockSelector:void 0===s?null:s,maskAllText:void 0!==c&&c,maskTextClass:void 0===u?"rr-mask":u,unmaskTextClass:void 0===l?null:l,maskTextSelector:void 0===d?null:d,unmaskTextSelector:void 0===f?null:f,skipChild:!1,inlineStylesheet:void 0===p||p,maskInputOptions:!0===g?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0}:!1===g?{}:g,maskAttributeFn:n.maskAttributeFn,maskTextFn:n.maskTextFn,maskInputFn:n.maskInputFn,slimDOMOptions:!0===_||"all"===_?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===_,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===_?{}:_,dataURLOptions:n.dataURLOptions,inlineImages:void 0!==h&&h,recordCanvas:void 0!==v&&v,preserveWhiteSpace:n.preserveWhiteSpace,onSerialize:n.onSerialize,onIframeLoad:n.onIframeLoad,iframeLoadTimeout:n.iframeLoadTimeout,onStylesheetLoad:n.onStylesheetLoad,stylesheetLoadTimeout:n.stylesheetLoadTimeout,keepIframeSrcFn:void 0===b?function(){return!1}:b,newlyAddedElement:!1})}(document,{mirror:ns,blockClass:a,blockSelector:c,unblockSelector:l,maskAllText:g,maskTextClass:_,unmaskTextClass:S,maskTextSelector:x,unmaskTextSelector:E,inlineStylesheet:I,maskAllInputs:dt,maskAttributeFn:R,maskInputFn:A,maskTextFn:D,slimDOM:ft,dataURLOptions:B,recordCanvas:q,inlineImages:Z,onSerialize:function(t){ia(t,ns)&&bt.addIframe(t),oa(t,ns)&&_t.trackLinkElement(t),aa(t)&&Et.addShadowRoot(t.shadowRoot,document)},onIframeLoad:function(t,e){bt.attachIframe(t,e),Et.observeAttachShadow(t)},onStylesheetLoad:function(t,e){_t.attachLinkElement(t,e)},keepIframeSrcFn:nt});if(!e)return console.warn("Failed to snapshot the document");Ja({type:pa.FullSnapshot,data:{node:e,initialOffset:$o(window)}}),Aa.forEach((function(t){return t.unlock()})),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&_t.adoptStyleSheets(document.adoptedStyleSheets,ns.getId(document))};Ka=Tt;try{var It=[],Ct=function(t){return Oa(Ha)({onMutation:at,mutationCb:mt,mousemoveCb:function(t,e){return Ja({type:pa.IncrementalSnapshot,data:{source:e,positions:t}})},mouseInteractionCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.MouseInteraction},t)})},scrollCb:gt,viewportResizeCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.ViewportResize},t)})},inputCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.Input},t)})},mediaInteractionCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.MediaInteraction},t)})},styleSheetRuleCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.StyleSheetRule},t)})},styleDeclarationCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.StyleDeclaration},t)})},canvasMutationCb:yt,fontCb:function(t){return Ja({type:pa.IncrementalSnapshot,data:v({source:ha.Font},t)})},selectionCb:function(t){Ja({type:pa.IncrementalSnapshot,data:v({source:ha.Selection},t)})},customElementCb:function(t){Ja({type:pa.IncrementalSnapshot,data:v({source:ha.CustomElement},t)})},blockClass:a,ignoreClass:f,ignoreSelector:h,maskAllText:g,maskTextClass:_,unmaskTextClass:S,maskTextSelector:x,unmaskTextSelector:E,maskInputOptions:dt,inlineStylesheet:I,sampling:U,recordCanvas:q,inlineImages:Z,userTriggeredOnInput:G,collectFonts:X,doc:t,maskAttributeFn:R,maskInputFn:A,maskTextFn:D,keepIframeSrcFn:nt,blockSelector:c,unblockSelector:l,slimDOMOptions:ft,dataURLOptions:B,mirror:ns,iframeManager:bt,stylesheetManager:_t,shadowDomManager:Et,processedNodeManager:xt,canvasManager:wt,ignoreCSSAttributes:it,plugins:jn([tt,"optionalAccess",function(t){return t.filter},"call",function(t){return t((function(t){return t.observer}))},"optionalAccess",function(t){return t.map},"call",function(t){return t((function(t){return{observer:t.observer,options:t.options,callback:function(e){return Ja({type:pa.Plugin,data:{plugin:t.name,payload:e}})}}}))}])||[]},{})};bt.addLoadListener((function(t){try{It.push(Ct(t.contentDocument))}catch(t){console.warn(t)}}));var Mt=function(){Tt(),It.push(Ct(document))};return"interactive"===document.readyState||"complete"===document.readyState?Mt():(It.push(qo("DOMContentLoaded",(function(){Ja({type:pa.DomContentLoaded,data:{}}),"DOMContentLoaded"===J&&Mt()}))),It.push(qo("load",(function(){Ja({type:pa.Load,data:{}}),"load"===J&&Mt()}),window))),function(){It.forEach((function(t){return t()})),xt.destroy(),Ka=void 0,Ma()}}catch(t){console.warn(t)}}rs.mirror=ns,rs.takeFullSnapshot=function(t){if(!Ka)throw new Error("please take full snapshot after start recording");Ka(t)};var is=3;function os(t){return t>9999999999?t:1e3*t}function as(t){return t>9999999999?t/1e3:t}function ss(t,e){"sentry.transaction"!==e.category&&(["ui.click","ui.input"].includes(e.category)?t.triggerUserActivity():t.checkAndHandleExpiredSession(),t.addUpdate((function(){return t.throttledAddEvent({type:pa.Custom,timestamp:1e3*(e.timestamp||0),data:{tag:"breadcrumb",payload:Hr(e,10,1e3)}}),"console"===e.category})))}var cs,us="button,a";function ls(t){return t.closest(us)||t}function ds(t){var e=fs(t);return e&&e instanceof Element?ls(e):e}function fs(t){return function(t){return"object"==typeof t&&!!t&&"target"in t}(t)?t.target:t}var ps,hs=function(){function t(t,e,n){void 0===n&&(n=ss),this._lastMutation=0,this._lastScroll=0,this._clicks=[],this._timeout=e.timeout/1e3,this._threshold=e.threshold/1e3,this._scollTimeout=e.scrollTimeout/1e3,this._replay=t,this._ignoreSelector=e.ignoreSelector,this._addBreadcrumbEvent=n}var e=t.prototype;return e.addListeners=function(){var t,e=this,n=(t=function(){e._lastMutation=ms()},cs||(cs=[],hr(Gi,"open",(function(t){return function(){if(cs)try{cs.forEach((function(t){return t()}))}catch(t){}for(var e=arguments.length,n=new Array(e),r=0;r-1&&cs.splice(e,1)});this._teardown=function(){n(),e._clicks=[],e._lastMutation=0,e._lastScroll=0}},e.removeListeners=function(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)},e.handleClick=function(t,e){if(!function(t,e){return!vs.includes(t.tagName)||("INPUT"===t.tagName&&!["submit","button"].includes(t.getAttribute("type")||"")||(!("A"!==t.tagName||!(t.hasAttribute("download")||t.hasAttribute("target")&&"_self"!==t.getAttribute("target")))||!(!e||!t.matches(e))))}(e,this._ignoreSelector)&&function(t){return!(!t.data||"number"!=typeof t.data.nodeId||!t.timestamp)}(t)){var n={timestamp:as(t.timestamp),clickBreadcrumb:t,clickCount:0,node:e};this._clicks.some((function(t){return t.node===n.node&&Math.abs(t.timestamp-n.timestamp)<1}))||(this._clicks.push(n),1===this._clicks.length&&this._scheduleCheckClicks())}},e.registerMutation=function(t){void 0===t&&(t=Date.now()),this._lastMutation=as(t)},e.registerScroll=function(t){void 0===t&&(t=Date.now()),this._lastScroll=as(t)},e.registerClick=function(t){var e=ls(t);this._handleMultiClick(e)},e._handleMultiClick=function(t){this._getClicks(t).forEach((function(t){t.clickCount++}))},e._getClicks=function(t){return this._clicks.filter((function(e){return e.node===t}))},e._checkClicks=function(){var t=this,e=[],n=ms();this._clicks.forEach((function(r){!r.mutationAfter&&t._lastMutation&&(r.mutationAfter=r.timestamp<=t._lastMutation?t._lastMutation-r.timestamp:void 0),!r.scrollAfter&&t._lastScroll&&(r.scrollAfter=r.timestamp<=t._lastScroll?t._lastScroll-r.timestamp:void 0),r.timestamp+t._timeout<=n&&e.push(r)}));for(var r=0,i=e;r-1&&(this._generateBreadcrumbs(o),this._clicks.splice(a,1))}this._clicks.length&&this._scheduleCheckClicks()},e._generateBreadcrumbs=function(t){var e=this._replay,n=t.scrollAfter&&t.scrollAfter<=this._scollTimeout,r=t.mutationAfter&&t.mutationAfter<=this._threshold,i=!n&&!r,o=t.clickCount,a=t.clickBreadcrumb;if(i){var s=1e3*Math.min(t.mutationAfter||this._timeout,this._timeout),c=s<1e3*this._timeout?"mutation":"timeout",u={type:"default",message:a.message,timestamp:a.timestamp,category:"ui.slowClickDetected",data:v({},a.data,{url:Gi.location.href,route:e.getCurrentRoute(),timeAfterClickMs:s,endReason:c,clickCount:o||1})};this._addBreadcrumbEvent(e,u)}else if(o>1){var l={type:"default",message:a.message,timestamp:a.timestamp,category:"ui.multiClick",data:v({},a.data,{url:Gi.location.href,route:e.getCurrentRoute(),clickCount:o,metric:!0})};this._addBreadcrumbEvent(e,l)}},e._scheduleCheckClicks=function(){var t=this;this._checkClickTimeout&&clearTimeout(this._checkClickTimeout),this._checkClickTimeout=setTimeout((function(){return t._checkClicks()}),1e3)},t}(),vs=["A","BUTTON","INPUT"];function ms(){return Date.now()/1e3}function gs(t){return v({timestamp:Date.now()/1e3,type:"default"},t)}!function(t){t[t.Document=0]="Document",t[t.DocumentType=1]="DocumentType",t[t.Element=2]="Element",t[t.Text=3]="Text",t[t.CDATA=4]="CDATA",t[t.Comment=5]="Comment"}(ps||(ps={}));var ys=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled","data-sentry-component"]);function _s(t){var e={};for(var n in t)if(ys.has(n)){var r=n;"data-testid"!==n&&"data-test-id"!==n||(r="testId"),e[r]=t[n]}return e}function bs(t,e){var n=rs.mirror.getId(t),r=n&&rs.mirror.getNode(n),i=r&&rs.mirror.getMeta(r),o=i&&function(t){return t.type===ps.Element}(i)?i:null;return{message:e,data:o?{nodeId:n,node:{id:n,tagName:o.tagName,textContent:Array.from(o.childNodes).map((function(t){return t.type===ps.Text&&t.textContent})).filter(Boolean).map((function(t){return t.trim()})).join(""),attributes:_s(o.attributes)}}:{}}}var Ss={resource:function(t){var e=t.entryType,n=t.initiatorType,r=t.name,i=t.responseEnd,o=t.startTime,a=t.decodedBodySize,s=t.encodedBodySize,c=t.responseStatus,u=t.transferSize;return["fetch","xmlhttprequest"].includes(n)?null:{type:e+"."+n,start:xs(o),end:xs(i),name:r,data:{size:u,statusCode:c,decodedBodySize:a,encodedBodySize:s}}},paint:function(t){var e=t.duration,n=t.entryType,r=t.name,i=xs(t.startTime);return{type:n,name:r,start:i,end:i+e,data:void 0}},navigation:function(t){var e=t.entryType,n=t.name,r=t.decodedBodySize,i=t.duration,o=t.domComplete,a=t.encodedBodySize,s=t.domContentLoadedEventStart,c=t.domContentLoadedEventEnd,u=t.domInteractive,l=t.loadEventStart,d=t.loadEventEnd,f=t.redirectCount,p=t.startTime,h=t.transferSize,v=t.type;return 0===i?null:{type:e+"."+v,start:xs(p),end:xs(o),name:n,data:{size:h,decodedBodySize:r,encodedBodySize:a,duration:i,domInteractive:u,domContentLoadedEventStart:s,domContentLoadedEventEnd:c,loadEventStart:l,loadEventEnd:d,domComplete:o,redirectCount:f}}}};function ks(t){return Ss[t.entryType]?Ss[t.entryType](t):null}function xs(t){return((Qn||Gi.performance.timeOrigin)+t)/1e3}function ws(t){function e(e){t.performanceEntries.includes(e)||t.performanceEntries.push(e)}function n(t){t.entries.forEach(e)}var r,i=[];return["navigation","paint","resource"].forEach((function(t){i.push(function(t,e){return Wi(t,e),zi[t]||(function(t){var e={};"event"===t&&(e.durationThreshold=0),Li(t,(function(e){Hi(t,{entries:e})}),e)}(t),zi[t]=!0),Vi(t,e)}(t,n))})),i.push((void 0===r&&(r=!1),function(t,e,n,r,i){var o;return void 0===i&&(i=!1),Wi(t,e),zi[t]||(o=n(),zi[t]=!0),r&&e({metric:r}),Vi(t,e,i?o:void 0)}("lcp",(function(e){var n=e.metric;t.replayPerformanceEntries.push(function(t){var e=t.entries,n=e[e.length-1],r=n?n.element:void 0,i=t.value,o=xs(i);return{type:"largest-contentful-paint",name:"largest-contentful-paint",start:o,end:o,data:{value:i,size:i,nodeId:r?rs.mirror.getId(r):void 0}}}(n))}),qi,Fi,r))),function(){i.forEach((function(t){return t()}))}}var Es=!1;function Ts(t,e){Es&&(ir.info(t),e&&Cs(t))}function Is(t,e){Es&&(ir.info(t),e&&setTimeout((function(){Cs(t)}),0))}function Cs(t){var e,n;e={category:"console",data:{logger:"replay"},level:"info",message:t},n={level:"info"},Pr().addBreadcrumb(e,n)}var Ms=function(t){function e(){return t.call(this,"Event buffer exceeded maximum size of "+ro+".")||this}return Dn(e,t),e}(Pn(Error)),Os=function(){function t(){this.events=[],this._totalSize=0,this.hasCheckout=!1}var e=t.prototype;return e.destroy=function(){this.events=[]},e.addEvent=function(){var t=Cn(dt().mark((function t(e){var n;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=JSON.stringify(e).length,this._totalSize+=n,!(this._totalSize>ro)){t.next=4;break}throw new Ms;case 4:this.events.push(e);case 5:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e.finish=function(){var t=this;return new Promise((function(e){var n=t.events;t.clear(),e(JSON.stringify(n))}))},e.clear=function(){this.events=[],this._totalSize=0,this.hasCheckout=!1},e.getEarliestTimestamp=function(){var t=this.events.map((function(t){return t.timestamp})).sort()[0];return t?os(t):null},Rn(t,[{key:"hasEvents",get:function(){return this.events.length>0}},{key:"type",get:function(){return"sync"}}]),t}(),Rs=function(){function t(t){this._worker=t,this._id=0}var e=t.prototype;return e.ensureReady=function(){var t=this;return this._ensureReadyPromise||(this._ensureReadyPromise=new Promise((function(e,n){t._worker.addEventListener("message",(function(t){t.data.success?e():n()}),{once:!0}),t._worker.addEventListener("error",(function(t){n(t)}),{once:!0})}))),this._ensureReadyPromise},e.destroy=function(){Ts("[Replay] Destroying compression worker"),this._worker.terminate()},e.postMessage=function(t,e){var n=this,r=this._getAndIncrementId();return new Promise((function(i,o){n._worker.addEventListener("message",(function e(a){var s=a.data;if(s.method===t&&s.id===r){if(n._worker.removeEventListener("message",e),!s.success)return Es&&ir.error("[Replay]",s.response),void o(new Error("Error in compression worker"));i(s.response)}})),n._worker.postMessage({id:r,method:t,arg:e})}))},e._getAndIncrementId=function(){return this._id++},t}(),As=function(){function t(t){this._worker=new Rs(t),this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1}var e=t.prototype;return e.ensureReady=function(){return this._worker.ensureReady()},e.destroy=function(){this._worker.destroy()},e.addEvent=function(t){var e=os(t.timestamp);(!this._earliestTimestamp||ero?Promise.reject(new Ms):this._sendEventToWorker(n)},e.finish=function(){return this._finishRequest()},e.clear=function(){this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this._worker.postMessage("clear").then(null,(function(t){Es&&ir.warn('[Replay] Sending "clear" message to worker failed',t)}))},e.getEarliestTimestamp=function(){return this._earliestTimestamp},e._sendEventToWorker=function(t){return this._worker.postMessage("addEvent",t)},e._finishRequest=function(){var t=Cn(dt().mark((function t(){var e;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this._worker.postMessage("finish");case 2:return e=t.sent,this._earliestTimestamp=null,this._totalSize=0,t.abrupt("return",e);case 6:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),Rn(t,[{key:"hasEvents",get:function(){return!!this._earliestTimestamp}},{key:"type",get:function(){return"worker"}}]),t}(),Ds=function(){function t(t){this._fallback=new Os,this._compression=new As(t),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}var e=t.prototype;return e.destroy=function(){this._fallback.destroy(),this._compression.destroy()},e.clear=function(){return this._used.clear()},e.getEarliestTimestamp=function(){return this._used.getEarliestTimestamp()},e.addEvent=function(t){return this._used.addEvent(t)},e.finish=function(){var t=Cn(dt().mark((function t(){return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.ensureWorkerIsLoaded();case 2:return t.abrupt("return",this._used.finish());case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),e.ensureWorkerIsLoaded=function(){return this._ensureWorkerIsLoadedPromise},e._ensureWorkerIsLoaded=function(){var t=Cn(dt().mark((function t(){return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this._compression.ensureReady();case 3:t.next=9;break;case 5:return t.prev=5,t.t0=t.catch(0),Ts("[Replay] Failed to load the compression worker, falling back to simple buffer"),t.abrupt("return");case 9:return t.next=11,this._switchToCompressionWorker();case 11:case"end":return t.stop()}}),t,this,[[0,5]])})));return function(){return t.apply(this,arguments)}}(),e._switchToCompressionWorker=function(){var t=Cn(dt().mark((function t(){var e,n,r,i,o,a,s;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:for(e=this._fallback,n=e.events,r=e.hasCheckout,i=[],o=Yi(n);!(a=o()).done;)s=a.value,i.push(this._compression.addEvent(s));return this._compression.hasCheckout=r,this._used=this._compression,t.prev=5,t.next=8,Promise.all(i);case 8:t.next=13;break;case 10:t.prev=10,t.t0=t.catch(5),Es&&ir.warn("[Replay] Failed to add events when switching buffers.",t.t0);case 13:case"end":return t.stop()}}),t,this,[[5,10]])})));return function(){return t.apply(this,arguments)}}(),Rn(t,[{key:"type",get:function(){return this._used.type}},{key:"hasEvents",get:function(){return this._used.hasEvents}},{key:"hasCheckout",get:function(){return this._used.hasCheckout},set:function(t){this._used.hasCheckout=t}}]),t}();function Ns(){try{return"sessionStorage"in Gi&&!!Gi.sessionStorage}catch(t){return!1}}function Ls(t){return void 0!==t&&Math.random()t.getContext().initialTimestamp+t.getOptions().maxReplayDuration&&(Ts("[Replay] Skipping event with timestamp "+n+" because it is after maxReplayDuration",t.getOptions()._experiments.traceInternals),1))}function Js(t,e){try{if("function"==typeof e&&function(t){return t.type===pa.Custom}(t))return e(t)}catch(t){return Es&&ir.error("[Replay] An error occured in the `beforeAddRecordingEvent` callback, skipping the event...",t),null}return t}function Ks(t){return!t.type}function Gs(t){return"transaction"===t.type}function $s(t){return"feedback"===t.type}function Xs(t){var e=function(){var t=Kr();if(!t)return!1;var e=t.getTransport();return e&&e.send.__sentry__baseTransport__||!1}();return function(n,r){if(t.isEnabled()&&(Ks(n)||Gs(n))){var i=r&&r.statusCode;e&&(!i||i<200||i>=300)||(Gs(n)?function(t,e){var n=t.getContext();e.contexts&&e.contexts.trace&&e.contexts.trace.trace_id&&n.traceIds.size<100&&n.traceIds.add(e.contexts.trace.trace_id)}(t,n):function(t,e){var n=t.getContext();if(e.event_id&&n.errorIds.size<100&&n.errorIds.add(e.event_id),"buffer"===t.recordingMode&&e.tags&&e.tags.replayId){var r=t.getOptions().beforeErrorSampling;("function"!=typeof r||r(e))&&setTimeout((function(){t.sendBufferedReplayOrFlush()}))}}(t,n))}}}function Qs(t,e){return e.map((function(e){var n=e.type,r=e.start,i=e.end,o=e.name,a=e.data,s=t.throttledAddEvent({type:pa.Custom,timestamp:r,data:{tag:"performanceSpan",payload:{op:n,description:o,startTimestamp:r,endTimestamp:i,data:a}}});return"string"==typeof s?Promise.resolve(null):s}))}function Zs(t,e){t.isEnabled()&&null!==e&&(function(t,e){return(!Es||!t.getOptions()._experiments.traceInternals)&&function(t,e){var n=e&&function(t){return void 0!==t.getClient}(e)?e.getClient():e,r=n&&n.getDsn(),i=n&&n.getOptions().tunnel;return function(t,e){return!!e&&t.includes(e.host)}(t,r)||function(t,e){return!!e&&$r(t)===$r(e)}(t,i)}(e,Kr())}(t,e.name)||t.addUpdate((function(){return Qs(t,[e]),!0})))}function tc(t,e){if(t)try{if("string"==typeof t)return e.encode(t).length;if(t instanceof URLSearchParams)return e.encode(t.toString()).length;if(t instanceof FormData){var n=cc(t);return e.encode(n).length}if(t instanceof Blob)return t.size;if(t instanceof ArrayBuffer)return t.byteLength}catch(t){}}function ec(t){if(t){var e=parseInt(t,10);return isNaN(e)?void 0:e}}function nc(t){try{if("string"==typeof t)return[t];if(t instanceof URLSearchParams)return[t.toString()];if(t instanceof FormData)return[cc(t)];if(!t)return[void 0]}catch(e){return Es&&ir.warn("[Replay] Failed to serialize body",t),[void 0,"BODY_PARSE_ERROR"]}return Es&&ir.info("[Replay] Skipping network body because of body type",t),[void 0,"UNPARSEABLE_BODY_TYPE"]}function rc(t,e){if(!t)return{headers:{},size:void 0,_meta:{warnings:[e]}};var n=v({},t._meta),r=n.warnings||[];return n.warnings=[].concat(r,[e]),t._meta=n,t}function ic(t,e){return e?{type:t,start:e.startTimestamp/1e3,end:e.endTimestamp/1e3,name:e.url,data:yr({method:e.method,statusCode:e.statusCode,request:e.request,response:e.response})}:null}function oc(t){return{headers:{},size:t,_meta:{warnings:["URL_SKIPPED"]}}}function ac(t,e,n){if(e||0!==Object.keys(t).length){if(!e)return{headers:t};if(!n)return{headers:t,size:e};var r={headers:t,size:e},i=function(t){if(!t||"string"!=typeof t)return{body:t};var e,n,r,i=t.length>eo,o=(n=(e=t)[0],r=e[e.length-1],"["===n&&"]"===r||"{"===n&&"}"===r);if(i){var a=t.slice(0,eo);return o?{body:a,warnings:["MAYBE_JSON_TRUNCATED"]}:{body:a+"…",warnings:["TEXT_TRUNCATED"]}}if(o)try{return{body:JSON.parse(t)}}catch(t){}return{body:t}}(n),o=i.body,a=i.warnings;return r.body=o,a&&a.length>0&&(r._meta={warnings:a}),r}}function sc(t,e){return Object.keys(t).reduce((function(n,r){var i=r.toLowerCase();return e.includes(i)&&t[r]&&(n[i]=t[r]),n}),{})}function cc(t){return new URLSearchParams(t).toString()}function uc(t,e){var n,r,i,o=function(t,e){if(void 0===e&&(e=Gi.document.baseURI),t.startsWith("http://")||t.startsWith("https://")||t.startsWith(Gi.location.origin))return t;var n=new URL(t,e);if(n.origin!==new URL(e).origin)return t;var r=n.href;return!t.endsWith("/")&&r.endsWith("/")?r.slice(0,-1):r}(t);return n=o,void 0===(r=e)&&(r=[]),void 0===i&&(i=!1),r.some((function(t){return function(t,e,n){return void 0===n&&(n=!1),!!Bn(t)&&(Fn(e,"RegExp")?e.test(t):!!Bn(e)&&(n?t===e:t.includes(e)))}(n,t,i)}))}function lc(){return(lc=Cn(dt().mark((function t(e,n,r){var i,o;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,dc(e,n,r);case 3:i=t.sent,o=ic("resource.fetch",i),Zs(r.replay,o),t.next=11;break;case 8:t.prev=8,t.t0=t.catch(0),Es&&ir.error("[Replay] Failed to capture fetch breadcrumb",t.t0);case 11:case"end":return t.stop()}}),t,null,[[0,8]])})))).apply(this,arguments)}function dc(t,e,n){return fc.apply(this,arguments)}function fc(){return(fc=Cn(dt().mark((function t(e,n,r){var i,o,a,s,c,u,l,d,f,p,h,v,m,g,y;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=Date.now(),o=n.startTimestamp,a=void 0===o?i:o,s=n.endTimestamp,c=void 0===s?i:s,u=e.data,l=u.url,d=u.method,f=u.status_code,p=void 0===f?0:f,h=u.request_body_size,v=u.response_body_size,m=uc(l,r.networkDetailAllowUrls)&&!uc(l,r.networkDetailDenyUrls),g=m?pc(r,n.input,h):oc(h),t.next=7,hc(m,r,n.response,v);case 7:return y=t.sent,t.abrupt("return",{startTimestamp:a,endTimestamp:c,url:l,method:d,statusCode:p,request:g,response:y});case 9:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function pc(t,e,n){var r,i,o=t.networkCaptureBodies,a=t.networkRequestHeaders,s=e?(i=a,1===(r=e).length&&"string"!=typeof r[0]?Sc(r[0],i):2===r.length?Sc(r[1],i):{}):{};if(!o)return ac(s,n,void 0);var c=nc(_c(e)),u=c[0],l=c[1],d=ac(s,n,u);return l?rc(d,l):d}function hc(t,e,n,r){return vc.apply(this,arguments)}function vc(){return(vc=Cn(dt().mark((function t(e,n,r,i){var o,a,s,c,u,l,d,f;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=n.networkCaptureBodies,a=n.textEncoder,s=n.networkResponseHeaders,e||void 0===i){t.next=3;break}return t.abrupt("return",oc(i));case 3:if(c=r?bc(r.headers,s):{},r&&(o||void 0===i)){t.next=6;break}return t.abrupt("return",ac(c,i,void 0));case 6:return t.next=8,gc(r);case 8:if(u=t.sent,l=u[0],d=u[1],f=mc(l,{networkCaptureBodies:o,textEncoder:a,responseBodySize:i,captureDetails:e,headers:c}),!d){t.next=14;break}return t.abrupt("return",rc(f,d));case 14:return t.abrupt("return",f);case 15:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function mc(t,e){var n=e.networkCaptureBodies,r=e.textEncoder,i=e.responseBodySize,o=e.captureDetails,a=e.headers;try{var s=t&&t.length&&void 0===i?tc(t,r):i;return o?ac(a,s,n?t:void 0):oc(s)}catch(t){return Es&&ir.warn("[Replay] Failed to serialize response body",t),ac(a,i,void 0)}}function gc(t){return yc.apply(this,arguments)}function yc(){return(yc=Cn(dt().mark((function t(e){var n,r;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=kc(e)){t.next=3;break}return t.abrupt("return",[void 0,"BODY_PARSE_ERROR"]);case 3:return t.prev=3,t.next=6,xc(n);case 6:return r=t.sent,t.abrupt("return",[r]);case 10:return t.prev=10,t.t0=t.catch(3),Es&&ir.warn("[Replay] Failed to get text body from response",t.t0),t.abrupt("return",[void 0,"BODY_PARSE_ERROR"]);case 14:case"end":return t.stop()}}),t,null,[[3,10]])})))).apply(this,arguments)}function _c(t){if(void 0===t&&(t=[]),2===t.length&&"object"==typeof t[1])return t[1].body}function bc(t,e){var n={};return e.forEach((function(e){t.get(e)&&(n[e]=t.get(e))})),n}function Sc(t,e){if(!t)return{};var n=t.headers;return n?n instanceof Headers?bc(n,e):Array.isArray(n)?{}:sc(n,e):{}}function kc(t){try{return t.clone()}catch(t){Es&&ir.warn("[Replay] Failed to clone response body",t)}}function xc(t){return new Promise((function(e,n){var r=setTimeout((function(){return n(new Error("Timeout while trying to read response body"))}),500);(function(t){return wc.apply(this,arguments)})(t).then((function(t){return e(t)}),(function(t){return n(t)})).finally((function(){return clearTimeout(r)}))}))}function wc(){return(wc=Cn(dt().mark((function t(e){return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.text();case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function Ec(){return(Ec=Cn(dt().mark((function t(e,n,r){var i,o;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:try{i=Tc(e,n,r),o=ic("resource.xhr",i),Zs(r.replay,o)}catch(t){Es&&ir.error("[Replay] Failed to capture xhr breadcrumb",t)}case 1:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function Tc(t,e,n){var r=Date.now(),i=e.startTimestamp,o=void 0===i?r:i,a=e.endTimestamp,s=void 0===a?r:a,c=e.input,u=e.xhr,l=t.data,d=l.url,f=l.method,p=l.status_code,h=void 0===p?0:p,v=l.request_body_size,m=l.response_body_size;if(!d)return null;if(!u||!uc(d,n.networkDetailAllowUrls)||uc(d,n.networkDetailDenyUrls))return{startTimestamp:o,endTimestamp:s,url:d,method:f,statusCode:h,request:oc(v),response:oc(m)};var g=u[ii],y=g?sc(g.request_headers,n.networkRequestHeaders):{},_=sc(function(t){var e=t.getAllResponseHeaders();return e?e.split("\r\n").reduce((function(t,e){var n=e.split(": "),r=n[0],i=n[1];return t[r.toLowerCase()]=i,t}),{}):{}}(u),n.networkResponseHeaders),b=n.networkCaptureBodies?nc(c):[void 0],S=b[0],k=b[1],x=n.networkCaptureBodies?function(t){var e=[];try{return[t.responseText]}catch(t){e.push(t)}try{return function(t,e){try{if("string"==typeof t)return[t];if(t instanceof Document)return[t.body.outerHTML];if("json"===e&&t&&"object"==typeof t)return[JSON.stringify(t)];if(!t)return[void 0]}catch(e){return Es&&ir.warn("[Replay] Failed to serialize body",t),[void 0,"BODY_PARSE_ERROR"]}return Es&&ir.info("[Replay] Skipping network body because of body type",t),[void 0,"UNPARSEABLE_BODY_TYPE"]}(t.response,t.responseType)}catch(t){e.push(t)}return Es&&ir.warn.apply(ir,["[Replay] Failed to get xhr response body"].concat(e)),[void 0]}(u):[void 0],w=x[0],E=x[1],T=ac(y,v,S),I=ac(_,m,w);return{startTimestamp:o,endTimestamp:s,url:d,method:f,statusCode:h,request:k?rc(T,k):T,response:E?rc(I,E):I}}function Ic(t){var e,n=Kr();try{var r=new TextEncoder,i=t.getOptions(),o={replay:t,textEncoder:r,networkDetailAllowUrls:i.networkDetailAllowUrls,networkDetailDenyUrls:i.networkDetailDenyUrls,networkCaptureBodies:i.networkCaptureBodies,networkRequestHeaders:i.networkRequestHeaders,networkResponseHeaders:i.networkResponseHeaders};n&&n.on?n.on("beforeAddBreadcrumb",(function(t,e){return function(t,e,n){if(e.data)try{(function(t){return"xhr"===t.category})(e)&&function(t){return t&&t.xhr}(n)&&(function(t,e,n){var r=e.xhr,i=e.input;if(r){var o=tc(i,n.textEncoder),a=r.getResponseHeader("content-length")?ec(r.getResponseHeader("content-length")):function(t,e,n){try{return tc("json"===e&&t&&"object"==typeof t?JSON.stringify(t):t,n)}catch(t){return}}(r.response,r.responseType,n.textEncoder);void 0!==o&&(t.data.request_body_size=o),void 0!==a&&(t.data.response_body_size=a)}}(e,n,t),function(t,e,n){Ec.apply(this,arguments)}(e,n,t)),function(t){return"fetch"===t.category}(e)&&function(t){return t&&t.response}(n)&&(function(t,e,n){var r=e.input,i=e.response,o=tc(r?_c(r):void 0,n.textEncoder),a=i?ec(i.headers.get("content-length")):void 0;void 0!==o&&(t.data.request_body_size=o),void 0!==a&&(t.data.response_body_size=a)}(e,n,t),function(t,e,n){lc.apply(this,arguments)}(e,n,t))}catch(t){Es&&ir.warn("Error when enriching network breadcrumb")}}(o,t,e)})):(e=function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.fetchData,i=t.response;if(!n)return null;var o=r.method;return{type:"resource.fetch",start:e/1e3,end:n/1e3,name:r.url,data:{method:o,statusCode:i?i.status:void 0}}}(e);Zs(t,n)}}}(t),ti("fetch",e),ei("fetch",ci),function(t){ti("xhr",t),ei("xhr",oi)}(function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.xhr[ii];if(!e||!n||!r)return null;var i=r.method,o=r.url,a=r.status_code;return void 0===o?null:{type:"resource.xhr",name:o,start:e/1e3,end:n/1e3,data:{method:i,statusCode:a}}}(e);Zs(t,n)}}}(t)))}catch(t){}}var Cc=null;function Mc(t){var e,n,r=Gr(),i=Kr();r.addScopeListener(function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.getLastBreadcrumb&&t.getLastBreadcrumb();return Cc!==e&&e?(Cc=e,!e.category||["fetch","xhr","sentry.event","sentry.transaction"].includes(e.category)||e.category.startsWith("ui.")?null:"console"===e.category?function(t){var e=t.data&&t.data.arguments;if(!Array.isArray(e)||0===e.length)return gs(t);var n=!1,r=e.map((function(t){if(!t)return t;if("string"==typeof t)return t.length>no?(n=!0,t.slice(0,no)+"…"):t;if("object"==typeof t)try{var e=Hr(t,7);return JSON.stringify(e).length>no?(n=!0,JSON.stringify(e,null,2).slice(0,no)+"…"):e}catch(t){}return t}));return gs(v({},t,{data:v({},t.data,{arguments:r},n?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{})}))}(e):gs(e)):null}(e);n&&ss(t,n)}}}(t)),ti("dom",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=function(t){var e,n="click"===t.name,r=null;try{e=fr(r=n?ds(t.event):fs(t.event),{maxStringLength:200})||""}catch(t){e=""}return{target:r,message:e}}(t),n=e.target,r=e.message;return gs(v({category:"ui."+t.name},bs(n,r)))}(e);if(n){var r="click"===e.name,i=r?e.event:void 0;!(r&&t.clickDetector&&i&&i.target)||i.altKey||i.metaKey||i.ctrlKey||i.shiftKey||(o=t.clickDetector,a=n,s=ds(e.event),o.handleClick(a,s)),ss(t,n)}}var o,a,s}}(t)),ei("dom",mi),e=function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.from,n=t.to,r=Date.now()/1e3;return{type:"navigation.push",start:r,end:r,name:n,data:{previous:e}}}(e);null!==n&&(t.getContext().urls.push(n.name),t.triggerUserActivity(),t.addUpdate((function(){return Qs(t,[n]),!1})))}}}(t),ti(n="history",e),ei(n,Si),Ic(t);var o=function(t,e){void 0===e&&(e=!1);var n=e?Xs(t):void 0;return Object.assign((function(e,r){if(!t.isEnabled())return e;if(function(t){return"replay_event"===t.type}(e))return delete e.breadcrumbs,e;if(!Ks(e)&&!Gs(e)&&!$s(e))return e;if(!t.checkAndHandleExpiredSession())return e;if($s(e))return t.flush(),e.contexts.feedback.replay_id=t.getSessionId(),function(t,e){t.triggerUserActivity(),t.addUpdate((function(){return!e.timestamp||(t.throttledAddEvent({type:pa.Custom,timestamp:1e3*e.timestamp,data:{tag:"breadcrumb",payload:{timestamp:e.timestamp,type:"default",category:"sentry.feedback",data:{feedbackId:e.event_id}}}}),!1)}))}(t,e),e;if(function(t,e){return!(t.type||!t.exception||!t.exception.values||!t.exception.values.length||!e.originalException||!e.originalException.__rrweb__)}(e,r)&&!t.getOptions()._experiments.captureExceptions)return Es&&ir.log("[Replay] Ignoring error from rrweb internals",e),null;var i=function(t,e){return"buffer"===t.recordingMode&&e.message!==Qi&&!(!e.exception||e.type)&&Ls(t.getOptions().errorSampleRate)}(t,e);return(i||"session"===t.recordingMode)&&(e.tags=v({},e.tags,{replayId:t.getSessionId()})),n&&n(e,{statusCode:200}),e}),{id:"Replay"})}(t,!Oc(i));i&&i.addEventProcessor?i.addEventProcessor(o):function(t){var e=Kr();e&&e.addEventProcessor&&e.addEventProcessor(t)}(o),Oc(i)&&(i.on("beforeSendEvent",function(t){return function(e){t.isEnabled()&&Ks(e)&&function(t,e){var n=e.exception&&e.exception.values&&e.exception.values[0].value;"string"==typeof n&&(n.match(/reactjs\.org\/docs\/error-decoder\.html\?invariant=(418|419|422|423|425)/)||n.match(/(does not match server-rendered HTML|Hydration failed because)/i))&&ss(t,gs({category:"replay.hydrate-error"}))}(t,e)}}(t)),i.on("afterSendEvent",Xs(t)),i.on("createDsc",(function(e){var n=t.getSessionId();n&&t.isEnabled()&&"session"===t.recordingMode&&t.checkAndHandleExpiredSession()&&(e.replay_id=n)})),i.on("startTransaction",(function(e){t.lastTransaction=e})),i.on("finishTransaction",(function(e){t.lastTransaction=e})),i.on("beforeSendFeedback",(function(e,n){var r=t.getSessionId();n&&n.includeReplay&&t.isEnabled()&&r&&e.contexts&&e.contexts.feedback&&(e.contexts.feedback.replay_id=r)})))}function Oc(t){return!(!t||!t.on)}function Rc(t){return Ac.apply(this,arguments)}function Ac(){return(Ac=Cn(dt().mark((function t(e){return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.abrupt("return",Promise.all(Qs(e,[(n=Gi.performance.memory,void 0,void 0,void 0,void 0,r=n.jsHeapSizeLimit,i=n.totalJSHeapSize,o=n.usedJSHeapSize,a=Date.now()/1e3,{type:"memory",name:"memory",start:a,end:a,data:{memory:{jsHeapSizeLimit:r,totalJSHeapSize:i,usedJSHeapSize:o}}})])));case 4:return t.prev=4,t.t0=t.catch(0),t.abrupt("return",[]);case 7:case"end":return t.stop()}var n,r,i,o,a}),t,null,[[0,4]])})))).apply(this,arguments)}function Dc(t){var e=!1;return function(n,r){if(t.checkAndHandleExpiredSession()){var i=r||!e;e=!0,t.clickDetector&&function(t,e){try{if(!function(t){return t.type===is}(e))return;var n=e.data.source;if(n===ha.Mutation&&t.registerMutation(e.timestamp),n===ha.Scroll&&t.registerScroll(e.timestamp),function(t){return t.data.source===ha.MouseInteraction}(e)){var r=e.data,i=r.type,o=r.id,a=rs.mirror.getNode(o);a instanceof HTMLElement&&i===va.Click&&t.registerClick(a)}}catch(t){}}(t.clickDetector,n),t.addUpdate((function(){if("buffer"===t.recordingMode&&i&&t.setInitialState(),!qs(t,n,i))return!0;if(!i)return!1;if(function(t,e){e&&t.session&&0===t.session.segmentId&&qs(t,function(t){var e=t.getOptions();return{type:pa.Custom,timestamp:Date.now(),data:{tag:"options",payload:{shouldRecordCanvas:t.isRecordingCanvas(),sessionSampleRate:e.sessionSampleRate,errorSampleRate:e.errorSampleRate,useCompressionOption:e.useCompression,blockAllMedia:e.blockAllMedia,maskAllText:e.maskAllText,maskAllInputs:e.maskAllInputs,useCompression:!!t.eventBuffer&&"worker"===t.eventBuffer.type,networkDetailHasUrls:e.networkDetailAllowUrls.length>0,networkCaptureBodies:e.networkCaptureBodies,networkRequestHasHeaders:e.networkRequestHeaders.length>0,networkResponseHasHeaders:e.networkResponseHeaders.length>0}}}}(t),!1)}(t,i),t.session&&t.session.previousSessionId)return!0;if("buffer"===t.recordingMode&&t.session&&t.eventBuffer){var e=t.eventBuffer.getEarliestTimestamp();e&&(Ts("[Replay] Updating session start time to earliest event in buffer to "+new Date(e),t.getOptions()._experiments.traceInternals),t.session.started=e,t.getOptions().stickySession&&js(t.session))}return"session"===t.recordingMode&&t.flush(),!0}))}else Es&&ir.warn("[Replay] Received replay event after session expired.")}}function Nc(t,e,n,r){return i=function(t,e,n,r){var i=t.sdkProcessingMetadata&&t.sdkProcessingMetadata.dynamicSamplingContext;return v({event_id:t.event_id,sent_at:(new Date).toISOString()},e&&{sdk:e},!!n&&r&&{dsn:ki(r)},i&&{trace:yr(v({},i))})}(t,function(t){if(t&&t.sdk){var e=t.sdk;return{name:e.name,version:e.version}}}(t),r,n),void 0===(o=[[{type:"replay_event"},t],[{type:"replay_recording",length:"string"==typeof e?(new TextEncoder).encode(e).length:e.length},e]])&&(o=[]),[i,o];var i,o}function Lc(t){var e,n=t.recordingData,r=t.headers,i=JSON.stringify(r)+"\n";if("string"==typeof n)e=""+i+n;else{var o=(new TextEncoder).encode(i);(e=new Uint8Array(o.length+n.length)).set(o),e.set(n,o.length)}return e}function Pc(t){return jc.apply(this,arguments)}function jc(){return jc=Cn(dt().mark((function t(e){var n,r,i,o,a,s,c,u,l,d,f;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=e.client,r=e.scope,i=e.replayId,o=e.event,a="object"!=typeof n._integrations||null===n._integrations||Array.isArray(n._integrations)?void 0:Object.keys(n._integrations),s={event_id:i,integrations:a},n.emit&&n.emit("preprocessEvent",o,s),t.next=6,Wr(n.getOptions(),o,s,r,n,Pr().getIsolationScope());case 6:if(c=t.sent){t.next=9;break}return t.abrupt("return",null);case 9:return c.platform=c.platform||"javascript",u=n.getSdkMetadata&&n.getSdkMetadata(),l=u&&u.sdk||{},d=l.name,f=l.version,c.sdk=v({},c.sdk,{name:d||"sentry.javascript.unknown",version:f||"0.0.0"}),t.abrupt("return",c);case 14:case"end":return t.stop()}}),t)}))),jc.apply(this,arguments)}function Uc(t){return Fc.apply(this,arguments)}function Fc(){return(Fc=Cn(dt().mark((function t(e){var n,r,i,o,a,s,c,u,l,d,f,p,h,v,m,g,y,_,b,S,k;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.recordingData,r=e.replayId,i=e.segmentId,o=e.eventContext,a=e.timestamp,s=e.session,c=Lc({recordingData:n,headers:{segment_id:i}}),u=o.urls,l=o.errorIds,d=o.traceIds,f=o.initialTimestamp,p=Kr(),h=Gr(),v=p&&p.getTransport(),m=p&&p.getDsn(),p&&v&&m&&s.sampled){t.next=9;break}return t.abrupt("return");case 9:return g={type:Xi,replay_start_timestamp:f/1e3,timestamp:a/1e3,error_ids:l,trace_ids:d,urls:u,replay_id:r,segment_id:i,replay_type:s.sampled},t.next=12,Pc({scope:h,client:p,replayId:r,event:g});case 12:if(y=t.sent){t.next=17;break}return p.recordDroppedEvent("event_processor","replay",g),Ts("An event processor returned `null`, will not send event."),t.abrupt("return");case 17:return delete y.sdkProcessingMetadata,_=Nc(y,c,m,p.getOptions().tunnel),t.prev=19,t.next=22,v.send(_);case 22:b=t.sent,t.next=30;break;case 25:t.prev=25,t.t0=t.catch(19),S=new Error(Qi);try{S.cause=t.t0}catch(t){}throw S;case 30:if(b){t.next=32;break}return t.abrupt("return",b);case 32:if("number"!=typeof b.statusCode||!(b.statusCode<200||b.statusCode>=300)){t.next=34;break}throw new Bc(b.statusCode);case 34:if(x=k=Ti({},b),"replay",void 0===(w=void 0)&&(w=Date.now()),!(function(t,e){return t[e]||t.all||0}(x,"replay")>w)){t.next=37;break}throw new zc(k);case 37:return t.abrupt("return",b);case 38:case"end":return t.stop()}var x,w}),t,null,[[19,25]])})))).apply(this,arguments)}var Bc=function(t){function e(e){return t.call(this,"Transport returned status code "+e)||this}return Dn(e,t),e}(Pn(Error)),zc=function(t){function e(e){var n;return(n=t.call(this,"Rate limit hit")||this).rateLimits=e,n}return Dn(e,t),e}(Pn(Error));function Hc(t,e){return qc.apply(this,arguments)}function qc(){return(qc=Cn(dt().mark((function t(e,n){var r,i,o;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(void 0===n&&(n={count:0,interval:Zi}),r=e.recordingData,i=e.options,r.length){t.next=4;break}return t.abrupt("return");case 4:return t.prev=4,t.next=7,Uc(e);case 7:return t.abrupt("return",!0);case 10:if(t.prev=10,t.t0=t.catch(4),!(t.t0 instanceof Bc||t.t0 instanceof zc)){t.next=14;break}throw t.t0;case 14:if("Replays",a={_retryCount:n.count},Pr().setContext("Replays",a),Es&&i._experiments&&i._experiments.captureExceptions&&Jr(t.t0),!(n.count>=to)){t.next=20;break}o=new Error(Qi+" - max retries exceeded");try{o.cause=t.t0}catch(t){}throw o;case 20:return n.interval*=++n.count,t.abrupt("return",new Promise((function(t,r){setTimeout(Cn(dt().mark((function i(){return dt().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return i.prev=0,i.next=3,Hc(e,n);case 3:t(!0),i.next=9;break;case 6:i.prev=6,i.t0=i.catch(0),r(i.t0);case 9:case"end":return i.stop()}}),i,null,[[0,6]])}))),n.interval)})));case 22:case"end":return t.stop()}var a}),t,null,[[4,10]])})))).apply(this,arguments)}var Wc="__THROTTLED";var Vc=function(){function t(e){var n=this,r=e.options,i=e.recordingOptions;t.prototype.__init.call(this),t.prototype.__init2.call(this),t.prototype.__init3.call(this),t.prototype.__init4.call(this),t.prototype.__init5.call(this),t.prototype.__init6.call(this),this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:3e5,sessionIdleExpire:9e5},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=i,this._options=r,this._debouncedFlush=function(t,e,n){var r,i,o,a=n&&n.maxWait?Math.max(n.maxWait,e):0;function s(){return c(),r=t()}function c(){void 0!==i&&clearTimeout(i),void 0!==o&&clearTimeout(o),i=o=void 0}function u(){return i&&clearTimeout(i),i=setTimeout(s,e),a&&void 0===o&&(o=setTimeout(s,a)),r}return u.cancel=c,u.flush=function(){return void 0!==i||void 0!==o?s():r},u}((function(){return n._flush()}),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=function(t,e,n){var r=new Map,i=!1;return function(){var o=Math.floor(Date.now()/1e3);if(function(t){var e=t-n;r.forEach((function(t,n){n=e){var a=i;return i=!0,a?"__SKIPPED":Wc}i=!1;var s=r.get(o)||0;return r.set(o,s+1),t.apply(void 0,arguments)}}((function(t,e){return function(t,e,n){return Ys(t,e)?Ws(t,e,n):Promise.resolve(null)}(n,t,e)}),300,5);var o=this.getOptions(),a=o.slowClickTimeout,s=o.slowClickIgnoreSelectors,c=a?{threshold:Math.min(3e3,a),timeout:a,scrollTimeout:300,ignoreSelector:s?s.join(","):""}:void 0;c&&(this.clickDetector=new hs(this,c))}var e=t.prototype;return e.getContext=function(){return this._context},e.isEnabled=function(){return this._isEnabled},e.isPaused=function(){return this._isPaused},e.isRecordingCanvas=function(){return Boolean(this._canvas)},e.getOptions=function(){return this._options},e.initializeSampling=function(t){var e=this._options,n=e.errorSampleRate,r=e.sessionSampleRate;n<=0&&r<=0||(this._initializeSessionForSampling(t),this.session?!1!==this.session.sampled&&(this.recordingMode="buffer"===this.session.sampled&&0===this.session.segmentId?"buffer":"session",Is("[Replay] Starting replay in "+this.recordingMode+" mode",this._options._experiments.traceInternals),this._initializeRecording()):this._handleException(new Error("Unable to initialize and create session")))},e.start=function(){if(this._isEnabled&&"session"===this.recordingMode)throw new Error("Replay recording is already in progress");if(this._isEnabled&&"buffer"===this.recordingMode)throw new Error("Replay buffering is in progress, call `flush()` to save the replay");Is("[Replay] Starting replay in session mode",this._options._experiments.traceInternals),this._updateUserActivity();var t=Hs({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire,traceInternals:this._options._experiments.traceInternals},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=t,this._initializeRecording()},e.startBuffering=function(){if(this._isEnabled)throw new Error("Replay recording is already in progress");Is("[Replay] Starting replay in buffer mode",this._options._experiments.traceInternals);var t=Hs({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,traceInternals:this._options._experiments.traceInternals},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=t,this.recordingMode="buffer",this._initializeRecording()},e.startRecording=function(){try{var t=this._canvas;this._stopRecording=rs(v({},this._recordingOptions,"buffer"===this.recordingMode&&{checkoutEveryNms:6e4},{emit:Dc(this),onMutation:this._onMutationHandler},t?{recordCanvas:t.recordCanvas,getCanvasManager:t.getCanvasManager,sampling:t.sampling,dataURLOptions:t.dataURLOptions}:{}))}catch(t){this._handleException(t)}},e.stopRecording=function(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(t){return this._handleException(t),!1}},e.stop=function(){var t=Cn(dt().mark((function t(e){var n,r,i,o;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r=(n=void 0===e?{}:e).forceFlush,i=void 0!==r&&r,o=n.reason,this._isEnabled){t.next=3;break}return t.abrupt("return");case 3:if(this._isEnabled=!1,t.prev=4,Ts("[Replay] Stopping Replay"+(o?" triggered by "+o:""),this._options._experiments.traceInternals),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),!i){t.next=12;break}return t.next=12,this._flush({force:!0});case 12:this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,a=this,function(){if(Ns())try{Gi.sessionStorage.removeItem($i)}catch(t){}}(),a.session=void 0,t.next=20;break;case 17:t.prev=17,t.t0=t.catch(4),this._handleException(t.t0);case 20:case"end":return t.stop()}var a}),t,this,[[4,17]])})));return function(e){return t.apply(this,arguments)}}(),e.pause=function(){this._isPaused||(this._isPaused=!0,this.stopRecording(),Ts("[Replay] Pausing replay",this._options._experiments.traceInternals))},e.resume=function(){this._isPaused&&this._checkSession()&&(this._isPaused=!1,this.startRecording(),Ts("[Replay] Resuming replay",this._options._experiments.traceInternals))},e.sendBufferedReplayOrFlush=function(){var t=Cn(dt().mark((function t(e){var n,r,i,o;return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=(void 0===e?{}:e).continueRecording,r=void 0===n||n,"session"!==this.recordingMode){t.next=3;break}return t.abrupt("return",this.flushImmediate());case 3:return i=Date.now(),Ts("[Replay] Converting buffer to session",this._options._experiments.traceInternals),t.next=7,this.flushImmediate();case 7:if(o=this.stopRecording(),r&&o){t.next=10;break}return t.abrupt("return");case 10:if("session"!==this.recordingMode){t.next=12;break}return t.abrupt("return");case 12:this.recordingMode="session",this.session&&(this._updateUserActivity(i),this._updateSessionActivity(i),this._maybeSaveSession()),this.startRecording();case 15:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e.addUpdate=function(t){var e=t();"buffer"!==this.recordingMode&&!0!==e&&this._debouncedFlush()},e.triggerUserActivity=function(){if(this._updateUserActivity(),this._stopRecording)this.checkAndHandleExpiredSession(),this._updateSessionActivity();else{if(!this._checkSession())return;this.resume()}},e.updateUserActivity=function(){this._updateUserActivity(),this._updateSessionActivity()},e.conditionalFlush=function(){return"buffer"===this.recordingMode?Promise.resolve():this.flushImmediate()},e.flush=function(){return this._debouncedFlush()},e.flushImmediate=function(){return this._debouncedFlush(),this._debouncedFlush.flush()},e.cancelFlush=function(){this._debouncedFlush.cancel()},e.getSessionId=function(){return this.session&&this.session.id},e.checkAndHandleExpiredSession=function(){if(!(this._lastActivity&&Fs(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&"session"===this.session.sampled))return!!this._checkSession();this.pause()},e.setInitialState=function(){var t=""+Gi.location.pathname+Gi.location.hash+Gi.location.search,e=""+Gi.location.origin+t;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=e,this._context.initialTimestamp=Date.now(),this._context.urls.push(e)},e.throttledAddEvent=function(t,e){var n=this,r=this._throttledAddEvent(t,e);if(r===Wc){var i=gs({category:"replay.throttled"});this.addUpdate((function(){return!qs(n,{type:5,timestamp:i.timestamp||0,data:{tag:"breadcrumb",payload:i,metric:!0}})}))}return r},e.getCurrentRoute=function(){var t=this.lastTransaction||Gr().getTransaction(),e=(t&&wr(t).data||{})["sentry.source"];if(t&&e&&["route","custom"].includes(e))return wr(t).description},e._initializeRecording=function(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=function(t){var e=t.useCompression,n=t.workerUrl;if(e&&window.Worker){var r=function(t){try{var e=t||("undefined"!=typeof __SENTRY_EXCLUDE_REPLAY_WORKER__&&__SENTRY_EXCLUDE_REPLAY_WORKER__?"":(r=new Blob(['var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==r||r<0)&&(r=0),(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},A=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},_=function(r,e){for(var i=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=x(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},x=function(t,n,r){return-1==t.s?Math.max(x(t.l,n,r+1),x(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,C)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B255){A(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;A(r,m,Q[et]),m+=R[et],et>3&&(A(r,m,rt>>5&8191),m+=i[et])}else A(r,m,N[rt]),m+=P[rt]}return A(r,m,N[256]),m+P[256]},U=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=U[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=C(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=A[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,a=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),s=a.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(a,n),O(a,s-8,r.d()),O(a,s-4,e),a}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),G="undefined"!=typeof TextEncoder&&new TextEncoder,H="undefined"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(r){for(var e=new t(n.length),i=0;i>1)),o=0,f=function(t){s[o++]=t};for(i=0;is.length){var h=new t(o+8+(a-i<<1));h.set(s),s=h}var l=n.charCodeAt(i);l<128||r?f(l):l<2048?(f(192|l>>6),f(128|63&l)):l>55295&&l<57344?(f(240|(l=65536+(1047552&l)|1023&n.charCodeAt(++i))>>18),f(128|l>>12&63),f(128|l>>6&63),f(128|63&l)):(f(224|l>>12),f(128|l>>6&63),f(128|63&l))}return b(s,0,o)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(let r=0,e=t.length;r{this._deflatedData.push(t)},this.stream=new J(((t,n)=>{this.deflate.push(t,n)})),this.stream.push("[")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener("message",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&"function"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});']),URL.createObjectURL(r)));if(!e)return;Ts("[Replay] Using compression worker"+(t?" from "+t:""));var n=new Worker(e);return new Ds(n)}catch(t){Ts("[Replay] Failed to create compression worker")}var r}(n);if(r)return r}return Ts("[Replay] Using simple buffer"),new Os}({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.startRecording()},e._handleException=function(t){Es&&ir.error("[Replay]",t),Es&&this._options._experiments&&this._options._experiments.captureExceptions&&Jr(t)},e._initializeSessionForSampling=function(t){var e=this._options.errorSampleRate>0,n=Hs({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,traceInternals:this._options._experiments.traceInternals,previousSessionId:t},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:e});this.session=n},e._checkSession=function(){if(!this.session)return!1;var t=this.session;return!zs(t,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})||(this._refreshSession(t),!1)},e._refreshSession=function(){var t=Cn(dt().mark((function t(e){return dt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._isEnabled){t.next=2;break}return t.abrupt("return");case 2:return t.next=4,this.stop({reason:"refresh session"});case 4:this.initializeSampling(e.id);case 5:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e._addListeners=function(){try{Gi.document.addEventListener("visibilitychange",this._handleVisibilityChange),Gi.addEventListener("blur",this._handleWindowBlur),Gi.addEventListener("focus",this._handleWindowFocus),Gi.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(Mc(this),this._hasInitializedCoreListeners=!0)}catch(t){this._handleException(t)}this._performanceCleanupCallback=ws(this)},e._removeListeners=function(){try{Gi.document.removeEventListener("visibilitychange",this._handleVisibilityChange),Gi.removeEventListener("blur",this._handleWindowBlur),Gi.removeEventListener("focus",this._handleWindowFocus),Gi.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(t){this._handleException(t)}},e.__init=function(){var t=this;this._handleVisibilityChange=function(){"visible"===Gi.document.visibilityState?t._doChangeToForegroundTasks():t._doChangeToBackgroundTasks()}},e.__init2=function(){var t=this;this._handleWindowBlur=function(){var e=gs({category:"ui.blur"});t._doChangeToBackgroundTasks(e)}},e.__init3=function(){var t=this;this._handleWindowFocus=function(){var e=gs({category:"ui.focus"});t._doChangeToForegroundTasks(e)}},e.__init4=function(){var t=this;this._handleKeyboardEvent=function(e){!function(t,e){if(t.isEnabled()){t.updateUserActivity();var n=function(t){var e=t.metaKey,n=t.shiftKey,r=t.ctrlKey,i=t.altKey,o=t.key,a=t.target;if(!a||function(t){return"INPUT"===t.tagName||"TEXTAREA"===t.tagName||t.isContentEditable}(a)||!o)return null;var s=e||r||i,c=1===o.length;if(!s&&c)return null;var u=fr(a,{maxStringLength:200})||"";return gs({category:"ui.keyDown",message:u,data:v({},bs(a,u).data,{metaKey:e,shiftKey:n,ctrlKey:r,altKey:i,key:o})})}(e);n&&ss(t,n)}}(t,e)}},e._doChangeToBackgroundTasks=function(t){this.session&&(Bs(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})||(t&&this._createCustomBreadcrumb(t),this.conditionalFlush()))},e._doChangeToForegroundTasks=function(t){this.session&&(this.checkAndHandleExpiredSession()?t&&this._createCustomBreadcrumb(t):Ts("[Replay] Document has become active, but session has expired"))},e._updateUserActivity=function(t){void 0===t&&(t=Date.now()),this._lastActivity=t},e._updateSessionActivity=function(t){void 0===t&&(t=Date.now()),this.session&&(this.session.lastActivity=t,this._maybeSaveSession())},e._createCustomBreadcrumb=function(t){var e=this;this.addUpdate((function(){e.throttledAddEvent({type:pa.Custom,timestamp:t.timestamp||0,data:{tag:"breadcrumb",payload:t}})}))},e._addPerformanceEntries=function(){var t,e=(t=this.performanceEntries,t.map(ks).filter(Boolean)).concat(this.replayPerformanceEntries);return this.performanceEntries=[],this.replayPerformanceEntries=[],Promise.all(Qs(this,e))},e._clearContext=function(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]},e._updateInitialTimestampFromEventBuffer=function(){var t=this.session,e=this.eventBuffer;if(t&&e&&!t.segmentId){var n=e.getEarliestTimestamp();n&&nthis._options.maxReplayDuration+3e4)){t.next=19;break}throw new Error("Session is too long, not sending replay");case 19:return r=this._popEventContext(),i=this.session.segmentId++,this._maybeSaveSession(),t.next=24,this.eventBuffer.finish();case 24:return o=t.sent,t.next=27,Hc({replayId:e,recordingData:o,segmentId:i,eventContext:r,session:this.session,options:this.getOptions(),timestamp:n});case 27:t.next=35;break;case 29:t.prev=29,t.t0=t.catch(14),this._handleException(t.t0),this.stop({reason:"sendReplay"}),(a=Kr())&&a.recordDroppedEvent("send_error","replay");case 35:case"end":return t.stop()}}),t,this,[[14,29]])})));return function(){return t.apply(this,arguments)}}(),e.__init5=function(){var t=this;this._flush=function(){var e=Cn(dt().mark((function e(n){var r,i,o,a,s,c,u,l;return dt().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=(void 0===n?{}:n).force,i=void 0!==r&&r,t._isEnabled||i){e.next=3;break}return e.abrupt("return");case 3:if(t.checkAndHandleExpiredSession()){e.next=6;break}return Es&&ir.error("[Replay] Attempting to finish replay event after session expired."),e.abrupt("return");case 6:if(t.session){e.next=8;break}return e.abrupt("return");case 8:if(o=t.session.started,a=Date.now(),s=a-o,t._debouncedFlush.cancel(),c=st._options.maxReplayDuration+5e3,!c&&!u){e.next=18;break}return Ts("[Replay] Session duration ("+Math.floor(s/1e3)+"s) is too "+(c?"short":"long")+", not sending replay.",t._options._experiments.traceInternals),c&&t._debouncedFlush(),e.abrupt("return");case 18:if((l=t.eventBuffer)&&0===t.session.segmentId&&!l.hasCheckout&&Ts("[Replay] Flushing initial segment without checkout.",t._options._experiments.traceInternals),t._flushLock){e.next=26;break}return t._flushLock=t._runFlush(),e.next=24,t._flushLock;case 24:return t._flushLock=void 0,e.abrupt("return");case 26:return e.prev=26,e.next=29,t._flushLock;case 29:e.next=34;break;case 31:e.prev=31,e.t0=e.catch(26),Es&&ir.error(e.t0);case 34:return e.prev=34,t._debouncedFlush(),e.finish(34);case 37:case"end":return e.stop()}}),e,null,[[26,31,34,37]])})));return function(t){return e.apply(this,arguments)}}()},e._maybeSaveSession=function(){this.session&&this._options.stickySession&&js(this.session)},e.__init6=function(){var t=this;this._onMutationHandler=function(e){var n=e.length,r=t._options.mutationLimit,i=r&&n>r;if(n>t._options.mutationBreadcrumbLimit||i){var o=gs({category:"replay.mutations",data:{count:n,limit:i}});t._createCustomBreadcrumb(o)}return!i||(t.stop({reason:"mutationLimit",forceFlush:"session"===t.recordingMode}),!1)}},t}();function Yc(t,e,n,r){var i="string"==typeof r?r.split(","):[],o=[].concat(t,i,e);return void 0!==n&&("string"==typeof n&&o.push("."+n),nr((function(){console.warn("[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.")}))),o.join(",")}var Jc='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',Kc=["content-length","content-type","accept"],Gc=!1,$c=function(){function t(e){var n=void 0===e?{}:e,r=n.flushMinDelay,i=void 0===r?5e3:r,o=n.flushMaxDelay,a=void 0===o?5500:o,s=n.minReplayDuration,c=void 0===s?4999:s,u=n.maxReplayDuration,l=void 0===u?io:u,d=n.stickySession,f=void 0===d||d,p=n.useCompression,h=void 0===p||p,m=n.workerUrl,g=n._experiments,y=void 0===g?{}:g,_=n.sessionSampleRate,b=n.errorSampleRate,S=n.maskAllText,k=void 0===S||S,x=n.maskAllInputs,w=void 0===x||x,E=n.blockAllMedia,T=void 0===E||E,I=n.mutationBreadcrumbLimit,C=void 0===I?750:I,M=n.mutationLimit,O=void 0===M?1e4:M,R=n.slowClickTimeout,A=void 0===R?7e3:R,D=n.slowClickIgnoreSelectors,N=void 0===D?[]:D,L=n.networkDetailAllowUrls,P=void 0===L?[]:L,j=n.networkDetailDenyUrls,U=void 0===j?[]:j,F=n.networkCaptureBodies,B=void 0===F||F,z=n.networkRequestHeaders,H=void 0===z?[]:z,q=n.networkResponseHeaders,W=void 0===q?[]:q,V=n.mask,Y=void 0===V?[]:V,J=n.maskAttributes,K=void 0===J?["title","placeholder"]:J,G=n.unmask,$=void 0===G?[]:G,X=n.block,Q=void 0===X?[]:X,Z=n.unblock,tt=void 0===Z?[]:Z,et=n.ignore,nt=void 0===et?[]:et,rt=n.maskFn,it=n.beforeAddRecordingEvent,ot=n.beforeErrorSampling,at=n.blockClass,st=n.blockSelector,ct=n.maskInputOptions,ut=n.maskTextClass,lt=n.maskTextSelector,dt=n.ignoreClass;this.name=t.id;var ft=function(t){var e=t.unmask,n=t.block,r=t.unblock,i=t.ignore,o=t.blockClass,a=t.blockSelector,s=t.maskTextClass,c=t.ignoreClass,u={maskTextSelector:Yc(t.mask,[".sentry-mask","[data-sentry-mask]"],s,t.maskTextSelector),unmaskTextSelector:Yc(e,[".sentry-unmask","[data-sentry-unmask]"]),blockSelector:Yc(n,[".sentry-block","[data-sentry-block]"].concat(['base[href="/"]']),o,a),unblockSelector:Yc(r,[".sentry-unblock","[data-sentry-unblock]"]),ignoreSelector:Yc(i,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'],c)};return o instanceof RegExp&&(u.blockClass=o),s instanceof RegExp&&(u.maskTextClass=s),u}({mask:Y,unmask:$,block:Q,unblock:tt,ignore:nt,blockClass:at,blockSelector:st,maskTextClass:ut,maskTextSelector:lt,ignoreClass:dt});if(this._recordingOptions=v({maskAllInputs:w,maskAllText:k,maskInputOptions:v({},ct||{},{password:!0}),maskTextFn:rt,maskInputFn:rt,maskAttributeFn:function(t,e,n){return function(t){var e=t.el,n=t.key,r=t.maskAttributes,i=t.privacyOptions,o=t.value;return t.maskAllText?i.unmaskTextSelector&&e.matches(i.unmaskTextSelector)?o:r.includes(n)||"value"===n&&"INPUT"===e.tagName&&["submit","button"].includes(e.getAttribute("type")||"")?o.replace(/[\S]/g,"*"):o:o}({maskAttributes:K,maskAllText:k,privacyOptions:ft,key:t,value:e,el:n})}},ft,{slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:function(t){try{t.__rrweb__=!0}catch(t){}}}),this._initialOptions={flushMinDelay:i,flushMaxDelay:a,minReplayDuration:Math.min(c,15e3),maxReplayDuration:Math.min(l,io),stickySession:f,sessionSampleRate:_,errorSampleRate:b,useCompression:h,workerUrl:m,blockAllMedia:T,maskAllInputs:w,maskAllText:k,mutationBreadcrumbLimit:C,mutationLimit:O,slowClickTimeout:A,slowClickIgnoreSelectors:N,networkDetailAllowUrls:P,networkDetailDenyUrls:U,networkCaptureBodies:B,networkRequestHeaders:Xc(H),networkResponseHeaders:Xc(W),beforeAddRecordingEvent:it,beforeErrorSampling:ot,_experiments:y},"number"==typeof _&&(console.warn("[Replay] You are passing `sessionSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysSessionSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: "+_+" })"),this._initialOptions.sessionSampleRate=_),"number"==typeof b&&(console.warn("[Replay] You are passing `errorSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysOnErrorSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: "+b+" })"),this._initialOptions.errorSampleRate=b),this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?this._recordingOptions.blockSelector+","+Jc:Jc),this._isInitialized&&Ci())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}t.__initStatic=function(){this.id="Replay"};var e=t.prototype;return e.setupOnce=function(){var t=this;Ci()&&(this._setup(),setTimeout((function(){return t._initialize()})))},e.start=function(){this._replay&&this._replay.start()},e.startBuffering=function(){this._replay&&this._replay.startBuffering()},e.stop=function(){return this._replay?this._replay.stop({forceFlush:"session"===this._replay.recordingMode}):Promise.resolve()},e.flush=function(t){return this._replay&&this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(t):Promise.resolve()},e.getReplayId=function(){if(this._replay&&this._replay.isEnabled())return this._replay.getSessionId()},e._initialize=function(){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(),this._replay.initializeSampling())},e._setup=function(){var t=function(t){var e=Kr(),n=e&&e.getOptions(),r=v({sessionSampleRate:0,errorSampleRate:0},yr(t));return n?(null==t.sessionSampleRate&&null==t.errorSampleRate&&null==n.replaysSessionSampleRate&&null==n.replaysOnErrorSampleRate&&nr((function(){console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")})),"number"==typeof n.replaysSessionSampleRate&&(r.sessionSampleRate=n.replaysSessionSampleRate),"number"==typeof n.replaysOnErrorSampleRate&&(r.errorSampleRate=n.replaysOnErrorSampleRate),r):(nr((function(){console.warn("SDK client is not available.")})),r)}(this._initialOptions);this._replay=new Vc({options:t,recordingOptions:this._recordingOptions})},e._maybeLoadFromReplayCanvasIntegration=function(){try{var t=Kr().getIntegrationByName("ReplayCanvas");if(!t)return;this._replay._canvas=t.getOptions()}catch(t){}},Rn(t,[{key:"_isInitialized",get:function(){return Gc},set:function(t){Gc=t}}]),t}();function Xc(t){return[].concat(Kc,t.map((function(t){return t.toLowerCase()})))}$c.__initStatic();var Qc=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function Zc(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,o=t.port,a=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(o?":"+o:"")+"/"+(r?r+"/":r)+a}function tu(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function eu(t){var e="string"==typeof t?function(t){var e=Qc.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],o=n[2],a=void 0===o?"":o,s=n[3],c=n[4],u=void 0===c?"":c,l="",f=n[5],p=f.split("/");if(p.length>1&&(l=p.slice(0,-1).join("/"),f=p.pop()),f){var h=f.match(/^\d+/);h&&(f=h[0])}return tu({host:s,pass:a,path:l,projectId:f,port:u,protocol:r,publicKey:i})}d((function(){console.error("Invalid Sentry Dsn: "+t)}))}(t):tu(t);if(e&&function(t){if(!i)return!0;var e=t.port,n=t.projectId,r=t.protocol;return!(["protocol","publicKey","host","projectId"].find((function(e){return!t[e]&&(h.error("Invalid Sentry Dsn: "+e+" missing"),!0)}))||(n.match(/^\d+$/)?function(t){return"http"===t||"https"===t}(r)?e&&isNaN(parseInt(e,10))&&(h.error("Invalid Sentry Dsn: Invalid port "+e),1):(h.error("Invalid Sentry Dsn: Invalid protocol "+r),1):(h.error("Invalid Sentry Dsn: Invalid projectId "+n),1)))}(e))return e}function nu(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return ru(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ru(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function ru(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(t);!(e=r()).done;){var i=e.value,o=Object.entries(i.tags),a=o.length>0?"|#"+o.map((function(t){return t[0]+":"+t[1]})).join(","):"";n+=i.name+"@"+i.unit+":"+i.metric+"|"+i.metricType+a+"|T"+i.timestamp+"\n"}return n}(t);return[{type:"statsd",length:e.length},e]}(t);return iu(i,[o])}function yu(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return _u(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_u(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _u(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?" ("+r+" times)":"")),this._outcomes[i]=(this._outcomes[i]||0)+r}},e.captureAggregateMetrics=function(t){Q&&h.log("Flushing aggregated metrics, number of metrics: "+t.length);var e=gu(t,this._dsn,this._options._metadata,this._options.tunnel);this._sendEnvelope(e)},e.on=function(t,e){this._hooks[t]||(this._hooks[t]=[]),this._hooks[t].push(e)},e.emit=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},e._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._transport},e._prepareEvent=function(t,e,n,r){var i=this;void 0===r&&(r=qt().getIsolationScope());var o=this.getOptions(),s=Object.keys(this._integrations);return!e.integrations&&s.length>0&&(e.integrations=s),this.emit("preprocessEvent",t,e),function(t,e,n,r,i,o){var s=t.normalizeDepth,c=void 0===s?3:s,u=t.normalizeMaxBreadth,l=void 0===u?1e3:u,d=v({},e,{event_id:e.event_id||n.event_id||V(),timestamp:e.timestamp||at()}),f=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,o=e.maxValueLength,a=void 0===o?250:o;"environment"in t||(t.environment="environment"in e?n:ct),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=D(t.message,a));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=D(s.value,a));var c=t.request;c&&c.url&&(c.url=D(c.url,a))}(d,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(d,f),void 0===e.type&&function(t,e){var n,r=a._sentryDebugIds;if(r){var i=wt.get(e);i?n=i:(n=new Map,wt.set(e,n));var o=Object.keys(r).reduce((function(t,i){var o,a=n.get(i);a?o=a:(o=e(i),n.set(i,o));for(var s=o.length-1;s>=0;s--){var c=o[s];if(c.filename){t[c.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=o[t.filename])}))}))}catch(t){}}}(d,t.stackParser);var p=function(t,e){if(!e)return t;var n=t?t.clone():new Pt;return n.update(e),n}(r,n.captureContext);n.mechanism&&G(d,n.mechanism);var h=i&&i.getEventProcessors?i.getEventProcessors():[],m=(Lt||(Lt=new Pt),Lt).getScopeData();o&&Dt(m,o.getScopeData()),p&&Dt(m,p.getScopeData());var g=[].concat(n.attachments||[],m.attachments);return g.length&&(n.attachments=g),At(d,m),it([].concat(h,nt(),m.eventProcessors),d,n).then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof c&&c>0?function(t,e,n){if(!t)return null;var r=v({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return v({},t,t.data&&{data:yt(t.data,e,n)})}))},t.user&&{user:yt(t.user,e,n)},t.contexts&&{contexts:yt(t.contexts,e,n)},t.extra&&{extra:yt(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=yt(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){var r=xt(t).data;return r&&(t.data=yt(r,e,n)),t}))),r}(t,c,l):t}))}(o,t,e,n,this,r).then((function(t){if(null===t)return t;var e=v({},r.getPropagationContext(),n?n.getPropagationContext():void 0);if((!t.contexts||!t.contexts.trace)&&e){var o=e.traceId,a=e.spanId,s=e.parentSpanId,c=e.dsc;t.contexts=v({trace:{trace_id:o,span_id:a,parent_span_id:s}},t.contexts);var u=c||Ot(o,i,n);t.sdkProcessingMetadata=v({dynamicSamplingContext:u},t.sdkProcessingMetadata)}return t}))},e._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){if(Q){var e=t;"log"===e.logLevel?h.log(e.message):h.warn(e)}}))},e._processEvent=function(t,e,n){var r=this,i=this.getOptions(),o=i.sampleRate,a=xu(t),s=ku(t),c=t.type||"error",u="before send for type `"+c+"`";if(s&&"number"==typeof o&&Math.random()>o)return this.recordDroppedEvent("sample_rate","error",t),tt(new fu("Discarding event because it's not included in the random sample (sampling rate = "+o+")","log"));var l="replay_event"===c?"replay":c,d=(t.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(t,e,n,d).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",l,t),new fu("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var o=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;if(ku(e)&&r)return r(e,n);if(xu(e)&&i){if(e.spans){var o=e.spans.length;e.sdkProcessingMetadata=v({},e.sdkProcessingMetadata,{spanCountBeforeProcessing:o})}return i(e,n)}return e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(T(t))return t.then((function(t){if(!w(t)&&null!==t)throw new fu(n);return t}),(function(t){throw new fu(e+" rejected with "+t)}));if(!w(t)&&null!==t)throw new fu(n);return t}(o,u)})).then((function(i){if(null===i){if(r.recordDroppedEvent("before_send",l,t),a){var o=1+(t.spans||[]).length;r.recordDroppedEvent("before_send","span",o)}throw new fu(u+" returned `null`, will not send event.","log")}var s=n&&n.getSession();if(!a&&s&&r._updateSessionFromEvent(s,i),a){var c=(i.sdkProcessingMetadata&&i.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);c>0&&r.recordDroppedEvent("before_send","span",c)}var d=i.transaction_info;return a&&d&&i.transaction!==t.transaction&&(i.transaction_info=v({},d,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof fu)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new fu("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},e._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},e._sendEnvelope=function(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)return this._transport.send(t).then(null,(function(t){Q&&h.error("Error while sending event:",t)}));Q&&h.error("Transport disabled")},e._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},t}();function ku(t){return void 0===t.type}function xu(t){return"transaction"===t.type}var wu=function(t){function e(e){var n;return function(t,e,n,r){void 0===n&&(n=[e]),void 0===r&&(r="npm");var i=t._metadata||{};i.sdk||(i.sdk={name:"sentry.javascript."+e,packages:n.map((function(t){return{name:r+":@sentry/"+t,version:Ut}})),version:Ut}),t._metadata=i}(e,"browser",["browser"],ce.SENTRY_SDK_SOURCE||"npm"),n=t.call(this,e)||this,e.sendClientReports&&ce.document&&ce.document.addEventListener("visibilitychange",(function(){"hidden"===ce.document.visibilityState&&n._flushOutcomes()})),n}Dn(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=Le(t,e,n&&n.syntheticException||void 0,r);return G(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),Z(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var o=Pe(t,e,r&&r.syntheticException||void 0,i);return o.level=n,r&&r.event_id&&(o.event_id=r.event_id),Z(o)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,o=v({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:Zc(i)}),a=function(t){return[{type:"user_report"},t]}(t);return iu(o,[a])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,iu((n=this._options.tunnel&&Zc(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:at(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(Su);function Eu(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Tu(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Tu(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Tu(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){Z(t).then((function(){--i||(clearTimeout(o),n(!0))}),r)}))}))}}}(t.bufferSize||Cu));var r={};function i(i){var o=[];if(ou(i,(function(e,n){var i=lu(n);if(function(t,e,n){return void 0===n&&(n=Date.now()),function(t,e){return t[e]||t.all||0}(t,e)>n}(r,i)){var a=Ou(e,n);t.recordDroppedEvent("ratelimit_backoff",i,a)}else o.push(e)})),0===o.length)return Z();var a=iu(i[0],o),s=function(e){ou(a,(function(n,r){var i=Ou(n,r);t.recordDroppedEvent(e,lu(r),i)}))};return n.add((function(){return e({body:su(a,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&Q&&h.warn("Sentry responded with status code "+t.statusCode+" to sent event."),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var o=v({},t),a=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(a)for(var c,u=Eu(a.trim().split(","));!(c=u()).done;){var l=c.value.split(":",5),d=l[0],f=l[1],p=l[4],h=parseInt(d,10),m=1e3*(isNaN(h)?60:h);if(f)for(var g,y=Eu(f.split(";"));!(g=y()).done;){var _=g.value;"metric_bucket"===_&&p&&!p.split(";").includes("custom")||(o[_]=n+m)}else o.all=n+m}else s?o.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?Iu:r-e}(s,n):429===r&&(o.all=n+6e4);return o}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof fu)return Q&&h.error("Skipped sending event because buffer is full."),s("queue_overflow"),Z();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function Ou(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var Ru=void 0;function Au(t,e){void 0===e&&(e=function(){if(Ru)return Ru;if(nn(ce.fetch))return Ru=ce.fetch.bind(ce);var t=ce.document,e=ce.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return Ru=e.bind(ce)}());var n=0,r=0;return Mu(t,(function(i){var o=i.body.length;n+=o,r++;var a=v({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,a).then((function(t){return n-=o,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return Ru=void 0,n-=o,r--,tt(t)}}))}var Du="?";function Nu(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var Lu=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Pu=/\((\S*)(?::(\d+))(?::(\d+))\)/,ju=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Uu=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Fu=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Bu=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=ht.test(a)?a.replace(ht,"$1"):a;if(!s.match(/\S*Error: /)){for(var c,u=ft(r);!(c=u()).done;){var l=(0,c.value)(s);if(l){n.push(l);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=Array.from(t);return/sentryWrapped/.test(e[e.length-1].function||"")&&e.pop(),e.reverse(),vt.test(e[e.length-1].function||"")&&(e.pop(),vt.test(e[e.length-1].function||"")&&e.pop()),e.slice(0,50).map((function(t){return v({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=Lu.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=Pu.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=zu(e[1]||Du,e[2]),i=r[0];return Nu(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=ju.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=Uu.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||Du,o=zu(i,r);return i=o[0],Nu(r=o[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=Fu.exec(t);return e?Nu(e[2],e[1]||Du,+e[3],e[4]?+e[4]:void 0):void 0}]]),zu=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:Du,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Hu="Dedupe",qu=function(){var t;return{name:Hu,setupOnce:function(){},processEvent:function(e){if(e.type)return e;try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!Vu(t,e)&&!!Wu(t,e))))}(t,e)||!!function(t,e){var n=Yu(e),r=Yu(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!Vu(t,e)&&!!Wu(t,e)))}(t,e))}(e,t))return null}catch(t){}return t=e}}};function Wu(t,e){var n=Ju(t),r=Ju(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i>t/4).toString(16)}))}function nl(){return Date.now()/1e3}var rl=function(){var t=Zu.performance;if(!t||!t.now)return nl;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/1e3}}(),il=(function(){var t=Zu.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function ml(t){return t.transaction}var gl=1;function yl(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=_l(t);return pl({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function _l(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function bl(t){var e=Al();if(!e)return{};var n=function(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=pl({environment:r.environment||ll,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}(_l(t).trace_id||"",e,Il().getScope()),r=ml(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=_l(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&gl)}(r)),e.emit&&e.emit("createDsc",n),n}var Sl=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=kl()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=v({},this._tags),e._extra=v({},this._extra),e._contexts=v({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=v({},this._sdkProcessingMetadata),e._propagationContext=v({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&vl(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=v({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=v({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=v({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=v({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=v({},this._tags,r.tags),this._extra=v({},this._extra,r.extra),this._contexts=v({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if($u(n)){var i=e;this._tags=v({},this._tags,i.tags),this._extra=v({},this._extra,i.extra),this._contexts=v({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=kl(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=v({timestamp:nl()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),function(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=pl(n);c&&Object.keys(c).length&&(t.extra=v({},c,t.extra));var u=pl(r);u&&Object.keys(u).length&&(t.tags=v({},u,t.tags));var l=pl(i);l&&Object.keys(l).length&&(t.user=v({},l,t.user));var d=pl(o);d&&Object.keys(d).length&&(t.contexts=v({},d,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=v({trace:yl(e)},t.contexts);var n=ml(e);if(n){t.sdkProcessingMetadata=v({dynamicSamplingContext:bl(e)},t.sdkProcessingMetadata);var r=_l(n).description;r&&(t.tags=v({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=v({},t.sdkProcessingMetadata,e)}(t,o)}(t,this.getScopeData()),fl([].concat(n,tl("globalEventProcessors",(function(){return[]})),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=v({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:el();if(!this._client)return ul.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,v({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:el();if(!this._client)return ul.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,v({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:el();return this._client?(this._client.captureEvent(t,v({},e,{event_id:n}),this),n):(ul.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function kl(){return{traceId:el(),spanId:el().substring(16)}}var xl=parseFloat("7.119.1"),wl=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=xl),this._version=r,e?i=e:(i=new Sl).setClient(t),n?o=n:(o=new Sl).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){il&&ul.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+Nl(o)+"\nError:",e)}}}("console",{args:n,level:t});var i=al[t];i&&i.apply(Zu.console,n)}}))}))}var Fl=["fatal","error","warning","log","info","debug"];function Bl(t){return"warn"===t?"warning":Fl.includes(t)?t:"log"}function zl(t,e){if(!Array.isArray(t))return"";for(var n,r=[],i=0;i(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","import { dynamicRequire, isNodeEnv } from './node';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance(): Performance | undefined {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = (module) => {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: () => {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n","import { isRegExp, isString } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","import type { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*healthcheck.*$/,\n /^.*healthy.*$/,\n /^.*live.*$/,\n /^.*ready.*$/,\n /^.*heartbeat.*$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcess: EventProcessor = (event: Event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n}\n\n/** JSDoc */\nexport function _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nexport function _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n __DEBUG_BUILD__ &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n const { values } = event.exception;\n try {\n const { type = '', value = '' } = (values && values[values.length - 1]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n }\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: { [key: string]: unknown }, name: string, value: unknown): void {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(value: V):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { node } from './node-stack-trace';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = stack.slice(0, STACKTRACE_FRAME_LIMIT);\n\n const lastFrameFunction = localStack[localStack.length - 1].function;\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (lastFrameFunction && /sentryWrapped/.test(lastFrameFunction)) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n const firstFrameFunction = localStack[localStack.length - 1].function;\n // 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)\n if (firstFrameFunction && /captureMessage|captureException/.test(firstFrameFunction)) {\n localStack.pop();\n }\n\n return localStack.map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n const getRandomByte =\n crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","import type { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalSingleton, GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] as const;\nexport type ConsoleLevel = (typeof CONSOLE_LEVELS)[number];\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record<(typeof CONSOLE_LEVELS)[number], LoggerMethod>;\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const originalConsole = GLOBAL_OBJ.console as Console & Record;\n const wrappedLevels: Partial = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] as WrappedFunction).__sentry_original__;\n if (level in originalConsole && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] as LoggerConsoleMethods[typeof level];\n originalConsole[level] = originalWrappedFunc as Console[typeof level];\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level as (typeof CONSOLE_LEVELS)[number]];\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if (__DEBUG_BUILD__) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nlet logger: Logger;\nif (__DEBUG_BUILD__) {\n logger = getGlobalSingleton('logger', makeLogger);\n} else {\n logger = makeLogger();\n}\n\nexport { logger };\n","export const DEFAULT_ENVIRONMENT = 'production';\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States = States.PENDING;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]> = [];\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport {\n arrayify,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isPlainObject,\n isThenable,\n logger,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { updateSession } from './session';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /** Transaction Name */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n this._user = user || {};\n if (this._session) {\n updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as (scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getAttachments(): Attachment[] {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n public applyToEvent(event: Event, hint: EventHint = {}): PromiseLike {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transaction = this._span.transaction;\n if (transaction) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: transaction.getDynamicSamplingContext(),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n __DEBUG_BUILD__ &&\n processor.id &&\n result === null &&\n logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalSingleton, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this._stack = [{ scope }];\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n this.getScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n this.getScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n this.getScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n this.getScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n this.getScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n this.getScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (__DEBUG_BUILD__ && !result) {\n // eslint-disable-next-line no-console\n console.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n public shouldSendDefaultPii(): boolean {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n private _withClient(callback: (client: Client, scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n __DEBUG_BUILD__ && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(carrier) || getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {\n const globalHubTopStack = parent.getStackTop();\n setHubOnCarrier(carrier, new Hub(globalHubTopStack.client, Scope.clone(globalHubTopStack.scope)));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope: Scope) => {\n scope.addEventProcessor((event: SentryEvent) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n}\n","import type {\n Breadcrumb,\n CaptureContext,\n CheckIn,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n MonitorConfig,\n Primitive,\n Severity,\n SeverityLevel,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { logger, uuid4 } from '@sentry/utils';\n\nimport type { Hub } from './hub';\nimport { getCurrentHub } from './hub';\nimport type { Scope } from './scope';\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): ReturnType {\n return getCurrentHub().captureException(exception, { captureContext });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): ReturnType {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event, hint?: EventHint): ReturnType {\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb): ReturnType {\n getCurrentHub().addBreadcrumb(breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): ReturnType {\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): ReturnType {\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): ReturnType {\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): ReturnType {\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): ReturnType {\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const client = getCurrentHub().getClient();\n if (!client) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig);\n }\n\n return uuid4();\n}\n","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\n/** JSDoc */\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nexport class TryCatch implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'TryCatch';\n\n /**\n * @inheritDoc\n */\n public name: string = TryCatch.id;\n\n /** JSDoc */\n private readonly _options: TryCatchOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n public setupOnce(): void {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n}\n\n/** JSDoc */\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: () => void): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type {\n HandlerDataFetch,\n HandlerDataXhr,\n SentryWrappedXMLHttpRequest,\n SentryXhrData,\n WrappedFunction,\n} from '@sentry/types';\n\nimport { isString } from './is';\nimport { CONSOLE_LEVELS, logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v2__';\n\nexport type InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n __DEBUG_BUILD__ && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in WINDOW)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: string): void {\n if (!(level in WINDOW.console)) {\n return;\n }\n\n fill(WINDOW.console, level, function (originalConsoleMethod: () => any): Function {\n return function (...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(WINDOW.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(WINDOW, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(WINDOW, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in WINDOW)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const url = args[1];\n const xhrInfo: SentryXhrData = (this[SENTRY_XHR_DATA_KEY] = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n request_headers: {},\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args: args as [string, string],\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr: this,\n } as HandlerDataXhr);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs as [string, string];\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n if (sentryXhrData && args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in WINDOW)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler: (typeof WINDOW)['onerror'] | null = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n WINDOW.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nlet _oldOnUnhandledRejectionHandler: (typeof WINDOW)['onunhandledrejection'] | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n WINDOW.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n// TODO remove this in v7 (this means the method will no longer be exported, under any name)\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, Severity, SeverityLevel, StackFrame, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n isUnhandledRejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception as DOMError) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n input: string,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\n return event;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Hub, Integration, Primitive, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\n/** JSDoc */\ntype GlobalHandlersIntegrations = Record;\n\n/** Global handlers */\nexport class GlobalHandlers implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GlobalHandlers';\n\n /**\n * @inheritDoc\n */\n public name: string = GlobalHandlers.id;\n\n /** JSDoc */\n private readonly _options: GlobalHandlersIntegrations;\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n private _installFunc: Record void) | undefined> = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n\n /** JSDoc */\n public constructor(options?: GlobalHandlersIntegrations) {\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key as GlobalHandlersIntegrationsOptionKeys];\n if (installFunc && options[key as GlobalHandlersIntegrationsOptionKeys]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key as GlobalHandlersIntegrationsOptionKeys] = undefined;\n }\n }\n }\n}\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler(): void {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler(): void {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e: any) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n __DEBUG_BUILD__ && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions(): [Hub, StackParser, boolean | undefined] {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n .replace(':80', '')\n .replace(':443', '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable max-lines */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event as SentryEvent, HandlerDataFetch, HandlerDataXhr, Integration } from '@sentry/types';\nimport type {\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n addInstrumentationHandler,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n SENTRY_XHR_DATA_KEY,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\ntype HandlerData = Record;\n\n/** JSDoc */\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nexport const BREADCRUMB_INTEGRATION_ID = 'Breadcrumbs';\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nexport class Breadcrumbs implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = BREADCRUMB_INTEGRATION_ID;\n\n /**\n * @inheritDoc\n */\n public name: string = Breadcrumbs.id;\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n public readonly options: Readonly;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n public setupOnce(): void {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n\n /**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\n public addSentryBreadcrumb(event: SentryEvent): void {\n if (this.options.sentry) {\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n }\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerData) => void {\n function _innerDomBreadcrumb(handlerData: HandlerData): void {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n target = _isEvent(event)\n ? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })\n : htmlTreeAsString(event, { keyAttrs, maxStringLength });\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _consoleBreadcrumb(handlerData: HandlerData & { args: unknown[]; level: string }): void {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/6010\n // see: https://github.com/getsentry/sentry-javascript/issues/5916\n for (let i = 0; i < handlerData.args.length; i++) {\n if (handlerData.args[i] === 'ref=Ref<') {\n handlerData.args[i + 1] = 'viewRef';\n break;\n }\n }\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _xhrBreadcrumb(handlerData: HandlerData & HandlerDataXhr): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _fetchBreadcrumb(handlerData: HandlerData & HandlerDataFetch & { response?: Response }): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: handlerData.response && handlerData.response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp,\n endTimestamp,\n };\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _historyBreadcrumb(handlerData: HandlerData & { from: string; to: string }): void {\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return event && !!(event as Record).target;\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, ExtendedError, Integration, StackParser } from '@sentry/types';\nimport { isInstanceOf } from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { exceptionFromError } from '../eventbuilder';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\ninterface LinkedErrorsOptions {\n key: string;\n limit: number;\n}\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: LinkedErrorsOptions['key'];\n\n /**\n * @inheritDoc\n */\n private readonly _limit: LinkedErrorsOptions['limit'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: Partial = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n const client = getCurrentHub().getClient();\n if (!client) {\n return;\n }\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(client.getOptions().stackParser, self._key, self._limit, event, hint) : event;\n });\n }\n}\n\n/**\n * @inheritDoc\n */\nexport function _handler(\n parser: StackParser,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): Event | null {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(parser, limit, hint.originalException as ExtendedError, key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nexport function _walkErrorTree(\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n stack: Exception[] = [],\n): Exception[] {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(parser, error[key]);\n return _walkErrorTree(parser, limit, error[key], key, [exception, ...stack]);\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, Integration } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\n/** HttpContext integration collects information about HTTP request headers */\nexport class HttpContext implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'HttpContext';\n\n /**\n * @inheritDoc\n */\n public name: string = HttpContext.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n if (getCurrentHub().getIntegration(HttpContext)) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n}\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import type { ClientOptions, Event, EventHint, StackFrame, StackParser } from '@sentry/types';\nimport { dateTimestampInSeconds, GLOBAL_OBJ, normalize, resolvedSyncPromise, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { Scope } from '../scope';\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!__DEBUG_BUILD__) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nexport const REPLAY_SESSION_KEY = 'sentryReplaySession';\nexport const REPLAY_EVENT_NAME = 'replay_event';\nexport const RECORDING_EVENT_NAME = 'replay_recording';\nexport const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nexport const SESSION_IDLE_PAUSE_DURATION = 300_000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nexport const SESSION_IDLE_EXPIRE_DURATION = 900_000; // 15 minutes in ms\n\n// The maximum length of a session\nexport const MAX_SESSION_LIFE = 3_600_000; // 60 minutes in ms\n\n/** Default flush delays */\nexport const DEFAULT_FLUSH_MIN_DELAY = 5_000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nexport const DEFAULT_FLUSH_MAX_DELAY = 5_500;\n\n/* How long to wait for error checkouts */\nexport const BUFFER_CHECKOUT_TIME = 60_000;\n\nexport const RETRY_BASE_INTERVAL = 5000;\nexport const RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nexport const NETWORK_BODY_MAX_SIZE = 150_000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nexport const CONSOLE_ARG_MAX_SIZE = 5_000;\n\n/* Min. time to wait before we consider something a slow click. */\nexport const SLOW_CLICK_THRESHOLD = 3_000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nexport const SLOW_CLICK_SCROLL_TIMEOUT = 300;\n/* Clicks in this time period are considered e.g. double/triple clicks. */\nexport const MULTI_CLICK_TIMEOUT = 1_000;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nexport const REPLAY_MAX_EVENT_BUFFER_SIZE = 20_000_000; // ~20MB\n","var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = n === null || n === void 0 ? void 0 : n.host;\n return Boolean(host && host.shadowRoot && host.shadowRoot === n);\n}\nfunction isInputTypeMasked({ maskInputOptions, tagName, type, }) {\n if (tagName.toLowerCase() === 'option') {\n tagName = 'select';\n }\n const actualType = typeof type === 'string' ? type.toLowerCase() : undefined;\n return (maskInputOptions[tagName.toLowerCase()] ||\n (actualType && maskInputOptions[actualType]) ||\n actualType === 'password' ||\n (tagName === 'input' && !type && maskInputOptions['text']));\n}\nfunction hasInputMaskOptions({ tagName, type, maskInputOptions, maskInputSelector, }) {\n return (maskInputSelector || isInputTypeMasked({ maskInputOptions, tagName, type }));\n}\nfunction maskInputValue({ input, maskInputSelector, unmaskInputSelector, maskInputOptions, tagName, type, value, maskInputFn, }) {\n let text = value || '';\n if (unmaskInputSelector && input.matches(unmaskInputSelector)) {\n return text;\n }\n if (input.hasAttribute('data-rr-is-password')) {\n type = 'password';\n }\n if (isInputTypeMasked({ maskInputOptions, tagName, type }) ||\n (maskInputSelector && input.matches(maskInputSelector))) {\n if (maskInputFn) {\n text = maskInputFn(text);\n }\n else {\n text = '*'.repeat(text.length);\n }\n }\n return text;\n}\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext('2d');\n if (!ctx)\n return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some((pixel) => pixel !== 0))\n return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute('data-rr-is-password')\n ? 'password'\n : type\n ? type.toLowerCase()\n : null;\n}\nfunction getInputValue(el, tagName, type) {\n typeof type === 'string' ? type.toLowerCase() : '';\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\n return el.getAttribute('value') || '';\n }\n return el.value;\n}\nfunction defineCustomElement(w, elementName) {\n try {\n if (!w.customElements.get(elementName)) {\n const CustomElement = w.HTMLElement;\n w.customElements.define(elementName, class extends CustomElement {\n });\n }\n }\n catch (_a) { }\n}\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\nconst IGNORED_NODE = -2;\nfunction defaultMaskFn(str) {\n return str ? str.replace(/[\\S]/g, '*') : '';\n}\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return 'form';\n }\n const processedTagName = element.tagName.toLowerCase().trim();\n if (tagNameRegex.test(processedTagName)) {\n return 'div';\n }\n return processedTagName;\n}\nfunction getCssRulesString(s) {\n try {\n const rules = s.rules || s.cssRules;\n return rules ? Array.from(rules).map(getCssRuleString).join('') : null;\n }\n catch (error) {\n return null;\n }\n}\nfunction getCssRuleString(rule) {\n let cssStringified = rule.cssText;\n if (isCSSImportRule(rule)) {\n try {\n cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;\n }\n catch (_a) {\n }\n }\n return validateStringifiedCssRule(cssStringified);\n}\nfunction validateStringifiedCssRule(cssStringified) {\n if (cssStringified.indexOf(':') > -1) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, '$1\\\\$2');\n }\n return cssStringified;\n}\nfunction isCSSImportRule(rule) {\n return 'styleSheet' in rule;\n}\nfunction stringifyStyleSheet(sheet) {\n return sheet.cssRules\n ? Array.from(sheet.cssRules)\n .map((rule) => rule.cssText ? validateStringifiedCssRule(rule.cssText) : '')\n .join('')\n : '';\n}\nfunction extractOrigin(url) {\n let origin = '';\n if (url.indexOf('//') > -1) {\n origin = url.split('/').slice(0, 3).join('/');\n }\n else {\n origin = url.split('/')[0];\n }\n origin = origin.split('?')[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst RELATIVE_PATH = /^(?!www\\.|(?:http|ftp)s?:\\/\\/|[A-Za-z]:\\\\|\\/\\/|#).*/;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || '';\n if (!filePath) {\n return origin;\n }\n if (!RELATIVE_PATH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === '/') {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split('/');\n const parts = filePath.split('/');\n stack.pop();\n for (const part of parts) {\n if (part === '.') {\n continue;\n }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\n });\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === '') {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars;\n let match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return '';\n }\n let output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === ',') {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n }\n else {\n let descriptorsStr = '';\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n let c = attributeValue.charAt(pos);\n if (c === '') {\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\n }\n else {\n if (c === ')') {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(', ');\n}\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === '') {\n return attributeValue;\n }\n const a = doc.createElement('a');\n a.href = attributeValue;\n return a.href;\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\n}\nfunction getHref() {\n const a = document.createElement('a');\n a.href = '';\n return a.href;\n}\nfunction transformAttribute(doc, element, _tagName, _name, value, maskAllText, unmaskTextSelector, maskTextFn) {\n if (!value) {\n return value;\n }\n const name = _name.toLowerCase();\n const tagName = _tagName.toLowerCase();\n if (name === 'src' || name === 'href') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset') {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style') {\n return absoluteToStylesheet(value, getHref());\n }\n else if (tagName === 'object' && name === 'data') {\n return absoluteToDoc(doc, value);\n }\n else if (maskAllText &&\n _shouldMaskAttribute(element, name, tagName, unmaskTextSelector)) {\n return maskTextFn ? maskTextFn(value) : defaultMaskFn(value);\n }\n return value;\n}\nfunction _shouldMaskAttribute(element, attribute, tagName, unmaskTextSelector) {\n if (unmaskTextSelector && element.matches(unmaskTextSelector)) {\n return false;\n }\n return (['placeholder', 'title', 'aria-label'].indexOf(attribute) > -1 ||\n (tagName === 'input' &&\n attribute === 'value' &&\n element.hasAttribute('type') &&\n ['submit', 'button'].indexOf(element.getAttribute('type').toLowerCase()) > -1));\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === 'string') {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < element.classList.length; eIndex++) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n return false;\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) {\n if (!node) {\n return false;\n }\n if (node.nodeType !== node.ELEMENT_NODE) {\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n }\n if (unmaskTextSelector) {\n if (node.matches(unmaskTextSelector) ||\n node.closest(unmaskTextSelector)) {\n return false;\n }\n }\n if (maskAllText) {\n return true;\n }\n if (typeof maskTextClass === 'string') {\n if (node.classList.contains(maskTextClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < node.classList.length; eIndex++) {\n const className = node.classList[eIndex];\n if (maskTextClass.test(className)) {\n return true;\n }\n }\n }\n if (maskTextSelector) {\n if (node.matches(maskTextSelector)) {\n return true;\n }\n }\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n }\n catch (error) {\n return;\n }\n if (readyState !== 'complete') {\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener('load', () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n iframeEl.src === '') {\n setTimeout(listener, 0);\n return;\n }\n iframeEl.addEventListener('load', listener);\n}\nfunction serializeNode(n, options) {\n var _a;\n const { doc, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, } = options;\n let rootId;\n if (doc.__sn) {\n const docId = doc.__sn.id;\n rootId = docId === 1 ? undefined : docId;\n }\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== 'CSS1Compat') {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode,\n rootId,\n };\n }\n else {\n return {\n type: NodeType.Document,\n childNodes: [],\n rootId,\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId,\n };\n case n.ELEMENT_NODE:\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n for (const { name, value } of Array.from(n.attributes)) {\n if (!skipAttribute(tagName, name)) {\n attributes[name] = transformAttribute(doc, n, tagName, name, value, maskAllText, unmaskTextSelector, maskTextFn);\n }\n }\n if (tagName === 'link' && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = getCssRulesString(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText ||\n n.textContent ||\n '').trim().length) {\n const cssText = getCssRulesString(n.sheet);\n if (cssText) {\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select' ||\n tagName === 'option') {\n const el = n;\n const type = getInputType(el);\n const value = getInputValue(el, tagName.toUpperCase(), type);\n const checked = n.checked;\n if (type !== 'submit' &&\n type !== 'button' &&\n value) {\n attributes.value = maskInputValue({\n input: el,\n type,\n tagName,\n value,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes.selected = true;\n }\n else {\n delete attributes.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n const blankCanvas = document.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === 'img' && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement('canvas');\n canvasCtx = canvasService.getContext('2d');\n }\n const image = n;\n const oldValue = image.crossOrigin;\n image.crossOrigin = 'anonymous';\n const recordInlineImage = () => {\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n catch (err) {\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\n }\n oldValue\n ? (attributes.crossOrigin = oldValue)\n : delete attributes.crossOrigin;\n };\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.onload = recordInlineImage;\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes.rr_mediaCurrentTime = n.currentTime;\n }\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock,\n rootId,\n };\n case n.TEXT_NODE:\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\n textContent = stringifyStyleSheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref());\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n if (parentTagName === 'TEXTAREA' && textContent) {\n textContent = '';\n }\n else if (parentTagName === 'OPTION' && textContent) {\n const option = n.parentNode;\n textContent = maskInputValue({\n input: option,\n type: null,\n tagName: parentTagName,\n value: textContent,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n else if (!isStyle &&\n !isScript &&\n needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) &&\n textContent) {\n textContent = maskTextFn\n ? maskTextFn(textContent)\n : defaultMaskFn(textContent);\n }\n return {\n type: NodeType.Text,\n textContent: textContent || '',\n isStyle,\n rootId,\n };\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: '',\n rootId,\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: n.textContent || '',\n rootId,\n };\n default:\n return false;\n }\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined || maybeAttr === null) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n }\n else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n (sn.attributes.rel === 'preload' ||\n sn.attributes.rel === 'modulepreload') &&\n sn.attributes.as === 'script') ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n sn.attributes.href.endsWith('.js')))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const { doc, map, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, keepIframeSrcFn = () => false, } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n });\n if (!_serializedNode) {\n console.warn(n, 'not serialized');\n return null;\n }\n let id;\n if ('__sn' in n) {\n id = n.__sn.id;\n }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n n.__sn = serializedNode;\n if (id === IGNORED_NODE) {\n return null;\n }\n map[id] = n;\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n if (n.shadowRoot)\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document ||\n serializedNode.type === NodeType.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n _serializedNode.type === NodeType.Element &&\n _serializedNode.tagName === 'head') {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n };\n for (const childN of Array.from(n.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n) && n.shadowRoot) {\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedChildNode.isShadow = true;\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode && isShadowRoot(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(n, () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const { blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskInputSelector = null, unmaskInputSelector = null, maskAllText = false, maskAllInputs = false, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\n const idNodeMap = {};\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n }\n : maskAllInputs === false\n ? {}\n : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true,\n }\n : slimDOM === false\n ? {}\n : slimDOM;\n return [\n serializeNodeWithId(n, {\n doc: n,\n map: idNodeMap,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n }),\n idNodeMap,\n ];\n}\nfunction skipAttribute(tagName, attributeName, value) {\n return ((tagName === 'video' || tagName === 'audio') && attributeName === 'autoplay');\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\nfunction parse(css, options = {}) {\n let lineno = 1;\n let column = 1;\n function updatePosition(str) {\n const lines = str.match(/\\n/g);\n if (lines) {\n lineno += lines.length;\n }\n let i = str.lastIndexOf('\\n');\n column = i === -1 ? column + str.length : str.length - i;\n }\n function position() {\n const start = { line: lineno, column };\n return (node) => {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n class Position {\n constructor(start) {\n this.start = start;\n this.end = { line: lineno, column };\n this.source = options.source;\n }\n }\n Position.prototype.content = css;\n const errorsList = [];\n function error(msg) {\n const err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = css;\n if (options.silent) {\n errorsList.push(err);\n }\n else {\n throw err;\n }\n }\n function stylesheet() {\n const rulesList = rules();\n return {\n type: 'stylesheet',\n stylesheet: {\n source: options.source,\n rules: rulesList,\n parsingErrors: errorsList,\n },\n };\n }\n function open() {\n return match(/^{\\s*/);\n }\n function close() {\n return match(/^}/);\n }\n function rules() {\n let node;\n const rules = [];\n whitespace();\n comments(rules);\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\n if (node !== false) {\n rules.push(node);\n comments(rules);\n }\n }\n return rules;\n }\n function match(re) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n function whitespace() {\n match(/^\\s*/);\n }\n function comments(rules = []) {\n let c;\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n c = comment();\n }\n return rules;\n }\n function comment() {\n const pos = position();\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\n return;\n }\n let i = 2;\n while ('' !== css.charAt(i) &&\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\n ++i;\n }\n i += 2;\n if ('' === css.charAt(i - 1)) {\n return error('End of comment missing');\n }\n const str = css.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n css = css.slice(i);\n column += 2;\n return pos({\n type: 'comment',\n comment: str,\n });\n }\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n return trim(m[0])\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\n return m.replace(/,/g, '\\u200C');\n })\n .split(/\\s*(?![^(]*\\)),\\s*/)\n .map((s) => {\n return s.replace(/\\u200C/g, ',');\n });\n }\n function declaration() {\n const pos = position();\n let propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const prop = trim(propMatch[0]);\n if (!match(/^:\\s*/)) {\n return error(`property missing ':'`);\n }\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\n const ret = pos({\n type: 'declaration',\n property: prop.replace(commentre, ''),\n value: val ? trim(val[0]).replace(commentre, '') : '',\n });\n match(/^[;\\s]*/);\n return ret;\n }\n function declarations() {\n const decls = [];\n if (!open()) {\n return error(`missing '{'`);\n }\n comments(decls);\n let decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n decl = declaration();\n }\n if (!close()) {\n return error(`missing '}'`);\n }\n return decls;\n }\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n if (!vals.length) {\n return;\n }\n return pos({\n type: 'keyframe',\n values: vals,\n declarations: declarations(),\n });\n }\n function atkeyframes() {\n const pos = position();\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\n if (!m) {\n return;\n }\n const vendor = m[1];\n m = match(/^([-\\w]+)\\s*/);\n if (!m) {\n return error('@keyframes missing name');\n }\n const name = m[1];\n if (!open()) {\n return error(`@keyframes missing '{'`);\n }\n let frame;\n let frames = comments();\n while ((frame = keyframe())) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n if (!close()) {\n return error(`@keyframes missing '}'`);\n }\n return pos({\n type: 'keyframes',\n name,\n vendor,\n keyframes: frames,\n });\n }\n function atsupports() {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n if (!open()) {\n return error(`@supports missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@supports missing '}'`);\n }\n return pos({\n type: 'supports',\n supports,\n rules: style,\n });\n }\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@host missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@host missing '}'`);\n }\n return pos({\n type: 'host',\n rules: style,\n });\n }\n function atmedia() {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n if (!open()) {\n return error(`@media missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@media missing '}'`);\n }\n return pos({\n type: 'media',\n media,\n rules: style,\n });\n }\n function atcustommedia() {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n return pos({\n type: 'custom-media',\n name: trim(m[1]),\n media: trim(m[2]),\n });\n }\n function atpage() {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n const sel = selector() || [];\n if (!open()) {\n return error(`@page missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@page missing '}'`);\n }\n return pos({\n type: 'page',\n selectors: sel,\n declarations: decls,\n });\n }\n function atdocument() {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n if (!open()) {\n return error(`@document missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@document missing '}'`);\n }\n return pos({\n type: 'document',\n document: doc,\n vendor,\n rules: style,\n });\n }\n function atfontface() {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@font-face missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@font-face missing '}'`);\n }\n return pos({\n type: 'font-face',\n declarations: decls,\n });\n }\n const atimport = _compileAtrule('import');\n const atcharset = _compileAtrule('charset');\n const atnamespace = _compileAtrule('namespace');\n function _compileAtrule(name) {\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\n return () => {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret = { type: name };\n ret[name] = m[1].trim();\n return pos(ret);\n };\n }\n function atrule() {\n if (css[0] !== '@') {\n return;\n }\n return (atkeyframes() ||\n atmedia() ||\n atcustommedia() ||\n atsupports() ||\n atimport() ||\n atcharset() ||\n atnamespace() ||\n atdocument() ||\n atpage() ||\n athost() ||\n atfontface());\n }\n function rule() {\n const pos = position();\n const sel = selector();\n if (!sel) {\n return error('selector missing');\n }\n comments();\n return pos({\n type: 'rule',\n selectors: sel,\n declarations: declarations(),\n });\n }\n return addParent(stylesheet());\n}\nfunction trim(str) {\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\n}\nfunction addParent(obj, parent) {\n const isNode = obj && typeof obj.type === 'string';\n const childParent = isNode ? obj : parent;\n for (const k of Object.keys(obj)) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach((v) => {\n addParent(v, childParent);\n });\n }\n else if (value && typeof value === 'object') {\n addParent(value, childParent);\n }\n }\n if (isNode) {\n Object.defineProperty(obj, 'parent', {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null,\n });\n }\n return obj;\n}\n\nconst tagMap = {\n script: 'noscript',\n altglyph: 'altGlyph',\n altglyphdef: 'altGlyphDef',\n altglyphitem: 'altGlyphItem',\n animatecolor: 'animateColor',\n animatemotion: 'animateMotion',\n animatetransform: 'animateTransform',\n clippath: 'clipPath',\n feblend: 'feBlend',\n fecolormatrix: 'feColorMatrix',\n fecomponenttransfer: 'feComponentTransfer',\n fecomposite: 'feComposite',\n feconvolvematrix: 'feConvolveMatrix',\n fediffuselighting: 'feDiffuseLighting',\n fedisplacementmap: 'feDisplacementMap',\n fedistantlight: 'feDistantLight',\n fedropshadow: 'feDropShadow',\n feflood: 'feFlood',\n fefunca: 'feFuncA',\n fefuncb: 'feFuncB',\n fefuncg: 'feFuncG',\n fefuncr: 'feFuncR',\n fegaussianblur: 'feGaussianBlur',\n feimage: 'feImage',\n femerge: 'feMerge',\n femergenode: 'feMergeNode',\n femorphology: 'feMorphology',\n feoffset: 'feOffset',\n fepointlight: 'fePointLight',\n fespecularlighting: 'feSpecularLighting',\n fespotlight: 'feSpotLight',\n fetile: 'feTile',\n feturbulence: 'feTurbulence',\n foreignobject: 'foreignObject',\n glyphref: 'glyphRef',\n lineargradient: 'linearGradient',\n radialgradient: 'radialGradient',\n};\nfunction getTagName(n) {\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\n if (tagName === 'link' && n.attributes._cssText) {\n tagName = 'style';\n }\n return tagName;\n}\nfunction escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\nfunction addHoverClass(cssText, cache) {\n const cachedStyle = cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.get(cssText);\n if (cachedStyle)\n return cachedStyle;\n const ast = parse(cssText, {\n silent: true,\n });\n if (!ast.stylesheet) {\n return cssText;\n }\n const selectors = [];\n ast.stylesheet.rules.forEach((rule) => {\n if ('selectors' in rule) {\n (rule.selectors || []).forEach((selector) => {\n if (HOVER_SELECTOR.test(selector)) {\n selectors.push(selector);\n }\n });\n }\n });\n if (selectors.length === 0) {\n return cssText;\n }\n const selectorMatcher = new RegExp(selectors\n .filter((selector, index) => selectors.indexOf(selector) === index)\n .sort((a, b) => b.length - a.length)\n .map((selector) => {\n return escapeRegExp(selector);\n })\n .join('|'), 'g');\n const result = cssText.replace(selectorMatcher, (selector) => {\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\n return `${selector}, ${newSelector}`;\n });\n cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.set(cssText, result);\n return result;\n}\nfunction createCache() {\n const stylesWithHoverClass = new Map();\n return {\n stylesWithHoverClass,\n };\n}\nfunction buildNode(n, options) {\n const { doc, hackCss, cache } = options;\n switch (n.type) {\n case NodeType.Document:\n return doc.implementation.createDocument(null, '', null);\n case NodeType.DocumentType:\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\n case NodeType.Element:\n const tagName = getTagName(n);\n let node;\n if (n.isSVG) {\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\n }\n else {\n node = doc.createElement(tagName);\n }\n for (const name in n.attributes) {\n if (!n.attributes.hasOwnProperty(name)) {\n continue;\n }\n let value = n.attributes[name];\n if (tagName === 'option' && name === 'selected' && value === false) {\n continue;\n }\n value =\n typeof value === 'boolean' || typeof value === 'number' || value === null ? '' : value;\n if (!name.startsWith('rr_')) {\n const isTextarea = tagName === 'textarea' && name === 'value';\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\n if (isRemoteOrDynamicCss && hackCss) {\n value = addHoverClass(value, cache);\n }\n if (isTextarea || isRemoteOrDynamicCss) {\n const child = doc.createTextNode(value);\n for (const c of Array.from(node.childNodes)) {\n if (c.nodeType === node.TEXT_NODE) {\n node.removeChild(c);\n }\n }\n node.appendChild(child);\n continue;\n }\n try {\n if (n.isSVG && name === 'xlink:href') {\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value);\n }\n else if (name === 'onload' ||\n name === 'onclick' ||\n name.substring(0, 7) === 'onmouse') {\n node.setAttribute('_' + name, value);\n }\n else if (tagName === 'meta' &&\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\n name === 'content') {\n node.setAttribute('csp-content', value);\n continue;\n }\n else if (tagName === 'link' &&\n (n.attributes.rel === 'preload' || n.attributes.rel === 'modulepreload') &&\n n.attributes.as === 'script') {\n }\n else if (tagName === 'link' &&\n n.attributes.rel === 'prefetch' &&\n typeof n.attributes.href === 'string' &&\n n.attributes.href.endsWith('.js')) {\n }\n else if (tagName === 'img' &&\n n.attributes.srcset &&\n n.attributes.rr_dataURL) {\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\n }\n else {\n node.setAttribute(name, value);\n }\n }\n catch (error) {\n }\n }\n else {\n if (tagName === 'canvas' && name === 'rr_dataURL') {\n const image = document.createElement('img');\n image.src = value;\n image.onload = () => {\n const ctx = node.getContext('2d');\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n }\n else if (tagName === 'img' && name === 'rr_dataURL') {\n const image = node;\n if (!image.currentSrc.startsWith('data:')) {\n image.setAttribute('rrweb-original-src', n.attributes.src);\n image.src = value;\n }\n }\n if (name === 'rr_width') {\n node.style.width = value;\n }\n else if (name === 'rr_height') {\n node.style.height = value;\n }\n else if (name === 'rr_mediaCurrentTime') {\n node.currentTime = n.attributes\n .rr_mediaCurrentTime;\n }\n else if (name === 'rr_mediaState') {\n switch (value) {\n case 'played':\n node\n .play()\n .catch((e) => console.warn('media playback error', e));\n break;\n case 'paused':\n node.pause();\n break;\n }\n }\n }\n }\n if (n.isShadowHost) {\n if (!node.shadowRoot) {\n node.attachShadow({ mode: 'open' });\n if (doc.defaultView) {\n defineCustomElement(doc.defaultView, tagName);\n }\n }\n else {\n while (node.shadowRoot.firstChild) {\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\n }\n }\n }\n return node;\n case NodeType.Text:\n return doc.createTextNode(n.isStyle && hackCss\n ? addHoverClass(n.textContent, cache)\n : n.textContent);\n case NodeType.CDATA:\n return doc.createCDATASection(n.textContent);\n case NodeType.Comment:\n return doc.createComment(n.textContent);\n default:\n return null;\n }\n}\nfunction buildNodeWithSN(n, options) {\n const { doc, map, skipChild = false, hackCss = true, afterAppend, cache, } = options;\n let node = buildNode(n, { doc, hackCss, cache });\n if (!node) {\n return null;\n }\n if (n.rootId) {\n console.assert(map[n.rootId] === doc, 'Target document should has the same root id.');\n }\n if (n.type === NodeType.Document) {\n doc.close();\n doc.open();\n if (n.compatMode === 'BackCompat' &&\n n.childNodes &&\n n.childNodes[0].type !== NodeType.DocumentType) {\n if (n.childNodes[0].type === NodeType.Element &&\n 'xmlns' in n.childNodes[0].attributes &&\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\n doc.write('');\n }\n else {\n doc.write('');\n }\n }\n node = doc;\n }\n node.__sn = n;\n map[n.id] = node;\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\n !skipChild) {\n for (const childN of n.childNodes) {\n const childNode = buildNodeWithSN(childN, {\n doc,\n map,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n if (!childNode) {\n console.warn('Failed to rebuild', childN);\n continue;\n }\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\n node.shadowRoot.appendChild(childNode);\n }\n else {\n node.appendChild(childNode);\n }\n if (afterAppend) {\n afterAppend(childNode);\n }\n }\n }\n return node;\n}\nfunction visit(idNodeMap, onVisit) {\n function walk(node) {\n onVisit(node);\n }\n for (const key in idNodeMap) {\n if (idNodeMap[key]) {\n walk(idNodeMap[key]);\n }\n }\n}\nfunction handleScroll(node) {\n const n = node.__sn;\n if (n.type !== NodeType.Element) {\n return;\n }\n const el = node;\n for (const name in n.attributes) {\n if (!(n.attributes.hasOwnProperty(name) && name.startsWith('rr_'))) {\n continue;\n }\n const value = n.attributes[name];\n if (name === 'rr_scrollLeft') {\n el.scrollLeft = value;\n }\n if (name === 'rr_scrollTop') {\n el.scrollTop = value;\n }\n }\n}\nfunction rebuild(n, options) {\n const { doc, onVisit, hackCss = true, afterAppend, cache } = options;\n const idNodeMap = {};\n const node = buildNodeWithSN(n, {\n doc,\n map: idNodeMap,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n visit(idNodeMap, (visitedNode) => {\n if (onVisit) {\n onVisit(visitedNode);\n }\n handleScroll(visitedNode);\n });\n return [node, idNodeMap];\n}\n\nexport { IGNORED_NODE, NodeType, addHoverClass, buildNodeWithSN, createCache, defineCustomElement, getInputType, getInputValue, hasInputMaskOptions, is2DCanvasBlank, isElement, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, snapshot, transformAttribute };\n","var EventType;\n(function (EventType) {\n EventType[EventType[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType[EventType[\"Load\"] = 1] = \"Load\";\n EventType[EventType[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType[EventType[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType[EventType[\"Meta\"] = 4] = \"Meta\";\n EventType[EventType[\"Custom\"] = 5] = \"Custom\";\n EventType[EventType[\"Plugin\"] = 6] = \"Plugin\";\n})(EventType || (EventType = {}));\nvar IncrementalSource;\n(function (IncrementalSource) {\n IncrementalSource[IncrementalSource[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource[IncrementalSource[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource[IncrementalSource[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource[IncrementalSource[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource[IncrementalSource[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource[IncrementalSource[\"Input\"] = 5] = \"Input\";\n IncrementalSource[IncrementalSource[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource[IncrementalSource[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource[IncrementalSource[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource[IncrementalSource[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource[IncrementalSource[\"Font\"] = 10] = \"Font\";\n IncrementalSource[IncrementalSource[\"Log\"] = 11] = \"Log\";\n IncrementalSource[IncrementalSource[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource[IncrementalSource[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n})(IncrementalSource || (IncrementalSource = {}));\nvar MouseInteractions;\n(function (MouseInteractions) {\n MouseInteractions[MouseInteractions[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions[MouseInteractions[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions[MouseInteractions[\"Click\"] = 2] = \"Click\";\n MouseInteractions[MouseInteractions[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions[MouseInteractions[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions[MouseInteractions[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions[MouseInteractions[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions[MouseInteractions[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions[MouseInteractions[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions[MouseInteractions[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions[MouseInteractions[\"TouchCancel\"] = 10] = \"TouchCancel\";\n})(MouseInteractions || (MouseInteractions = {}));\nvar CanvasContext;\n(function (CanvasContext) {\n CanvasContext[CanvasContext[\"2D\"] = 0] = \"2D\";\n CanvasContext[CanvasContext[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext[CanvasContext[\"WebGL2\"] = 2] = \"WebGL2\";\n})(CanvasContext || (CanvasContext = {}));\nvar MediaInteractions;\n(function (MediaInteractions) {\n MediaInteractions[MediaInteractions[\"Play\"] = 0] = \"Play\";\n MediaInteractions[MediaInteractions[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions[MediaInteractions[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions[MediaInteractions[\"VolumeChange\"] = 3] = \"VolumeChange\";\n})(MediaInteractions || (MediaInteractions = {}));\nvar ReplayerEvents;\n(function (ReplayerEvents) {\n ReplayerEvents[\"Start\"] = \"start\";\n ReplayerEvents[\"Pause\"] = \"pause\";\n ReplayerEvents[\"Resume\"] = \"resume\";\n ReplayerEvents[\"Resize\"] = \"resize\";\n ReplayerEvents[\"Finish\"] = \"finish\";\n ReplayerEvents[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents[\"EventCast\"] = \"event-cast\";\n ReplayerEvents[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents[\"Flush\"] = \"flush\";\n ReplayerEvents[\"StateChange\"] = \"state-change\";\n ReplayerEvents[\"PlayBack\"] = \"play-back\";\n})(ReplayerEvents || (ReplayerEvents = {}));\n\nexport { CanvasContext, EventType, IncrementalSource, MediaInteractions, MouseInteractions, ReplayerEvents };\n","import { IncrementalSource } from './types.js';\nimport { IGNORED_NODE, isShadowRoot, NodeType } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nfunction createMirror() {\n return {\n map: {},\n getId(n) {\n if (!n || !n.__sn) {\n return -1;\n }\n return n.__sn.id;\n },\n getNode(id) {\n return this.map[id] || null;\n },\n removeNodeFromMap(n) {\n const id = n.__sn && n.__sn.id;\n delete this.map[id];\n if (n.childNodes) {\n n.childNodes.forEach((child) => this.removeNodeFromMap(child));\n }\n },\n has(id) {\n return this.map.hasOwnProperty(id);\n },\n reset() {\n this.map = {};\n },\n };\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\n '\\r\\n' +\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n '\\r\\n' +\n 'or you can use record.mirror to access the mirror instance during recording.';\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n};\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === 'map') {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n}\nfunction throttle(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function (arg) {\n let now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n let remaining = wait - (now - previous);\n let context = this;\n let args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n }\n else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(target, key, isRevoked\n ? d\n : {\n set(value) {\n setTimeout(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n },\n });\n return () => hookSetter(target, key, original || {}, true);\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => { };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === 'function') {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original,\n },\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n }\n catch (_a) {\n return () => { };\n }\n}\nfunction getWindowHeight() {\n return (window.innerHeight ||\n (document.documentElement && document.documentElement.clientHeight) ||\n (document.body && document.body.clientHeight));\n}\nfunction getWindowWidth() {\n return (window.innerWidth ||\n (document.documentElement && document.documentElement.clientWidth) ||\n (document.body && document.body.clientWidth));\n}\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector) {\n if (!node) {\n return false;\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n let needBlock = false;\n const needUnblock = unblockSelector && node.matches(unblockSelector);\n if (typeof blockClass === 'string') {\n if (node.closest !== undefined) {\n needBlock =\n !needUnblock &&\n node.closest('.' + blockClass) !== null;\n }\n else {\n needBlock =\n !needUnblock && node.classList.contains(blockClass);\n }\n }\n else {\n !needUnblock &&\n node.classList.forEach((className) => {\n if (blockClass.test(className)) {\n needBlock = true;\n }\n });\n }\n if (!needBlock && blockSelector) {\n needBlock = node.matches(blockSelector);\n }\n return ((!needUnblock && needBlock) ||\n isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector));\n }\n if (node.nodeType === node.TEXT_NODE) {\n return isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector);\n }\n return isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector);\n}\nfunction isIgnored(n) {\n if ('__sn' in n) {\n return n.__sn.id === IGNORED_NODE;\n }\n return false;\n}\nfunction isAncestorRemoved(target, mirror) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror.getId(target);\n if (!mirror.has(id)) {\n return true;\n }\n if (target.parentNode &&\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror);\n}\nfunction isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype\n .forEach;\n }\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype\n .forEach;\n }\n if (!Node.prototype.contains) {\n Node.prototype.contains = function contains(node) {\n if (!(0 in arguments)) {\n throw new TypeError('1 argument is required');\n }\n do {\n if (this === node) {\n return true;\n }\n } while ((node = node && node.parentNode));\n return false;\n };\n }\n}\nclass TreeIndex {\n constructor() {\n this.reset();\n }\n add(mutation) {\n const parentTreeNode = this.indexes.get(mutation.parentId);\n const treeNode = {\n id: mutation.node.id,\n mutation,\n children: [],\n texts: [],\n attributes: [],\n };\n if (!parentTreeNode) {\n this.tree[treeNode.id] = treeNode;\n }\n else {\n treeNode.parent = parentTreeNode;\n parentTreeNode.children[treeNode.id] = treeNode;\n }\n this.indexes.set(treeNode.id, treeNode);\n }\n remove(mutation, mirror) {\n const parentTreeNode = this.indexes.get(mutation.parentId);\n const treeNode = this.indexes.get(mutation.id);\n const deepRemoveFromMirror = (id) => {\n this.removeIdSet.add(id);\n const node = mirror.getNode(id);\n node === null || node === void 0 ? void 0 : node.childNodes.forEach((childNode) => {\n if ('__sn' in childNode) {\n deepRemoveFromMirror(childNode.__sn.id);\n }\n });\n };\n const deepRemoveFromTreeIndex = (node) => {\n this.removeIdSet.add(node.id);\n Object.values(node.children).forEach((n) => deepRemoveFromTreeIndex(n));\n const _treeNode = this.indexes.get(node.id);\n if (_treeNode) {\n const _parentTreeNode = _treeNode.parent;\n if (_parentTreeNode) {\n delete _treeNode.parent;\n delete _parentTreeNode.children[_treeNode.id];\n this.indexes.delete(mutation.id);\n }\n }\n };\n if (!treeNode) {\n this.removeNodeMutations.push(mutation);\n deepRemoveFromMirror(mutation.id);\n }\n else if (!parentTreeNode) {\n delete this.tree[treeNode.id];\n this.indexes.delete(treeNode.id);\n deepRemoveFromTreeIndex(treeNode);\n }\n else {\n delete treeNode.parent;\n delete parentTreeNode.children[treeNode.id];\n this.indexes.delete(mutation.id);\n deepRemoveFromTreeIndex(treeNode);\n }\n }\n text(mutation) {\n const treeNode = this.indexes.get(mutation.id);\n if (treeNode) {\n treeNode.texts.push(mutation);\n }\n else {\n this.textMutations.push(mutation);\n }\n }\n attribute(mutation) {\n const treeNode = this.indexes.get(mutation.id);\n if (treeNode) {\n treeNode.attributes.push(mutation);\n }\n else {\n this.attributeMutations.push(mutation);\n }\n }\n scroll(d) {\n this.scrollMap.set(d.id, d);\n }\n input(d) {\n this.inputMap.set(d.id, d);\n }\n flush() {\n const { tree, removeNodeMutations, textMutations, attributeMutations, } = this;\n const batchMutationData = {\n source: IncrementalSource.Mutation,\n removes: removeNodeMutations,\n texts: textMutations,\n attributes: attributeMutations,\n adds: [],\n };\n const walk = (treeNode, removed) => {\n if (removed) {\n this.removeIdSet.add(treeNode.id);\n }\n batchMutationData.texts = batchMutationData.texts\n .concat(removed ? [] : treeNode.texts)\n .filter((m) => !this.removeIdSet.has(m.id));\n batchMutationData.attributes = batchMutationData.attributes\n .concat(removed ? [] : treeNode.attributes)\n .filter((m) => !this.removeIdSet.has(m.id));\n if (!this.removeIdSet.has(treeNode.id) &&\n !this.removeIdSet.has(treeNode.mutation.parentId) &&\n !removed) {\n batchMutationData.adds.push(treeNode.mutation);\n if (treeNode.children) {\n Object.values(treeNode.children).forEach((n) => walk(n, false));\n }\n }\n else {\n Object.values(treeNode.children).forEach((n) => walk(n, true));\n }\n };\n Object.values(tree).forEach((n) => walk(n, false));\n for (const id of this.scrollMap.keys()) {\n if (this.removeIdSet.has(id)) {\n this.scrollMap.delete(id);\n }\n }\n for (const id of this.inputMap.keys()) {\n if (this.removeIdSet.has(id)) {\n this.inputMap.delete(id);\n }\n }\n const scrollMap = new Map(this.scrollMap);\n const inputMap = new Map(this.inputMap);\n this.reset();\n return {\n mutationData: batchMutationData,\n scrollMap,\n inputMap,\n };\n }\n reset() {\n this.tree = [];\n this.indexes = new Map();\n this.removeNodeMutations = [];\n this.textMutations = [];\n this.attributeMutations = [];\n this.removeIdSet = new Set();\n this.scrollMap = new Map();\n this.inputMap = new Map();\n }\n idRemoved(id) {\n return this.removeIdSet.has(id);\n }\n}\nfunction queueToResolveTrees(queue) {\n const queueNodeMap = {};\n const putIntoMap = (m, parent) => {\n const nodeInTree = {\n value: m,\n parent,\n children: [],\n };\n queueNodeMap[m.node.id] = nodeInTree;\n return nodeInTree;\n };\n const queueNodeTrees = [];\n for (const mutation of queue) {\n const { nextId, parentId } = mutation;\n if (nextId && nextId in queueNodeMap) {\n const nextInTree = queueNodeMap[nextId];\n if (nextInTree.parent) {\n const idx = nextInTree.parent.children.indexOf(nextInTree);\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\n }\n else {\n const idx = queueNodeTrees.indexOf(nextInTree);\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\n }\n continue;\n }\n if (parentId in queueNodeMap) {\n const parentInTree = queueNodeMap[parentId];\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\n continue;\n }\n queueNodeTrees.push(putIntoMap(mutation, null));\n }\n return queueNodeTrees;\n}\nfunction iterateResolveTree(tree, cb) {\n cb(tree.value);\n for (let i = tree.children.length - 1; i >= 0; i--) {\n iterateResolveTree(tree.children[i], cb);\n }\n}\nfunction isIframeINode(node) {\n if ('__sn' in node) {\n return (node.__sn.type === NodeType.Element && node.__sn.tagName === 'iframe');\n }\n return false;\n}\nfunction getBaseDimension(node, rootIframe) {\n var _a, _b;\n const frameElement = (_b = (_a = node.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) === null || _b === void 0 ? void 0 : _b.frameElement;\n if (!frameElement || frameElement === rootIframe) {\n return {\n x: 0,\n y: 0,\n relativeScale: 1,\n absoluteScale: 1,\n };\n }\n const frameDimension = frameElement.getBoundingClientRect();\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\n const relativeScale = frameDimension.height / frameElement.clientHeight;\n return {\n x: frameDimension.x * frameBaseDimension.relativeScale +\n frameBaseDimension.x,\n y: frameDimension.y * frameBaseDimension.relativeScale +\n frameBaseDimension.y,\n relativeScale,\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\n };\n}\nfunction hasShadowRoot(n) {\n return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);\n}\n\nexport { TreeIndex, _mirror, createMirror, getBaseDimension, getWindowHeight, getWindowWidth, hasShadowRoot, hookSetter, isAncestorRemoved, isBlocked, isIframeINode, isIgnored, isTouchEvent, iterateResolveTree, on, patch, polyfill, queueToResolveTrees, throttle };\n","import { isShadowRoot, maskInputValue, transformAttribute, needMaskingText, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isAncestorRemoved, isIframeINode, hasShadowRoot } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\n return '__ln' in n;\n}\nclass DoubleLinkedList {\n constructor() {\n this.length = 0;\n this.head = null;\n }\n get(position) {\n if (position >= this.length) {\n throw new Error('Position outside of list range');\n }\n let current = this.head;\n for (let index = 0; index < position; index++) {\n current = (current === null || current === void 0 ? void 0 : current.next) || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null,\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n }\n else if (n.nextSibling &&\n isNodeInLinkedList(n.nextSibling) &&\n n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n }\n else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n this.length++;\n }\n removeNode(n) {\n const current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n }\n }\n else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nfunction isINode(n) {\n return '__sn' in n;\n}\nclass MutationBuffer {\n constructor() {\n this.frozen = false;\n this.locked = false;\n this.texts = [];\n this.attributes = [];\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.processMutations = (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n };\n this.emit = () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n) => {\n var _a, _b, _c, _d, _e;\n const shadowHost = n.getRootNode\n ? (_a = n.getRootNode()) === null || _a === void 0 ? void 0 : _a.host\n : null;\n let rootShadowHost = shadowHost;\n while ((_c = (_b = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _b === void 0 ? void 0 : _b.call(rootShadowHost)) === null || _c === void 0 ? void 0 : _c.host)\n rootShadowHost =\n ((_e = (_d = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _d === void 0 ? void 0 : _d.call(rootShadowHost)) === null || _e === void 0 ? void 0 : _e.host) ||\n null;\n const notInDoc = !this.doc.contains(n) &&\n (!rootShadowHost || !this.doc.contains(rootShadowHost));\n if (!n.parentNode || notInDoc) {\n return;\n }\n const parentId = isShadowRoot(n.parentNode)\n ? this.mirror.getId(shadowHost)\n : this.mirror.getId(n.parentNode);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n let sn = serializeNodeWithId(n, {\n doc: this.doc,\n map: this.mirror.map,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n unblockSelector: this.unblockSelector,\n maskTextClass: this.maskTextClass,\n maskTextSelector: this.maskTextSelector,\n unmaskTextSelector: this.unmaskTextSelector,\n maskInputSelector: this.maskInputSelector,\n unmaskInputSelector: this.unmaskInputSelector,\n skipChild: true,\n inlineStylesheet: this.inlineStylesheet,\n maskAllText: this.maskAllText,\n maskInputOptions: this.maskInputOptions,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isIframeINode(currentN)) {\n this.iframeManager.addIframe(currentN);\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n this.iframeManager.attachIframe(iframe, childSn);\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn,\n });\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n of this.movedSet) {\n if (isParentRemoved(this.removes, n, this.mirror) &&\n !this.movedSet.has(n.parentNode)) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) &&\n !isParentRemoved(this.removes, n, this.mirror)) {\n pushAdd(n);\n }\n else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n }\n else {\n this.droppedSet.add(n);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(candidate.value.parentNode);\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n for (let index = addList.length - 1; index >= 0; index--) {\n const _node = addList.get(index);\n if (_node) {\n const parentId = this.mirror.getId(_node.value.parentNode);\n const nextId = getNextId(_node.value);\n if (parentId !== -1 && nextId !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts\n .map((text) => ({\n id: this.mirror.getId(text.node),\n value: text.value,\n }))\n .filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes\n .map((attribute) => ({\n id: this.mirror.getId(attribute.node),\n attributes: attribute.attributes,\n }))\n .filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds,\n };\n if (!payload.texts.length &&\n !payload.attributes.length &&\n !payload.removes.length &&\n !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.removes = [];\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n };\n this.processMutation = (m) => {\n if (isIgnored(m.target)) {\n return;\n }\n switch (m.type) {\n case 'characterData': {\n const value = m.target.textContent;\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextSelector, this.maskAllText) && value\n ? this.maskTextFn\n ? this.maskTextFn(value)\n : value.replace(/[\\S]/g, '*')\n : value,\n node: m.target,\n });\n }\n break;\n }\n case 'attributes': {\n const target = m.target;\n let value = target.getAttribute(m.attributeName);\n if (m.attributeName === 'value') {\n value = maskInputValue({\n input: target,\n maskInputSelector: this.maskInputSelector,\n unmaskInputSelector: this.unmaskInputSelector,\n maskInputOptions: this.maskInputOptions,\n tagName: target.tagName,\n type: target.getAttribute('type'),\n value,\n maskInputFn: this.maskInputFn,\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) || value === m.oldValue) {\n return;\n }\n let item = this.attributes.find((a) => a.node === m.target);\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n };\n this.attributes.push(item);\n }\n if (m.attributeName === 'type' &&\n target.tagName === 'INPUT' &&\n (m.oldValue || '').toLowerCase() === 'password') {\n target.setAttribute('data-rr-is-password', 'true');\n }\n if (m.attributeName === 'style') {\n const old = this.doc.createElement('span');\n if (m.oldValue) {\n old.setAttribute('style', m.oldValue);\n }\n if (item.attributes.style === undefined ||\n item.attributes.style === null) {\n item.attributes.style = {};\n }\n try {\n const styleObj = item.attributes.style;\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) ||\n newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === '') {\n styleObj[pname] = newValue;\n }\n else {\n styleObj[pname] = [newValue, newPriority];\n }\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === '') {\n styleObj[pname] = false;\n }\n }\n }\n catch (error) {\n console.warn('[rrweb] Error when parsing update to style attribute:', error);\n }\n }\n else {\n const element = m.target;\n item.attributes[m.attributeName] = transformAttribute(this.doc, element, element.tagName, m.attributeName, value, this.maskAllText, this.unmaskTextSelector, this.maskTextFn);\n }\n break;\n }\n case 'childList': {\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target)\n ? this.mirror.getId(m.target.host)\n : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) || isIgnored(n)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n }\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) &&\n this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n }\n else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) ? true : undefined,\n });\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n };\n this.genAdds = (n, target) => {\n if (target && isBlocked(target, this.blockClass, this.blockSelector, this.unblockSelector)) {\n return;\n }\n if (isINode(n)) {\n if (isIgnored(n)) {\n return;\n }\n this.movedSet.add(n);\n let targetId = null;\n if (target && isINode(target)) {\n targetId = target.__sn.id;\n }\n if (targetId) {\n this.movedMap[moveKey(n.__sn.id, targetId)] = true;\n }\n }\n else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector))\n n.childNodes.forEach((childN) => this.genAdds(childN));\n };\n }\n init(options) {\n [\n 'mutationCb',\n 'blockClass',\n 'blockSelector',\n 'unblockSelector',\n 'maskTextClass',\n 'maskTextSelector',\n 'unmaskTextSelector',\n 'maskInputSelector',\n 'unmaskInputSelector',\n 'inlineStylesheet',\n 'maskAllText',\n 'maskInputOptions',\n 'maskTextFn',\n 'maskInputFn',\n 'recordCanvas',\n 'inlineImages',\n 'slimDOMOptions',\n 'doc',\n 'mirror',\n 'iframeManager',\n 'shadowDomManager',\n 'canvasManager',\n ].forEach((key) => {\n this[key] = options[key];\n });\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n }\n}\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction isParentRemoved(removes, n, mirror) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n const parentId = mirror.getId(parentNode);\n if (removes.some((r) => r.id === parentId)) {\n return true;\n }\n return isParentRemoved(removes, parentNode, mirror);\n}\nfunction isAncestorInSet(set, n) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return isAncestorInSet(set, parentNode);\n}\n\nexport { MutationBuffer as default };\n","const callbackWrapper = (cb) => {\n const rrwebWrapped = (...rest) => {\n try {\n return cb(...rest);\n }\n catch (error) {\n try {\n error.__rrweb__ = true;\n }\n catch (_a) {\n }\n throw error;\n }\n };\n return rrwebWrapped;\n};\n\nexport { callbackWrapper };\n","import { getInputType, getInputValue, hasInputMaskOptions, maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isBlocked, hookSetter, patch, isTouchEvent, getWindowHeight, getWindowWidth } from '../utils.js';\nimport { MouseInteractions, IncrementalSource } from '../types.js';\nimport MutationBuffer from './mutation.js';\nimport { callbackWrapper } from '../sentry/callbackWrapper.js';\n\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if ('composedPath' in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n }\n else if ('path' in event && event.path.length) {\n return event.path[0];\n }\n }\n catch (_a) { }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n var _a, _b;\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n let mutationObserverCtor = window.MutationObserver ||\n window.__rrMutationObserver;\n const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');\n if (angularZoneSymbol &&\n window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\n if (options.onMutation && options.onMutation(mutations) === false) {\n return;\n }\n mutationBuffer.processMutations(mutations);\n }));\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n });\n return observer;\n}\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\n if (sampling.mousemove === false) {\n return () => { };\n }\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\n ? sampling.mousemoveCallback\n : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle((source) => {\n const totalOffset = Date.now() - timeBaseline;\n callbackWrapper(mousemoveCb)(positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }), source);\n positions = [];\n timeBaseline = null;\n }, callbackThreshold);\n const updatePosition = throttle((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = isTouchEvent(evt)\n ? evt.changedTouches[0]\n : evt;\n if (!timeBaseline) {\n timeBaseline = Date.now();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror.getId(target),\n timeOffset: Date.now() - timeBaseline,\n });\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n ? IncrementalSource.Drag\n : evt instanceof MouseEvent\n ? IncrementalSource.MouseMove\n : IncrementalSource.TouchMove);\n }, threshold, {\n trailing: false,\n });\n const handlers = [\n on('mousemove', callbackWrapper(updatePosition), doc),\n on('touchmove', callbackWrapper(updatePosition), doc),\n on('drag', callbackWrapper(updatePosition), doc),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n if (sampling.mouseInteraction === false) {\n return () => { };\n }\n const disableMap = sampling.mouseInteraction === true ||\n sampling.mouseInteraction === undefined\n ? {}\n : sampling.mouseInteraction;\n const handlers = [];\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const e = isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror.getId(target);\n const { clientX, clientY } = e;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[eventKey],\n id,\n x: clientX,\n y: clientY,\n });\n };\n };\n Object.keys(MouseInteractions)\n .filter((key) => Number.isNaN(Number(key)) &&\n !key.endsWith('_Departed') &&\n disableMap[key] !== false)\n .forEach((eventKey) => {\n const eventName = eventKey.toLowerCase();\n const handler = callbackWrapper(getHandler(eventKey));\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n const updatePosition = throttle((evt) => {\n const target = getEventTarget(evt);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const id = mirror.getId(target);\n if (target === doc) {\n const scrollEl = (doc.scrollingElement || doc.documentElement);\n callbackWrapper(scrollCb)({\n id,\n x: scrollEl.scrollLeft,\n y: scrollEl.scrollTop,\n });\n }\n else {\n callbackWrapper(scrollCb)({\n id,\n x: target.scrollLeft,\n y: target.scrollTop,\n });\n }\n }, sampling.scroll || 100);\n return on('scroll', callbackWrapper(updatePosition), doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb, }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = throttle(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n callbackWrapper(viewportResizeCb)({\n width: Number(width),\n height: Number(height),\n });\n lastH = height;\n lastW = width;\n }\n }, 200);\n return on('resize', callbackWrapper(updateDimension), window);\n}\nfunction wrapEventWithUserTriggeredFlag(v, enable) {\n const value = Object.assign({}, v);\n if (!enable)\n delete value.userTriggered;\n return value;\n}\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nconst lastInputValueMap = new WeakMap();\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputSelector, unmaskInputSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const tagName = target && target.tagName;\n const userTriggered = event.isTrusted;\n if (tagName === 'OPTION')\n target = target.parentElement;\n if (!target ||\n !tagName ||\n INPUT_TAGS.indexOf(tagName) < 0 ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const el = target;\n const type = getInputType(el);\n if (el.classList.contains(ignoreClass) ||\n (ignoreSelector && el.matches(ignoreSelector))) {\n return;\n }\n let text = getInputValue(el, tagName, type);\n let isChecked = false;\n if (type === 'radio' || type === 'checkbox') {\n isChecked = target.checked;\n }\n if (hasInputMaskOptions({\n maskInputOptions,\n maskInputSelector,\n tagName,\n type,\n })) {\n text = maskInputValue({\n input: el,\n maskInputOptions,\n maskInputSelector,\n unmaskInputSelector,\n tagName,\n type,\n value: text,\n maskInputFn,\n });\n }\n cbWithDedup(target, callbackWrapper(wrapEventWithUserTriggeredFlag)({ text, isChecked, userTriggered }, userTriggeredOnInput));\n const name = target.name;\n if (type === 'radio' && name && isChecked) {\n doc\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\n .forEach((el) => {\n if (el !== target) {\n const text = maskInputValue({\n input: el,\n maskInputOptions,\n maskInputSelector,\n unmaskInputSelector,\n tagName,\n type,\n value: getInputValue(el, tagName, type),\n maskInputFn,\n });\n cbWithDedup(el, callbackWrapper(wrapEventWithUserTriggeredFlag)({\n text,\n isChecked: !isChecked,\n userTriggered: false,\n }, userTriggeredOnInput));\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue ||\n lastInputValue.text !== v.text ||\n lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror.getId(target);\n inputCb(Object.assign(Object.assign({}, v), { id }));\n }\n }\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\n const propertyDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');\n const hookProperties = [\n [HTMLInputElement.prototype, 'value'],\n [HTMLInputElement.prototype, 'checked'],\n [HTMLSelectElement.prototype, 'value'],\n [HTMLTextAreaElement.prototype, 'value'],\n [HTMLSelectElement.prototype, 'selectedIndex'],\n [HTMLOptionElement.prototype, 'selected'],\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\n set() {\n callbackWrapper(eventHandler)({ target: this });\n },\n })));\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if ((hasNestedCSSRule('CSSGroupingRule') &&\n childRule.parentRule instanceof CSSGroupingRule) ||\n (hasNestedCSSRule('CSSMediaRule') &&\n childRule.parentRule instanceof CSSMediaRule) ||\n (hasNestedCSSRule('CSSSupportsRule') &&\n childRule.parentRule instanceof CSSSupportsRule) ||\n (hasNestedCSSRule('CSSConditionRule') &&\n childRule.parentRule instanceof CSSConditionRule)) {\n const rules = Array.from(childRule.parentRule.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n else {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => { };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const id = mirror.getId(thisArg.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n adds: [{ rule, index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const id = mirror.getId(thisArg.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n removes: [{ index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n }\n else {\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n insertRule: type.prototype.insertRule,\n deleteRule: type.prototype.deleteRule,\n };\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const id = mirror.getId(thisArg.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index || 0,\n ],\n },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const id = mirror.getId(thisArg.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index] },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror }, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n var _a, _b;\n const [property, value, priority] = argumentsList;\n const id = mirror.getId((_b = (_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id,\n set: {\n property,\n value,\n priority,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n var _a, _b;\n const [property] = argumentsList;\n const id = mirror.getId((_b = (_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id,\n remove: {\n property,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, }) {\n const handler = (type) => throttle(callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const { currentTime, volume, muted } = target;\n mediaInteractionCb({\n type,\n id: mirror.getId(target),\n currentTime,\n volume,\n muted,\n });\n }), sampling.media || 500);\n const handlers = [\n on('play', handler(0)),\n on('pause', handler(1)),\n on('seeked', handler(2)),\n on('volumechange', handler(3)),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => { };\n }\n const handlers = [];\n const fontMap = new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n const fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== 'string',\n descriptors,\n fontSource: typeof source === 'string'\n ? source\n :\n JSON.stringify(Array.from(new Uint8Array(source))),\n });\n return fontFace;\n };\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\n return function (fontFace) {\n setTimeout(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }, 0);\n return original.apply(this, [fontFace]);\n };\n });\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction mergeHooks(o, hooks) {\n const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, } = o;\n o.mutationCb = (...p) => {\n if (hooks.mutation) {\n hooks.mutation(...p);\n }\n mutationCb(...p);\n };\n o.mousemoveCb = (...p) => {\n if (hooks.mousemove) {\n hooks.mousemove(...p);\n }\n mousemoveCb(...p);\n };\n o.mouseInteractionCb = (...p) => {\n if (hooks.mouseInteraction) {\n hooks.mouseInteraction(...p);\n }\n mouseInteractionCb(...p);\n };\n o.scrollCb = (...p) => {\n if (hooks.scroll) {\n hooks.scroll(...p);\n }\n scrollCb(...p);\n };\n o.viewportResizeCb = (...p) => {\n if (hooks.viewportResize) {\n hooks.viewportResize(...p);\n }\n viewportResizeCb(...p);\n };\n o.inputCb = (...p) => {\n if (hooks.input) {\n hooks.input(...p);\n }\n inputCb(...p);\n };\n o.mediaInteractionCb = (...p) => {\n if (hooks.mediaInteaction) {\n hooks.mediaInteaction(...p);\n }\n mediaInteractionCb(...p);\n };\n o.styleSheetRuleCb = (...p) => {\n if (hooks.styleSheetRule) {\n hooks.styleSheetRule(...p);\n }\n styleSheetRuleCb(...p);\n };\n o.styleDeclarationCb = (...p) => {\n if (hooks.styleDeclaration) {\n hooks.styleDeclaration(...p);\n }\n styleDeclarationCb(...p);\n };\n o.canvasMutationCb = (...p) => {\n if (hooks.canvasMutation) {\n hooks.canvasMutation(...p);\n }\n canvasMutationCb(...p);\n };\n o.fontCb = (...p) => {\n if (hooks.font) {\n hooks.font(...p);\n }\n fontCb(...p);\n };\n}\nfunction initObservers(o, hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => { };\n }\n mergeHooks(o, hooks);\n const mutationObserver = initMutationObserver(o, o.doc);\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o);\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n const styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow,\n });\n const fontObserver = o.collectFonts ? initFontObserver(o) : () => { };\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n mutationObserver.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n try {\n styleSheetObserver();\n styleDeclarationObserver();\n }\n catch (e) {\n }\n fontObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== 'undefined';\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(typeof window[prop] !== 'undefined' &&\n window[prop].prototype &&\n 'insertRule' in window[prop].prototype &&\n 'deleteRule' in window[prop].prototype);\n}\n\nexport { INPUT_TAGS, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n","/*\n * base64-arraybuffer 1.0.2 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n","class IframeManager {\n constructor(options) {\n this.iframes = new WeakMap();\n this.mutationCb = options.mutationCb;\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n attachIframe(iframeEl, childSn) {\n var _a;\n this.mutationCb({\n adds: [\n {\n parentId: iframeEl.__sn.id,\n nextId: null,\n node: childSn,\n },\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true,\n });\n (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);\n }\n}\n\nexport { IframeManager };\n","import { initMutationObserver, initScrollObserver } from './observer.js';\nimport { patch } from '../utils.js';\n\nclass ShadowDomManager {\n constructor(options) {\n this.restorePatches = [];\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n const manager = this;\n this.restorePatches.push(patch(HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n const shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager.addShadowRoot(this.shadowRoot, this.ownerDocument);\n return shadowRoot;\n };\n }));\n }\n addShadowRoot(shadowRoot, doc) {\n initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);\n initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));\n }\n observeAttachShadow(iframeElement) {\n if (iframeElement.contentWindow) {\n const manager = this;\n this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n const shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);\n return shadowRoot;\n };\n }));\n }\n }\n reset() {\n this.restorePatches.forEach((restorePatch) => restorePatch());\n }\n}\n\nexport { ShadowDomManager };\n","import { encode } from './../../../../../../ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js';\n\nconst webGLVarMap = new Map();\nfunction variableListFor(ctx, ctor) {\n let contextMap = webGLVarMap.get(ctx);\n if (!contextMap) {\n contextMap = new Map();\n webGLVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n if (!value ||\n !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))\n return;\n const name = value.constructor.name;\n const list = variableListFor(ctx, name);\n let index = list.indexOf(value);\n if (index === -1) {\n index = list.length;\n list.push(value);\n }\n return index;\n};\nfunction serializeArg(value, win, ctx) {\n if (value instanceof Array) {\n return value.map((arg) => serializeArg(arg, win, ctx));\n }\n else if (value === null) {\n return value;\n }\n else if (value instanceof Float32Array ||\n value instanceof Float64Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Uint8Array ||\n value instanceof Uint16Array ||\n value instanceof Int16Array ||\n value instanceof Int8Array ||\n value instanceof Uint8ClampedArray) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [Object.values(value)],\n };\n }\n else if (value instanceof ArrayBuffer) {\n const name = value.constructor.name;\n const base64 = encode(value);\n return {\n rr_type: name,\n base64,\n };\n }\n else if (value instanceof DataView) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.buffer, win, ctx),\n value.byteOffset,\n value.byteLength,\n ],\n };\n }\n else if (value instanceof HTMLImageElement) {\n const name = value.constructor.name;\n const { src } = value;\n return {\n rr_type: name,\n src,\n };\n }\n else if (value instanceof ImageData) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [serializeArg(value.data, win, ctx), value.width, value.height],\n };\n }\n else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\n const name = value.constructor.name;\n const index = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name,\n index: index,\n };\n }\n return value;\n}\nconst serializeArgs = (args, win, ctx) => {\n return [...args].map((arg) => serializeArg(arg, win, ctx));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n const webGLConstructorNames = [\n 'WebGLActiveInfo',\n 'WebGLBuffer',\n 'WebGLFramebuffer',\n 'WebGLProgram',\n 'WebGLRenderbuffer',\n 'WebGLShader',\n 'WebGLShaderPrecisionFormat',\n 'WebGLTexture',\n 'WebGLUniformLocation',\n 'WebGLVertexArrayObject',\n 'WebGLVertexArrayObjectOES',\n ];\n const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');\n return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));\n};\n\nexport { isInstanceOfWebGLObject, saveWebGLVar, serializeArg, serializeArgs, variableListFor };\n","import { CanvasContext } from '../../../types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\nimport { saveWebGLVar, serializeArgs } from './serialize-args.js';\n\nfunction patchGLPrototype(prototype, type, cb, blockClass, unblockSelector, blockSelector, mirror, win) {\n const handlers = [];\n const props = Object.getOwnPropertyNames(prototype);\n for (const prop of props) {\n try {\n if (typeof prototype[prop] !== 'function') {\n continue;\n }\n const restoreHandler = patch(prototype, prop, function (original) {\n return function (...args) {\n const result = original.apply(this, args);\n saveWebGLVar(result, win, prototype);\n if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector)) {\n const id = mirror.getId(this.canvas);\n const recordArgs = serializeArgs([...args], win, prototype);\n const mutation = {\n type,\n property: prop,\n args: recordArgs,\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n const hookHandler = hookSetter(prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type,\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, unblockSelector, mirror) {\n const handlers = [];\n handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, unblockSelector, mirror, win));\n if (typeof win.WebGL2RenderingContext !== 'undefined') {\n handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, unblockSelector, mirror, win));\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nexport { initCanvasWebGLMutationObserver as default };\n","import { snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, on, createMirror, getWindowWidth, getWindowHeight, isIframeINode, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../types.js';\nimport { IframeManager } from './iframe-manager.js';\nimport { ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManager } from './observers/canvas/canvas-manager.js';\nimport { callbackWrapper } from '../sentry/callbackWrapper.js';\n\nfunction wrapEvent(e) {\n return Object.assign(Object.assign({}, e), { timestamp: Date.now() });\n}\nlet wrappedEmit;\nlet takeFullSnapshot;\nconst mirror = createMirror();\nfunction record(options = {}) {\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, maskInputSelector = null, unmaskTextSelector = null, unmaskInputSelector = null, inlineStylesheet = true, maskAllText = false, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, mousemoveWait, recordCanvas = false, userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, onMutation, } = options;\n if (!emit) {\n throw new Error('emit function is required');\n }\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\n sampling.mousemove = mousemoveWait;\n }\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n radio: true,\n checkbox: true,\n }\n : _maskInputOptions !== undefined\n ? _maskInputOptions\n : {};\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\n ? {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n headMetaAuthorship: _slimDOMOptions === 'all',\n headMetaDescKeywords: _slimDOMOptions === 'all',\n }\n : _slimDOMOptions\n ? _slimDOMOptions\n : {};\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (e, isCheckout) => {\n var _a;\n if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&\n e.type !== EventType.FullSnapshot &&\n !(e.type === EventType.IncrementalSnapshot &&\n e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n emit(eventProcessor(e), isCheckout);\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n }\n else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation &&\n e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms &&\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Mutation }, m),\n }));\n };\n const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Scroll }, p),\n }));\n const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),\n }));\n const iframeManager = new IframeManager({\n mutationCb: wrappedMutationEmit,\n });\n const canvasManager = new CanvasManager({\n recordCanvas,\n mutationCb: wrappedCanvasMutationEmit,\n win: window,\n blockClass,\n blockSelector,\n unblockSelector,\n mirror,\n });\n const shadowDomManager = new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n onMutation,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n inlineStylesheet,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n canvasManager,\n },\n mirror,\n });\n takeFullSnapshot = (isCheckout = false) => {\n var _a, _b, _c, _d;\n wrappedEmit(wrapEvent({\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight(),\n },\n }), isCheckout);\n mutationBuffers.forEach((buf) => buf.lock());\n const [node, idNodeMap] = snapshot(document, {\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n inlineStylesheet,\n maskAllText,\n maskAllInputs: maskInputOptions,\n maskTextFn,\n slimDOM: slimDOMOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n) => {\n if (isIframeINode(n)) {\n iframeManager.addIframe(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n shadowDomManager.observeAttachShadow(iframe);\n },\n keepIframeSrcFn,\n });\n if (!node) {\n return console.warn('Failed to snapshot the document');\n }\n mirror.map = idNodeMap;\n wrappedEmit(wrapEvent({\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: {\n left: window.pageXOffset !== undefined\n ? window.pageXOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||\n ((_b = (_a = document === null || document === void 0 ? void 0 : document.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollLeft) ||\n 0,\n top: window.pageYOffset !== undefined\n ? window.pageYOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||\n ((_d = (_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.parentElement) === null || _d === void 0 ? void 0 : _d.scrollTop) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollTop) ||\n 0,\n },\n },\n }));\n mutationBuffers.forEach((buf) => buf.unlock());\n };\n try {\n const handlers = [];\n handlers.push(on('DOMContentLoaded', () => {\n wrappedEmit(wrapEvent({\n type: EventType.DomContentLoaded,\n data: {},\n }));\n }));\n const observe = (doc) => {\n var _a;\n return callbackWrapper(initObservers)({\n onMutation,\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions,\n },\n })),\n mouseInteractionCb: (d) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),\n })),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.ViewportResize }, d),\n })),\n inputCb: (v) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Input }, v),\n })),\n mediaInteractionCb: (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),\n })),\n styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),\n })),\n styleDeclarationCb: (r) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),\n })),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Font }, p),\n })),\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskAllText,\n maskInputFn,\n maskTextFn,\n blockSelector,\n unblockSelector,\n slimDOMOptions,\n mirror,\n iframeManager,\n shadowDomManager,\n canvasManager,\n plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit(wrapEvent({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload,\n },\n })),\n }))) || [],\n }, hooks);\n };\n iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n }\n catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n };\n if (document.readyState === 'interactive' ||\n document.readyState === 'complete') {\n init();\n }\n else {\n handlers.push(on('load', () => {\n wrappedEmit(wrapEvent({\n type: EventType.Load,\n data: {},\n }));\n init();\n }, window));\n }\n return () => {\n handlers.forEach((h) => h());\n };\n }\n catch (error) {\n console.warn(error);\n }\n}\nrecord.addCustomEvent = (tag, payload) => {\n if (!wrappedEmit) {\n throw new Error('please add custom event after start recording');\n }\n wrappedEmit(wrapEvent({\n type: EventType.Custom,\n data: {\n tag,\n payload,\n },\n }));\n};\nrecord.freezePage = () => {\n mutationBuffers.forEach((buf) => buf.freeze());\n};\nrecord.takeFullSnapshot = (isCheckout) => {\n if (!takeFullSnapshot) {\n throw new Error('please take full snapshot after start recording');\n }\n takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\n\nexport { record as default };\n","import { __rest } from './../../../../../../ext/tslib/tslib.es6.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\n\nclass CanvasManager {\n reset() {\n this.pendingCanvasMutations.clear();\n this.resetObservers && this.resetObservers();\n }\n freeze() {\n this.frozen = true;\n }\n unfreeze() {\n this.frozen = false;\n }\n lock() {\n this.locked = true;\n }\n unlock() {\n this.locked = false;\n }\n constructor(options) {\n this.pendingCanvasMutations = new Map();\n this.rafStamps = { latestId: 0, invokeId: null };\n this.frozen = false;\n this.locked = false;\n this.processMutation = function (target, mutation) {\n const newFrame = this.rafStamps.invokeId &&\n this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n };\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n if (options.recordCanvas === true)\n this.initCanvasMutationObserver(options.win, options.blockClass, options.blockSelector, options.unblockSelector);\n }\n initCanvasMutationObserver(win, blockClass, unblockSelector, blockSelector) {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector);\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\n this.resetObservers = () => {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n };\n }\n startPendingCanvasMutationFlusher() {\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n startRAFTimestamping() {\n const setLatestRAFTimestamp = (timestamp) => {\n this.rafStamps.latestId = timestamp;\n requestAnimationFrame(setLatestRAFTimestamp);\n };\n requestAnimationFrame(setLatestRAFTimestamp);\n }\n flushPendingCanvasMutations() {\n this.pendingCanvasMutations.forEach((values, canvas) => {\n const id = this.mirror.getId(canvas);\n this.flushPendingCanvasMutationFor(canvas, id);\n });\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n flushPendingCanvasMutationFor(canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1)\n return;\n const values = valuesWithType.map((value) => {\n const rest = __rest(value, [\"type\"]);\n return rest;\n });\n const { type } = valuesWithType[0];\n this.mutationCb({ id, type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n }\n}\n\nexport { CanvasManager };\n","import { patch, isBlocked } from '../../../utils.js';\n\nfunction initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector) {\n const handlers = [];\n try {\n const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {\n return function (contextType, ...args) {\n if (!isBlocked(this, blockClass, blockSelector, unblockSelector)) {\n if (!('__context' in this))\n this.__context = contextType;\n }\n return original.apply(this, [contextType, ...args]);\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n console.error('failed to patch HTMLCanvasElement.prototype.getContext');\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nexport { initCanvasContextObserver as default };\n","import { CanvasContext } from '../../../types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\n\nfunction initCanvas2DMutationObserver(cb, win, blockClass, unblockSelector, blockSelector, mirror) {\n const handlers = [];\n const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);\n for (const prop of props2D) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {\n continue;\n }\n const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {\n return function (...args) {\n if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector)) {\n setTimeout(() => {\n const recordArgs = [...args];\n if (prop === 'drawImage') {\n if (recordArgs[0] &&\n recordArgs[0] instanceof HTMLCanvasElement) {\n const canvas = recordArgs[0];\n const ctx = canvas.getContext('2d');\n let imgd = ctx === null || ctx === void 0 ? void 0 : ctx.getImageData(0, 0, canvas.width, canvas.height);\n let pix = imgd === null || imgd === void 0 ? void 0 : imgd.data;\n recordArgs[0] = JSON.stringify(pix);\n }\n }\n cb(this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: recordArgs,\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nexport { initCanvas2DMutationObserver as default };\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\n\nexport { __rest };\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../../types';\n\n/**\n * Add a breadcrumb event to replay.\n */\nexport function addBreadcrumbEvent(replay: ReplayContainer, breadcrumb: Breadcrumb): void {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category as string)) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n void replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1_000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n","import type { INode } from '@sentry-internal/rrweb-snapshot';\n\nexport interface DomHandlerData {\n name: string;\n event: Node | { target: EventTarget };\n}\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nexport function getClickTargetNode(event: DomHandlerData['event'] | MouseEvent): Node | INode | null {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n const closestInteractive = target.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || target;\n}\n\n/** Get the event target node. */\nexport function getTargetNode(event: Node | { target: EventTarget | null }): Node | INode | null {\n if (isEventWithTarget(event)) {\n return event.target as Node | null;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event: unknown): event is { target: EventTarget | null } {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n","import { fill } from '@sentry/utils';\n\nimport { WINDOW } from '../../constants';\n\ntype WindowOpenHandler = () => void;\n\nlet handlers: undefined | WindowOpenHandler[];\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nexport function onWindowOpen(cb: WindowOpenHandler): () => void {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers as WindowOpenHandler[]).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen(): void {\n fill(WINDOW, 'open', function (originalWindowOpen: () => void): () => void {\n return function (...args: unknown[]): void {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n","import type { Breadcrumb } from '@sentry/types';\n\nimport { WINDOW } from '../constants';\nimport type { MultiClickFrame, ReplayClickDetector, ReplayContainer, SlowClickConfig, SlowClickFrame } from '../types';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClickTargetNode } from './util/domUtils';\nimport { onWindowOpen } from './util/onWindowOpen';\n\ntype ClickBreadcrumb = Breadcrumb & {\n timestamp: number;\n};\n\ninterface Click {\n timestamp: number;\n mutationAfter?: number;\n scrollAfter?: number;\n clickBreadcrumb: ClickBreadcrumb;\n clickCount: number;\n node: HTMLElement;\n}\n\n/** Handle a click. */\nexport function handleClick(clickDetector: ReplayClickDetector, clickBreadcrumb: Breadcrumb, node: HTMLElement): void {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nexport class ClickDetector implements ReplayClickDetector {\n // protected for testing\n protected _lastMutation = 0;\n protected _lastScroll = 0;\n\n private _clicks: Click[] = [];\n private _teardown: undefined | (() => void);\n\n private _multiClickTimeout: number;\n private _threshold: number;\n private _scollTimeout: number;\n private _timeout: number;\n private _ignoreSelector: string;\n\n private _replay: ReplayContainer;\n private _checkClickTimeout?: ReturnType;\n private _addBreadcrumbEvent: typeof addBreadcrumbEvent;\n\n public constructor(\n replay: ReplayContainer,\n slowClickConfig: SlowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._multiClickTimeout = slowClickConfig.multiClickTimeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n public addListeners(): void {\n const mutationHandler = (): void => {\n this._lastMutation = nowInSeconds();\n };\n\n const scrollHandler = (): void => {\n this._lastScroll = nowInSeconds();\n };\n\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n const clickHandler = (event: MouseEvent): void => {\n if (!event.target) {\n return;\n }\n\n const node = getClickTargetNode(event);\n if (node) {\n this._handleMultiClick(node as HTMLElement);\n }\n };\n\n const obs = new MutationObserver(mutationHandler);\n\n obs.observe(WINDOW.document.documentElement, {\n attributes: true,\n characterData: true,\n childList: true,\n subtree: true,\n });\n\n WINDOW.addEventListener('scroll', scrollHandler, { passive: true });\n WINDOW.addEventListener('click', clickHandler, { passive: true });\n\n this._teardown = () => {\n WINDOW.removeEventListener('scroll', scrollHandler);\n WINDOW.removeEventListener('click', clickHandler);\n cleanupWindowOpen();\n\n obs.disconnect();\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n public removeListeners(): void {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** Handle a click */\n public handleClick(breadcrumb: Breadcrumb, node: HTMLElement): void {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const click = this._getClick(node);\n\n if (click) {\n // this means a click on the same element was captured in the last 1s, so we consider this a multi click\n return;\n }\n\n const newClick: Click = {\n timestamp: breadcrumb.timestamp,\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Count multiple clicks on elements. */\n private _handleMultiClick(node: HTMLElement): void {\n const click = this._getClick(node);\n\n if (!click) {\n return;\n }\n\n click.clickCount++;\n }\n\n /** Try to get an existing click on the given element. */\n private _getClick(node: HTMLElement): Click | undefined {\n const now = nowInSeconds();\n\n // Find any click on the same element in the last second\n // If one exists, we consider this click as a double/triple/etc click\n return this._clicks.find(click => click.node === node && now - click.timestamp < this._multiClickTimeout);\n }\n\n /** Check the clicks that happened. */\n private _checkClicks(): void {\n const timedOutClicks: Click[] = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // If an action happens after the multi click threshold, we can skip waiting and handle the click right away\n const actionTime = click.scrollAfter || click.mutationAfter || 0;\n if (actionTime && actionTime >= this._multiClickTimeout) {\n timedOutClicks.push(click);\n return;\n }\n\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n this._generateBreadcrumbs(click);\n\n const pos = this._clicks.indexOf(click);\n if (pos !== -1) {\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n private _generateBreadcrumbs(click: Click): void {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb: SlowClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb: MultiClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n private _scheduleCheckClicks(): void {\n this._checkClickTimeout = setTimeout(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nexport function ignoreElement(node: HTMLElement, ignoreSelector: string): boolean {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is ClickBreadcrumb {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds(): number {\n return Date.now() / 1000;\n}\n","var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = n === null || n === void 0 ? void 0 : n.host;\n return Boolean(host && host.shadowRoot && host.shadowRoot === n);\n}\nfunction isInputTypeMasked({ maskInputOptions, tagName, type, }) {\n if (tagName.toLowerCase() === 'option') {\n tagName = 'select';\n }\n const actualType = typeof type === 'string' ? type.toLowerCase() : undefined;\n return (maskInputOptions[tagName.toLowerCase()] ||\n (actualType && maskInputOptions[actualType]) ||\n actualType === 'password' ||\n (tagName === 'input' && !type && maskInputOptions['text']));\n}\nfunction hasInputMaskOptions({ tagName, type, maskInputOptions, maskInputSelector, }) {\n return (maskInputSelector || isInputTypeMasked({ maskInputOptions, tagName, type }));\n}\nfunction maskInputValue({ input, maskInputSelector, unmaskInputSelector, maskInputOptions, tagName, type, value, maskInputFn, }) {\n let text = value || '';\n if (unmaskInputSelector && input.matches(unmaskInputSelector)) {\n return text;\n }\n if (input.hasAttribute('data-rr-is-password')) {\n type = 'password';\n }\n if (isInputTypeMasked({ maskInputOptions, tagName, type }) ||\n (maskInputSelector && input.matches(maskInputSelector))) {\n if (maskInputFn) {\n text = maskInputFn(text);\n }\n else {\n text = '*'.repeat(text.length);\n }\n }\n return text;\n}\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext('2d');\n if (!ctx)\n return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some((pixel) => pixel !== 0))\n return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute('data-rr-is-password')\n ? 'password'\n : type\n ? type.toLowerCase()\n : null;\n}\nfunction getInputValue(el, tagName, type) {\n typeof type === 'string' ? type.toLowerCase() : '';\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\n return el.getAttribute('value') || '';\n }\n return el.value;\n}\nfunction defineCustomElement(w, elementName) {\n try {\n if (!w.customElements.get(elementName)) {\n const CustomElement = w.HTMLElement;\n w.customElements.define(elementName, class extends CustomElement {\n });\n }\n }\n catch (_a) { }\n}\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\nconst IGNORED_NODE = -2;\nfunction defaultMaskFn(str) {\n return str ? str.replace(/[\\S]/g, '*') : '';\n}\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return 'form';\n }\n const processedTagName = element.tagName.toLowerCase().trim();\n if (tagNameRegex.test(processedTagName)) {\n return 'div';\n }\n return processedTagName;\n}\nfunction getCssRulesString(s) {\n try {\n const rules = s.rules || s.cssRules;\n return rules ? Array.from(rules).map(getCssRuleString).join('') : null;\n }\n catch (error) {\n return null;\n }\n}\nfunction getCssRuleString(rule) {\n let cssStringified = rule.cssText;\n if (isCSSImportRule(rule)) {\n try {\n cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;\n }\n catch (_a) {\n }\n }\n return validateStringifiedCssRule(cssStringified);\n}\nfunction validateStringifiedCssRule(cssStringified) {\n if (cssStringified.indexOf(':') > -1) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, '$1\\\\$2');\n }\n return cssStringified;\n}\nfunction isCSSImportRule(rule) {\n return 'styleSheet' in rule;\n}\nfunction stringifyStyleSheet(sheet) {\n return sheet.cssRules\n ? Array.from(sheet.cssRules)\n .map((rule) => rule.cssText ? validateStringifiedCssRule(rule.cssText) : '')\n .join('')\n : '';\n}\nfunction extractOrigin(url) {\n let origin = '';\n if (url.indexOf('//') > -1) {\n origin = url.split('/').slice(0, 3).join('/');\n }\n else {\n origin = url.split('/')[0];\n }\n origin = origin.split('?')[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst RELATIVE_PATH = /^(?!www\\.|(?:http|ftp)s?:\\/\\/|[A-Za-z]:\\\\|\\/\\/|#).*/;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || '';\n if (!filePath) {\n return origin;\n }\n if (!RELATIVE_PATH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === '/') {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split('/');\n const parts = filePath.split('/');\n stack.pop();\n for (const part of parts) {\n if (part === '.') {\n continue;\n }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\n });\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === '') {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars;\n let match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return '';\n }\n let output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === ',') {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n }\n else {\n let descriptorsStr = '';\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n let c = attributeValue.charAt(pos);\n if (c === '') {\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\n }\n else {\n if (c === ')') {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(', ');\n}\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === '') {\n return attributeValue;\n }\n const a = doc.createElement('a');\n a.href = attributeValue;\n return a.href;\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\n}\nfunction getHref() {\n const a = document.createElement('a');\n a.href = '';\n return a.href;\n}\nfunction transformAttribute(doc, element, _tagName, _name, value, maskAllText, unmaskTextSelector, maskTextFn) {\n if (!value) {\n return value;\n }\n const name = _name.toLowerCase();\n const tagName = _tagName.toLowerCase();\n if (name === 'src' || name === 'href') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset') {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style') {\n return absoluteToStylesheet(value, getHref());\n }\n else if (tagName === 'object' && name === 'data') {\n return absoluteToDoc(doc, value);\n }\n else if (maskAllText &&\n _shouldMaskAttribute(element, name, tagName, unmaskTextSelector)) {\n return maskTextFn ? maskTextFn(value) : defaultMaskFn(value);\n }\n return value;\n}\nfunction _shouldMaskAttribute(element, attribute, tagName, unmaskTextSelector) {\n if (unmaskTextSelector && element.matches(unmaskTextSelector)) {\n return false;\n }\n return (['placeholder', 'title', 'aria-label'].indexOf(attribute) > -1 ||\n (tagName === 'input' &&\n attribute === 'value' &&\n element.hasAttribute('type') &&\n ['submit', 'button'].indexOf(element.getAttribute('type').toLowerCase()) > -1));\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === 'string') {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < element.classList.length; eIndex++) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n return false;\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) {\n if (!node) {\n return false;\n }\n if (node.nodeType !== node.ELEMENT_NODE) {\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n }\n if (unmaskTextSelector) {\n if (node.matches(unmaskTextSelector) ||\n node.closest(unmaskTextSelector)) {\n return false;\n }\n }\n if (maskAllText) {\n return true;\n }\n if (typeof maskTextClass === 'string') {\n if (node.classList.contains(maskTextClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < node.classList.length; eIndex++) {\n const className = node.classList[eIndex];\n if (maskTextClass.test(className)) {\n return true;\n }\n }\n }\n if (maskTextSelector) {\n if (node.matches(maskTextSelector)) {\n return true;\n }\n }\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n }\n catch (error) {\n return;\n }\n if (readyState !== 'complete') {\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener('load', () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n iframeEl.src === '') {\n setTimeout(listener, 0);\n return;\n }\n iframeEl.addEventListener('load', listener);\n}\nfunction serializeNode(n, options) {\n var _a;\n const { doc, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, } = options;\n let rootId;\n if (doc.__sn) {\n const docId = doc.__sn.id;\n rootId = docId === 1 ? undefined : docId;\n }\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== 'CSS1Compat') {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode,\n rootId,\n };\n }\n else {\n return {\n type: NodeType.Document,\n childNodes: [],\n rootId,\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId,\n };\n case n.ELEMENT_NODE:\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n for (const { name, value } of Array.from(n.attributes)) {\n if (!skipAttribute(tagName, name)) {\n attributes[name] = transformAttribute(doc, n, tagName, name, value, maskAllText, unmaskTextSelector, maskTextFn);\n }\n }\n if (tagName === 'link' && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = getCssRulesString(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText ||\n n.textContent ||\n '').trim().length) {\n const cssText = getCssRulesString(n.sheet);\n if (cssText) {\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select' ||\n tagName === 'option') {\n const el = n;\n const type = getInputType(el);\n const value = getInputValue(el, tagName.toUpperCase(), type);\n const checked = n.checked;\n if (type !== 'submit' &&\n type !== 'button' &&\n value) {\n attributes.value = maskInputValue({\n input: el,\n type,\n tagName,\n value,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes.selected = true;\n }\n else {\n delete attributes.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n const blankCanvas = document.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === 'img' && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement('canvas');\n canvasCtx = canvasService.getContext('2d');\n }\n const image = n;\n const oldValue = image.crossOrigin;\n image.crossOrigin = 'anonymous';\n const recordInlineImage = () => {\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n catch (err) {\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\n }\n oldValue\n ? (attributes.crossOrigin = oldValue)\n : delete attributes.crossOrigin;\n };\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.onload = recordInlineImage;\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes.rr_mediaCurrentTime = n.currentTime;\n }\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock,\n rootId,\n };\n case n.TEXT_NODE:\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\n textContent = stringifyStyleSheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref());\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n if (parentTagName === 'TEXTAREA' && textContent) {\n textContent = '';\n }\n else if (parentTagName === 'OPTION' && textContent) {\n const option = n.parentNode;\n textContent = maskInputValue({\n input: option,\n type: null,\n tagName: parentTagName,\n value: textContent,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n else if (!isStyle &&\n !isScript &&\n needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) &&\n textContent) {\n textContent = maskTextFn\n ? maskTextFn(textContent)\n : defaultMaskFn(textContent);\n }\n return {\n type: NodeType.Text,\n textContent: textContent || '',\n isStyle,\n rootId,\n };\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: '',\n rootId,\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: n.textContent || '',\n rootId,\n };\n default:\n return false;\n }\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined || maybeAttr === null) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n }\n else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n (sn.attributes.rel === 'preload' ||\n sn.attributes.rel === 'modulepreload') &&\n sn.attributes.as === 'script') ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n sn.attributes.href.endsWith('.js')))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const { doc, map, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, keepIframeSrcFn = () => false, } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n });\n if (!_serializedNode) {\n console.warn(n, 'not serialized');\n return null;\n }\n let id;\n if ('__sn' in n) {\n id = n.__sn.id;\n }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n n.__sn = serializedNode;\n if (id === IGNORED_NODE) {\n return null;\n }\n map[id] = n;\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n if (n.shadowRoot)\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document ||\n serializedNode.type === NodeType.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n _serializedNode.type === NodeType.Element &&\n _serializedNode.tagName === 'head') {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n };\n for (const childN of Array.from(n.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n) && n.shadowRoot) {\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedChildNode.isShadow = true;\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode && isShadowRoot(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(n, () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const { blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskInputSelector = null, unmaskInputSelector = null, maskAllText = false, maskAllInputs = false, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\n const idNodeMap = {};\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n }\n : maskAllInputs === false\n ? {}\n : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true,\n }\n : slimDOM === false\n ? {}\n : slimDOM;\n return [\n serializeNodeWithId(n, {\n doc: n,\n map: idNodeMap,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n }),\n idNodeMap,\n ];\n}\nfunction visitSnapshot(node, onVisit) {\n function walk(current) {\n onVisit(current);\n if (current.type === NodeType.Document ||\n current.type === NodeType.Element) {\n current.childNodes.forEach(walk);\n }\n }\n walk(node);\n}\nfunction cleanupSnapshot() {\n _id = 1;\n}\nfunction skipAttribute(tagName, attributeName, value) {\n return ((tagName === 'video' || tagName === 'audio') && attributeName === 'autoplay');\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\nfunction parse(css, options = {}) {\n let lineno = 1;\n let column = 1;\n function updatePosition(str) {\n const lines = str.match(/\\n/g);\n if (lines) {\n lineno += lines.length;\n }\n let i = str.lastIndexOf('\\n');\n column = i === -1 ? column + str.length : str.length - i;\n }\n function position() {\n const start = { line: lineno, column };\n return (node) => {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n class Position {\n constructor(start) {\n this.start = start;\n this.end = { line: lineno, column };\n this.source = options.source;\n }\n }\n Position.prototype.content = css;\n const errorsList = [];\n function error(msg) {\n const err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = css;\n if (options.silent) {\n errorsList.push(err);\n }\n else {\n throw err;\n }\n }\n function stylesheet() {\n const rulesList = rules();\n return {\n type: 'stylesheet',\n stylesheet: {\n source: options.source,\n rules: rulesList,\n parsingErrors: errorsList,\n },\n };\n }\n function open() {\n return match(/^{\\s*/);\n }\n function close() {\n return match(/^}/);\n }\n function rules() {\n let node;\n const rules = [];\n whitespace();\n comments(rules);\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\n if (node !== false) {\n rules.push(node);\n comments(rules);\n }\n }\n return rules;\n }\n function match(re) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n function whitespace() {\n match(/^\\s*/);\n }\n function comments(rules = []) {\n let c;\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n c = comment();\n }\n return rules;\n }\n function comment() {\n const pos = position();\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\n return;\n }\n let i = 2;\n while ('' !== css.charAt(i) &&\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\n ++i;\n }\n i += 2;\n if ('' === css.charAt(i - 1)) {\n return error('End of comment missing');\n }\n const str = css.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n css = css.slice(i);\n column += 2;\n return pos({\n type: 'comment',\n comment: str,\n });\n }\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n return trim(m[0])\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\n return m.replace(/,/g, '\\u200C');\n })\n .split(/\\s*(?![^(]*\\)),\\s*/)\n .map((s) => {\n return s.replace(/\\u200C/g, ',');\n });\n }\n function declaration() {\n const pos = position();\n let propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const prop = trim(propMatch[0]);\n if (!match(/^:\\s*/)) {\n return error(`property missing ':'`);\n }\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\n const ret = pos({\n type: 'declaration',\n property: prop.replace(commentre, ''),\n value: val ? trim(val[0]).replace(commentre, '') : '',\n });\n match(/^[;\\s]*/);\n return ret;\n }\n function declarations() {\n const decls = [];\n if (!open()) {\n return error(`missing '{'`);\n }\n comments(decls);\n let decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n decl = declaration();\n }\n if (!close()) {\n return error(`missing '}'`);\n }\n return decls;\n }\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n if (!vals.length) {\n return;\n }\n return pos({\n type: 'keyframe',\n values: vals,\n declarations: declarations(),\n });\n }\n function atkeyframes() {\n const pos = position();\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\n if (!m) {\n return;\n }\n const vendor = m[1];\n m = match(/^([-\\w]+)\\s*/);\n if (!m) {\n return error('@keyframes missing name');\n }\n const name = m[1];\n if (!open()) {\n return error(`@keyframes missing '{'`);\n }\n let frame;\n let frames = comments();\n while ((frame = keyframe())) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n if (!close()) {\n return error(`@keyframes missing '}'`);\n }\n return pos({\n type: 'keyframes',\n name,\n vendor,\n keyframes: frames,\n });\n }\n function atsupports() {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n if (!open()) {\n return error(`@supports missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@supports missing '}'`);\n }\n return pos({\n type: 'supports',\n supports,\n rules: style,\n });\n }\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@host missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@host missing '}'`);\n }\n return pos({\n type: 'host',\n rules: style,\n });\n }\n function atmedia() {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n if (!open()) {\n return error(`@media missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@media missing '}'`);\n }\n return pos({\n type: 'media',\n media,\n rules: style,\n });\n }\n function atcustommedia() {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n return pos({\n type: 'custom-media',\n name: trim(m[1]),\n media: trim(m[2]),\n });\n }\n function atpage() {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n const sel = selector() || [];\n if (!open()) {\n return error(`@page missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@page missing '}'`);\n }\n return pos({\n type: 'page',\n selectors: sel,\n declarations: decls,\n });\n }\n function atdocument() {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n if (!open()) {\n return error(`@document missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@document missing '}'`);\n }\n return pos({\n type: 'document',\n document: doc,\n vendor,\n rules: style,\n });\n }\n function atfontface() {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@font-face missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@font-face missing '}'`);\n }\n return pos({\n type: 'font-face',\n declarations: decls,\n });\n }\n const atimport = _compileAtrule('import');\n const atcharset = _compileAtrule('charset');\n const atnamespace = _compileAtrule('namespace');\n function _compileAtrule(name) {\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\n return () => {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret = { type: name };\n ret[name] = m[1].trim();\n return pos(ret);\n };\n }\n function atrule() {\n if (css[0] !== '@') {\n return;\n }\n return (atkeyframes() ||\n atmedia() ||\n atcustommedia() ||\n atsupports() ||\n atimport() ||\n atcharset() ||\n atnamespace() ||\n atdocument() ||\n atpage() ||\n athost() ||\n atfontface());\n }\n function rule() {\n const pos = position();\n const sel = selector();\n if (!sel) {\n return error('selector missing');\n }\n comments();\n return pos({\n type: 'rule',\n selectors: sel,\n declarations: declarations(),\n });\n }\n return addParent(stylesheet());\n}\nfunction trim(str) {\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\n}\nfunction addParent(obj, parent) {\n const isNode = obj && typeof obj.type === 'string';\n const childParent = isNode ? obj : parent;\n for (const k of Object.keys(obj)) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach((v) => {\n addParent(v, childParent);\n });\n }\n else if (value && typeof value === 'object') {\n addParent(value, childParent);\n }\n }\n if (isNode) {\n Object.defineProperty(obj, 'parent', {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null,\n });\n }\n return obj;\n}\n\nconst tagMap = {\n script: 'noscript',\n altglyph: 'altGlyph',\n altglyphdef: 'altGlyphDef',\n altglyphitem: 'altGlyphItem',\n animatecolor: 'animateColor',\n animatemotion: 'animateMotion',\n animatetransform: 'animateTransform',\n clippath: 'clipPath',\n feblend: 'feBlend',\n fecolormatrix: 'feColorMatrix',\n fecomponenttransfer: 'feComponentTransfer',\n fecomposite: 'feComposite',\n feconvolvematrix: 'feConvolveMatrix',\n fediffuselighting: 'feDiffuseLighting',\n fedisplacementmap: 'feDisplacementMap',\n fedistantlight: 'feDistantLight',\n fedropshadow: 'feDropShadow',\n feflood: 'feFlood',\n fefunca: 'feFuncA',\n fefuncb: 'feFuncB',\n fefuncg: 'feFuncG',\n fefuncr: 'feFuncR',\n fegaussianblur: 'feGaussianBlur',\n feimage: 'feImage',\n femerge: 'feMerge',\n femergenode: 'feMergeNode',\n femorphology: 'feMorphology',\n feoffset: 'feOffset',\n fepointlight: 'fePointLight',\n fespecularlighting: 'feSpecularLighting',\n fespotlight: 'feSpotLight',\n fetile: 'feTile',\n feturbulence: 'feTurbulence',\n foreignobject: 'foreignObject',\n glyphref: 'glyphRef',\n lineargradient: 'linearGradient',\n radialgradient: 'radialGradient',\n};\nfunction getTagName(n) {\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\n if (tagName === 'link' && n.attributes._cssText) {\n tagName = 'style';\n }\n return tagName;\n}\nfunction escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\nfunction addHoverClass(cssText, cache) {\n const cachedStyle = cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.get(cssText);\n if (cachedStyle)\n return cachedStyle;\n const ast = parse(cssText, {\n silent: true,\n });\n if (!ast.stylesheet) {\n return cssText;\n }\n const selectors = [];\n ast.stylesheet.rules.forEach((rule) => {\n if ('selectors' in rule) {\n (rule.selectors || []).forEach((selector) => {\n if (HOVER_SELECTOR.test(selector)) {\n selectors.push(selector);\n }\n });\n }\n });\n if (selectors.length === 0) {\n return cssText;\n }\n const selectorMatcher = new RegExp(selectors\n .filter((selector, index) => selectors.indexOf(selector) === index)\n .sort((a, b) => b.length - a.length)\n .map((selector) => {\n return escapeRegExp(selector);\n })\n .join('|'), 'g');\n const result = cssText.replace(selectorMatcher, (selector) => {\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\n return `${selector}, ${newSelector}`;\n });\n cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.set(cssText, result);\n return result;\n}\nfunction createCache() {\n const stylesWithHoverClass = new Map();\n return {\n stylesWithHoverClass,\n };\n}\nfunction buildNode(n, options) {\n const { doc, hackCss, cache } = options;\n switch (n.type) {\n case NodeType.Document:\n return doc.implementation.createDocument(null, '', null);\n case NodeType.DocumentType:\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\n case NodeType.Element:\n const tagName = getTagName(n);\n let node;\n if (n.isSVG) {\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\n }\n else {\n node = doc.createElement(tagName);\n }\n for (const name in n.attributes) {\n if (!n.attributes.hasOwnProperty(name)) {\n continue;\n }\n let value = n.attributes[name];\n if (tagName === 'option' && name === 'selected' && value === false) {\n continue;\n }\n value =\n typeof value === 'boolean' || typeof value === 'number' || value === null ? '' : value;\n if (!name.startsWith('rr_')) {\n const isTextarea = tagName === 'textarea' && name === 'value';\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\n if (isRemoteOrDynamicCss && hackCss) {\n value = addHoverClass(value, cache);\n }\n if (isTextarea || isRemoteOrDynamicCss) {\n const child = doc.createTextNode(value);\n for (const c of Array.from(node.childNodes)) {\n if (c.nodeType === node.TEXT_NODE) {\n node.removeChild(c);\n }\n }\n node.appendChild(child);\n continue;\n }\n try {\n if (n.isSVG && name === 'xlink:href') {\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value);\n }\n else if (name === 'onload' ||\n name === 'onclick' ||\n name.substring(0, 7) === 'onmouse') {\n node.setAttribute('_' + name, value);\n }\n else if (tagName === 'meta' &&\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\n name === 'content') {\n node.setAttribute('csp-content', value);\n continue;\n }\n else if (tagName === 'link' &&\n (n.attributes.rel === 'preload' || n.attributes.rel === 'modulepreload') &&\n n.attributes.as === 'script') {\n }\n else if (tagName === 'link' &&\n n.attributes.rel === 'prefetch' &&\n typeof n.attributes.href === 'string' &&\n n.attributes.href.endsWith('.js')) {\n }\n else if (tagName === 'img' &&\n n.attributes.srcset &&\n n.attributes.rr_dataURL) {\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\n }\n else {\n node.setAttribute(name, value);\n }\n }\n catch (error) {\n }\n }\n else {\n if (tagName === 'canvas' && name === 'rr_dataURL') {\n const image = document.createElement('img');\n image.src = value;\n image.onload = () => {\n const ctx = node.getContext('2d');\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n }\n else if (tagName === 'img' && name === 'rr_dataURL') {\n const image = node;\n if (!image.currentSrc.startsWith('data:')) {\n image.setAttribute('rrweb-original-src', n.attributes.src);\n image.src = value;\n }\n }\n if (name === 'rr_width') {\n node.style.width = value;\n }\n else if (name === 'rr_height') {\n node.style.height = value;\n }\n else if (name === 'rr_mediaCurrentTime') {\n node.currentTime = n.attributes\n .rr_mediaCurrentTime;\n }\n else if (name === 'rr_mediaState') {\n switch (value) {\n case 'played':\n node\n .play()\n .catch((e) => console.warn('media playback error', e));\n break;\n case 'paused':\n node.pause();\n break;\n }\n }\n }\n }\n if (n.isShadowHost) {\n if (!node.shadowRoot) {\n node.attachShadow({ mode: 'open' });\n if (doc.defaultView) {\n defineCustomElement(doc.defaultView, tagName);\n }\n }\n else {\n while (node.shadowRoot.firstChild) {\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\n }\n }\n }\n return node;\n case NodeType.Text:\n return doc.createTextNode(n.isStyle && hackCss\n ? addHoverClass(n.textContent, cache)\n : n.textContent);\n case NodeType.CDATA:\n return doc.createCDATASection(n.textContent);\n case NodeType.Comment:\n return doc.createComment(n.textContent);\n default:\n return null;\n }\n}\nfunction buildNodeWithSN(n, options) {\n const { doc, map, skipChild = false, hackCss = true, afterAppend, cache, } = options;\n let node = buildNode(n, { doc, hackCss, cache });\n if (!node) {\n return null;\n }\n if (n.rootId) {\n console.assert(map[n.rootId] === doc, 'Target document should has the same root id.');\n }\n if (n.type === NodeType.Document) {\n doc.close();\n doc.open();\n if (n.compatMode === 'BackCompat' &&\n n.childNodes &&\n n.childNodes[0].type !== NodeType.DocumentType) {\n if (n.childNodes[0].type === NodeType.Element &&\n 'xmlns' in n.childNodes[0].attributes &&\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\n doc.write('');\n }\n else {\n doc.write('');\n }\n }\n node = doc;\n }\n node.__sn = n;\n map[n.id] = node;\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\n !skipChild) {\n for (const childN of n.childNodes) {\n const childNode = buildNodeWithSN(childN, {\n doc,\n map,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n if (!childNode) {\n console.warn('Failed to rebuild', childN);\n continue;\n }\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\n node.shadowRoot.appendChild(childNode);\n }\n else {\n node.appendChild(childNode);\n }\n if (afterAppend) {\n afterAppend(childNode);\n }\n }\n }\n return node;\n}\nfunction visit(idNodeMap, onVisit) {\n function walk(node) {\n onVisit(node);\n }\n for (const key in idNodeMap) {\n if (idNodeMap[key]) {\n walk(idNodeMap[key]);\n }\n }\n}\nfunction handleScroll(node) {\n const n = node.__sn;\n if (n.type !== NodeType.Element) {\n return;\n }\n const el = node;\n for (const name in n.attributes) {\n if (!(n.attributes.hasOwnProperty(name) && name.startsWith('rr_'))) {\n continue;\n }\n const value = n.attributes[name];\n if (name === 'rr_scrollLeft') {\n el.scrollLeft = value;\n }\n if (name === 'rr_scrollTop') {\n el.scrollTop = value;\n }\n }\n}\nfunction rebuild(n, options) {\n const { doc, onVisit, hackCss = true, afterAppend, cache } = options;\n const idNodeMap = {};\n const node = buildNodeWithSN(n, {\n doc,\n map: idNodeMap,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n visit(idNodeMap, (visitedNode) => {\n if (onVisit) {\n onVisit(visitedNode);\n }\n handleScroll(visitedNode);\n });\n return [node, idNodeMap];\n}\n\nexport { IGNORED_NODE, NodeType, addHoverClass, buildNodeWithSN, cleanupSnapshot, createCache, defineCustomElement, getInputType, getInputValue, hasInputMaskOptions, is2DCanvasBlank, isElement, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, snapshot, transformAttribute, visitSnapshot };\n","import type { BreadcrumbFrame } from '../types/replayFrame';\n\n/**\n * Create a breadcrumb for a replay.\n */\nexport function createBreadcrumb(\n breadcrumb: Omit & Partial>,\n): BreadcrumbFrame {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n","// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nexport function getAttributesToRecord(attributes: Record): Record {\n const obj: Record = {};\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n","import type { INode } from '@sentry-internal/rrweb-snapshot';\nimport { NodeType } from '@sentry-internal/rrweb-snapshot';\nimport type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { handleClick } from './handleClick';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport type { DomHandlerData } from './util/domUtils';\nimport { getClickTargetNode, getTargetNode } from './util/domUtils';\nimport { getAttributesToRecord } from './util/getAttributesToRecord';\n\nexport const handleDomListener: (replay: ReplayContainer) => (handlerData: DomHandlerData) => void = (\n replay: ReplayContainer,\n) => {\n return (handlerData: DomHandlerData): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick && (handlerData.event as PointerEvent);\n // Ignore clicks if ctrl/alt/meta keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (isClick && replay.clickDetector && event && !event.altKey && !event.metaKey && !event.ctrlKey) {\n handleClick(\n replay.clickDetector,\n result as Breadcrumb & { timestamp: number; data: { nodeId: number } },\n getClickTargetNode(handlerData.event) as HTMLElement,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nexport function getBaseDomBreadcrumb(target: Node | INode | null, message: string): Breadcrumb {\n // `__sn` property is the serialized node created by rrweb\n const serializedNode = target && isRrwebNode(target) && target.__sn.type === NodeType.Element ? target.__sn : null;\n\n return {\n message,\n data: serializedNode\n ? {\n nodeId: serializedNode.id,\n node: {\n id: serializedNode.id,\n tagName: serializedNode.tagName,\n textContent: target\n ? Array.from(target.childNodes)\n .map(\n (node: Node | INode) => '__sn' in node && node.__sn.type === NodeType.Text && node.__sn.textContent,\n )\n .filter(Boolean) // filter out empty values\n .map(text => (text as string).trim())\n .join('')\n : '',\n attributes: getAttributesToRecord(serializedNode.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nexport function handleDom(handlerData: DomHandlerData): Breadcrumb | null {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData: DomHandlerData): { target: Node | INode | null; message: string } {\n const isClick = handlerData.name === 'click';\n\n let message: string | undefined;\n let target: Node | INode | null = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event) : getTargetNode(handlerData.event);\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isRrwebNode(node: EventTarget): node is INode {\n return '__sn' in node;\n}\n","import type { PerformanceNavigationTiming, PerformancePaintTiming } from '../types';\n\nconst NAVIGATION_ENTRY_KEYS: Array = [\n 'name',\n 'type',\n 'startTime',\n 'transferSize',\n 'duration',\n];\n\nfunction isNavigationEntryEqual(a: PerformanceNavigationTiming) {\n return function (b: PerformanceNavigationTiming) {\n return NAVIGATION_ENTRY_KEYS.every(key => a[key] === b[key]);\n };\n}\n\n/**\n * There are some difficulties diagnosing why there are duplicate navigation\n * entries. We've witnessed several intermittent results:\n * - duplicate entries have duration = 0\n * - duplicate entries are the same object reference\n * - none of the above\n *\n * Compare the values of several keys to determine if the entries are duplicates or not.\n */\n// TODO (high-prio): Figure out wth is returned here\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function dedupePerformanceEntries(\n currentList: PerformanceEntryList,\n newList: PerformanceEntryList,\n): PerformanceEntryList {\n // Partition `currentList` into 3 different lists based on entryType\n const [existingNavigationEntries, existingLcpEntries, existingEntries] = currentList.reduce(\n (acc: [PerformanceNavigationTiming[], PerformancePaintTiming[], PerformanceEntryList], entry) => {\n if (entry.entryType === 'navigation') {\n acc[0].push(entry as PerformanceNavigationTiming);\n } else if (entry.entryType === 'largest-contentful-paint') {\n acc[1].push(entry as PerformancePaintTiming);\n } else {\n acc[2].push(entry);\n }\n return acc;\n },\n [[], [], []],\n );\n\n const newEntries: PerformanceEntryList = [];\n const newNavigationEntries: PerformanceNavigationTiming[] = [];\n let newLcpEntry: PerformancePaintTiming | undefined = existingLcpEntries.length\n ? existingLcpEntries[existingLcpEntries.length - 1] // Take the last element as list is sorted\n : undefined;\n\n newList.forEach(entry => {\n if (entry.entryType === 'largest-contentful-paint') {\n // We want the latest LCP event only\n if (!newLcpEntry || newLcpEntry.startTime < entry.startTime) {\n newLcpEntry = entry;\n }\n return;\n }\n\n if (entry.entryType === 'navigation') {\n const navigationEntry = entry as PerformanceNavigationTiming;\n\n // Check if the navigation entry is contained in currentList or newList\n if (\n // Ignore any navigation entries with duration 0, as they are likely duplicates\n entry.duration > 0 &&\n // Ensure new entry does not already exist in existing entries\n !existingNavigationEntries.find(isNavigationEntryEqual(navigationEntry)) &&\n // Ensure new entry does not already exist in new list of navigation entries\n !newNavigationEntries.find(isNavigationEntryEqual(navigationEntry))\n ) {\n newNavigationEntries.push(navigationEntry);\n }\n\n // Otherwise this navigation entry is considered a duplicate and is thrown away\n return;\n }\n\n newEntries.push(entry);\n });\n\n // Re-combine and sort by startTime\n return [\n ...(newLcpEntry ? [newLcpEntry] : []),\n ...existingNavigationEntries,\n ...existingEntries,\n ...newEntries,\n ...newNavigationEntries,\n ].sort((a, b) => a.startTime - b.startTime);\n}\n","/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nexport function timestampToMs(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestampToMs';\nimport { EventBufferSizeExceededError } from '.';\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nexport class EventBufferArray implements EventBuffer {\n /** All the events that are buffered to be sent. */\n public events: RecordingEvent[];\n private _totalSize = 0;\n\n public constructor() {\n this.events = [];\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'sync';\n }\n\n /** @inheritdoc */\n public destroy(): void {\n this.events = [];\n }\n\n /** @inheritdoc */\n public async addEvent(event: RecordingEvent): Promise {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n public finish(): Promise {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n public clear(): void {\n this.events = [];\n this._totalSize = 0;\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n","import { logger } from '@sentry/utils';\n\nimport type { WorkerRequest, WorkerResponse } from '../types';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class WorkerHandler {\n private _worker: Worker;\n private _id: number;\n private _ensureReadyPromise?: Promise;\n\n public constructor(worker: Worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }: MessageEvent) => {\n if ((data as WorkerResponse).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n public destroy(): void {\n __DEBUG_BUILD__ && logger.log('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n public postMessage(method: WorkerRequest['method'], arg?: WorkerRequest['arg']): Promise {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }: MessageEvent): void => {\n const response = data as WorkerResponse;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n __DEBUG_BUILD__ && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response as T);\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n private _getAndIncrementId(): number {\n return this._id++;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestampToMs';\nimport { EventBufferSizeExceededError } from '.';\nimport { WorkerHandler } from './WorkerHandler';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class EventBufferCompressionWorker implements EventBuffer {\n private _worker: WorkerHandler;\n private _earliestTimestamp: number | null;\n private _totalSize = 0;\n\n public constructor(worker: Worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n public destroy(): void {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n public addEvent(event: RecordingEvent): Promise {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n public finish(): Promise {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n public clear(): void {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n void this._worker.postMessage('clear');\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n private _sendEventToWorker(data: string): Promise {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n private async _finishRequest(): Promise {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferCompressionWorker } from './EventBufferCompressionWorker';\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nexport class EventBufferProxy implements EventBuffer {\n private _fallback: EventBufferArray;\n private _compression: EventBufferCompressionWorker;\n private _used: EventBuffer;\n private _ensureWorkerIsLoadedPromise: Promise;\n\n public constructor(worker: Worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return this._used.type;\n }\n\n /** @inheritDoc */\n public get hasEvents(): boolean {\n return this._used.hasEvents;\n }\n\n /** @inheritDoc */\n public destroy(): void {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n public clear(): void {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n public addEvent(event: RecordingEvent): Promise {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n public async finish(): Promise {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n public ensureWorkerIsLoaded(): Promise {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n private async _ensureWorkerIsLoaded(): Promise {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n __DEBUG_BUILD__ && logger.log('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n private async _switchToCompressionWorker(): Promise {\n const { events } = this._fallback;\n\n const addEventPromises: Promise[] = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n __DEBUG_BUILD__ && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n","import { getWorkerURL } from '@sentry-internal/replay-worker';\nimport { logger } from '@sentry/utils';\n\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { EventBuffer } from '../types';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferProxy } from './EventBufferProxy';\n\ninterface CreateEventBufferParams {\n useCompression: boolean;\n}\n\n/**\n * Create an event buffer for replays.\n */\nexport function createEventBuffer({ useCompression }: CreateEventBufferParams): EventBuffer {\n // eslint-disable-next-line no-restricted-globals\n if (useCompression && window.Worker) {\n try {\n const workerUrl = getWorkerURL();\n\n __DEBUG_BUILD__ && logger.log('[Replay] Using compression worker');\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n __DEBUG_BUILD__ && logger.log('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n }\n\n __DEBUG_BUILD__ && logger.log('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nexport class EventBufferSizeExceededError extends Error {\n public constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n","/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nexport function isExpired(\n initialTime: null | number,\n expiry: undefined | number,\n targetTime: number = +new Date(),\n): boolean {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n","import type { Session, Timeouts } from '../types';\nimport { isExpired } from './isExpired';\n\n/**\n * Checks to see if session is expired\n */\nexport function isSessionExpired(session: Session, timeouts: Timeouts, targetTime: number = +new Date()): boolean {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, timeouts.maxSessionLife, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, timeouts.sessionIdleExpire, targetTime)\n );\n}\n","/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nexport function isSampled(sampleRate?: number): boolean {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\n\n/**\n * Save a session to session storage.\n */\nexport function saveSession(session: Session): void {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n if (!hasSessionStorage) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import { uuid4 } from '@sentry/utils';\n\nimport type { Sampled, Session } from '../types';\n\n/**\n * Get a session with defaults & applied sampling.\n */\nexport function makeSession(session: Partial & { sampled: Sampled }): Session {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n shouldRefresh: true,\n };\n}\n","import { logger } from '@sentry/utils';\n\nimport type { Sampled, Session, SessionOptions } from '../types';\nimport { isSampled } from '../util/isSampled';\nimport { saveSession } from './saveSession';\nimport { makeSession } from './Session';\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nexport function getSessionSampleType(sessionSampleRate: number, allowBuffering: boolean): Sampled {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nexport function createSession({ sessionSampleRate, allowBuffering, stickySession = false }: SessionOptions): Session {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n });\n\n __DEBUG_BUILD__ && logger.log(`[Replay] Creating new session: ${session.id}`);\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n","import { logger } from '@sentry/utils';\n\nimport type { Session, SessionOptions, Timeouts } from '../types';\nimport { isSessionExpired } from '../util/isSessionExpired';\nimport { createSession } from './createSession';\nimport { fetchSession } from './fetchSession';\nimport { makeSession } from './Session';\n\ninterface GetSessionParams extends SessionOptions {\n timeouts: Timeouts;\n\n /**\n * The current session (e.g. if stickySession is off)\n */\n currentSession?: Session;\n}\n\n/**\n * Get or create a session\n */\nexport function getSession({\n timeouts,\n currentSession,\n stickySession,\n sessionSampleRate,\n allowBuffering,\n}: GetSessionParams): { type: 'new' | 'saved'; session: Session } {\n // If session exists and is passed, use it instead of always hitting session storage\n const session = currentSession || (stickySession && fetchSession());\n\n if (session) {\n // If there is a session, check if it is valid (e.g. \"last activity\" time\n // should be within the \"session idle time\", and \"session started\" time is\n // within \"max session time\").\n const isExpired = isSessionExpired(session, timeouts);\n\n if (!isExpired || (allowBuffering && session.shouldRefresh)) {\n return { type: 'saved', session };\n } else if (!session.shouldRefresh) {\n // This is the case if we have an error session that is completed\n // (=triggered an error). Session will continue as session-based replay,\n // and when this session is expired, it will not be renewed until user\n // reloads.\n const discardedSession = makeSession({ sampled: false });\n return { type: 'new', session: discardedSession };\n } else {\n __DEBUG_BUILD__ && logger.log('[Replay] Session has expired');\n }\n // Otherwise continue to create a new session\n }\n\n const newSession = createSession({\n stickySession,\n sessionSampleRate,\n allowBuffering,\n });\n\n return { type: 'new', session: newSession };\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { makeSession } from './Session';\n\n/**\n * Fetches a session from storage\n */\nexport function fetchSession(): Session | null {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n\n if (!hasSessionStorage) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) as Session;\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { getCurrentHub } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { EventBufferSizeExceededError } from '../eventBuffer';\nimport type { AddEventResult, RecordingEvent, ReplayContainer, ReplayFrameEvent } from '../types';\nimport { timestampToMs } from './timestampToMs';\n\nfunction isCustomEvent(event: RecordingEvent): event is ReplayFrameEvent {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport async function addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!replay.eventBuffer) {\n // This implies that `_isEnabled` is false\n return null;\n }\n\n if (replay.isPaused()) {\n // Do not add to event buffer when recording is paused\n return null;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return null;\n }\n\n try {\n if (isCheckout) {\n replay.eventBuffer.clear();\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback =\n typeof replayOptions.beforeAddRecordingEvent === 'function' && isCustomEvent(event)\n ? replayOptions.beforeAddRecordingEvent(event)\n : event;\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await replay.eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const reason = error && error instanceof EventBufferSizeExceededError ? 'addEventSizeExceeded' : 'addEvent';\n\n __DEBUG_BUILD__ && logger.error(error);\n await replay.stop(reason);\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n","import type { ErrorEvent, Event, ReplayEvent, TransactionEvent } from '@sentry/types';\n\n/** If the event is an error event */\nexport function isErrorEvent(event: Event): event is ErrorEvent {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nexport function isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nexport function isReplayEvent(event: Event): event is ReplayEvent {\n return event.type === 'replay_event';\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { Event, Transport, TransportMakeRequestResponse } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isTransactionEvent } from '../util/eventUtils';\n\ntype AfterSendEventCallback = (event: Event, sendResponse: TransportMakeRequestResponse | void) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleAfterSendEvent(replay: ReplayContainer): AfterSendEventCallback {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event: Event, sendResponse: TransportMakeRequestResponse | void) => {\n if (!isErrorEvent(event) && !isTransactionEvent(event)) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n if (isTransactionEvent(event) && event.contexts && event.contexts.trace && event.contexts.trace.trace_id) {\n replay.getContext().traceIds.add(event.contexts.trace.trace_id as string);\n return;\n }\n\n // Everything below is just for error events\n if (!isErrorEvent(event)) {\n return;\n }\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n if (event.event_id) {\n replay.getContext().errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode === 'buffer' && event.tags && event.tags.replayId) {\n setTimeout(() => {\n // Capture current event buffer as new replay\n void replay.sendBufferedReplayOrFlush();\n });\n }\n };\n}\n\nfunction isBaseTransportSend(): boolean {\n const client = getCurrentHub().getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send as Transport['send'] & { __sentry__baseTransport__?: true }).__sentry__baseTransport__ || false\n );\n}\n","import { EventType } from '@sentry-internal/rrweb';\n\nimport type { AddEventResult, AllEntryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\n\n/**\n * Create a \"span\" for each performance entry.\n */\nexport function createPerformanceSpans(\n replay: ReplayContainer,\n entries: ReplayPerformanceEntry[],\n): Promise[] {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n","import type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../../types';\nimport { createPerformanceSpans } from '../../util/createPerformanceSpans';\nimport { shouldFilterRequest } from '../../util/shouldFilterRequest';\n\n/** Add a performance entry breadcrumb */\nexport function addNetworkBreadcrumb(\n replay: ReplayContainer,\n result: ReplayPerformanceEntry | null,\n): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n","import { getCurrentHub } from '@sentry/core';\n\nimport type { ReplayContainer } from '../types';\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nexport function shouldFilterRequest(replay: ReplayContainer, url: string): boolean {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (__DEBUG_BUILD__ && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return _isSentryRequest(url);\n}\n\n/**\n * Checks wether a given URL belongs to the configured Sentry DSN.\n */\nfunction _isSentryRequest(url: string): boolean {\n const client = getCurrentHub().getClient();\n const dsn = client && client.getDsn();\n return dsn ? url.includes(dsn.host) : false;\n}\n","export const OBJ = 10;\nexport const OBJ_KEY = 11;\nexport const OBJ_KEY_STR = 12;\nexport const OBJ_VAL = 13;\nexport const OBJ_VAL_STR = 14;\nexport const OBJ_VAL_COMPLETED = 15;\n\nexport const ARR = 20;\nexport const ARR_VAL = 21;\nexport const ARR_VAL_STR = 22;\nexport const ARR_VAL_COMPLETED = 23;\n\nexport type JsonToken =\n | typeof OBJ\n | typeof OBJ_KEY\n | typeof OBJ_KEY_STR\n | typeof OBJ_VAL\n | typeof OBJ_VAL_STR\n | typeof OBJ_VAL_COMPLETED\n | typeof ARR\n | typeof ARR_VAL\n | typeof ARR_VAL_STR\n | typeof ARR_VAL_COMPLETED;\n","import type { JsonToken } from './constants';\nimport {\n ARR,\n ARR_VAL,\n ARR_VAL_COMPLETED,\n ARR_VAL_STR,\n OBJ,\n OBJ_KEY,\n OBJ_KEY_STR,\n OBJ_VAL,\n OBJ_VAL_COMPLETED,\n OBJ_VAL_STR,\n} from './constants';\n\nconst ALLOWED_PRIMITIVES = ['true', 'false', 'null'];\n\n/**\n * Complete an incomplete JSON string.\n * This will ensure that the last element always has a `\"~~\"` to indicate it was truncated.\n * For example, `[1,2,` will be completed to `[1,2,\"~~\"]`\n * and `{\"aa\":\"b` will be completed to `{\"aa\":\"b~~\"}`\n */\nexport function completeJson(incompleteJson: string, stack: JsonToken[]): string {\n if (!stack.length) {\n return incompleteJson;\n }\n\n let json = incompleteJson;\n\n // Most checks are only needed for the last step in the stack\n const lastPos = stack.length - 1;\n const lastStep = stack[lastPos];\n\n json = _fixLastStep(json, lastStep);\n\n // Complete remaining steps - just add closing brackets\n for (let i = lastPos; i >= 0; i--) {\n const step = stack[i];\n\n switch (step) {\n case OBJ:\n json = `${json}}`;\n break;\n case ARR:\n json = `${json}]`;\n break;\n }\n }\n\n return json;\n}\n\nfunction _fixLastStep(json: string, lastStep: JsonToken): string {\n switch (lastStep) {\n // Object cases\n case OBJ:\n return `${json}\"~~\":\"~~\"`;\n case OBJ_KEY:\n return `${json}:\"~~\"`;\n case OBJ_KEY_STR:\n return `${json}~~\":\"~~\"`;\n case OBJ_VAL:\n return _maybeFixIncompleteObjValue(json);\n case OBJ_VAL_STR:\n return `${json}~~\"`;\n case OBJ_VAL_COMPLETED:\n return `${json},\"~~\":\"~~\"`;\n\n // Array cases\n case ARR:\n return `${json}\"~~\"`;\n case ARR_VAL:\n return _maybeFixIncompleteArrValue(json);\n case ARR_VAL_STR:\n return `${json}~~\"`;\n case ARR_VAL_COMPLETED:\n return `${json},\"~~\"`;\n }\n\n return json;\n}\n\nfunction _maybeFixIncompleteArrValue(json: string): string {\n const pos = _findLastArrayDelimiter(json);\n\n if (pos > -1) {\n const part = json.slice(pos + 1);\n\n if (ALLOWED_PRIMITIVES.includes(part.trim())) {\n return `${json},\"~~\"`;\n }\n\n // Everything else is replaced with `\"~~\"`\n return `${json.slice(0, pos + 1)}\"~~\"`;\n }\n\n // fallback, this shouldn't happen, to be save\n return json;\n}\n\nfunction _findLastArrayDelimiter(json: string): number {\n for (let i = json.length - 1; i >= 0; i--) {\n const char = json[i];\n\n if (char === ',' || char === '[') {\n return i;\n }\n }\n\n return -1;\n}\n\nfunction _maybeFixIncompleteObjValue(json: string): string {\n const startPos = json.lastIndexOf(':');\n\n const part = json.slice(startPos + 1);\n\n if (ALLOWED_PRIMITIVES.includes(part.trim())) {\n return `${json},\"~~\":\"~~\"`;\n }\n\n // Everything else is replaced with `\"~~\"`\n // This also means we do not have incomplete numbers, e.g `[1` is replaced with `[\"~~\"]`\n return `${json.slice(0, startPos + 1)}\"~~\"`;\n}\n","import type { JsonToken } from './constants';\nimport {\n ARR,\n ARR_VAL,\n ARR_VAL_COMPLETED,\n ARR_VAL_STR,\n OBJ,\n OBJ_KEY,\n OBJ_KEY_STR,\n OBJ_VAL,\n OBJ_VAL_COMPLETED,\n OBJ_VAL_STR,\n} from './constants';\n\n/**\n * Evaluate an (incomplete) JSON string.\n */\nexport function evaluateJson(json: string): JsonToken[] {\n const stack: JsonToken[] = [];\n\n for (let pos = 0; pos < json.length; pos++) {\n _evaluateJsonPos(stack, json, pos);\n }\n\n return stack;\n}\n\nfunction _evaluateJsonPos(stack: JsonToken[], json: string, pos: number): void {\n const curStep = stack[stack.length - 1];\n\n const char = json[pos];\n\n const whitespaceRegex = /\\s/;\n\n if (whitespaceRegex.test(char)) {\n return;\n }\n\n if (char === '\"' && !_isEscaped(json, pos)) {\n _handleQuote(stack, curStep);\n return;\n }\n\n switch (char) {\n case '{':\n _handleObj(stack, curStep);\n break;\n case '[':\n _handleArr(stack, curStep);\n break;\n case ':':\n _handleColon(stack, curStep);\n break;\n case ',':\n _handleComma(stack, curStep);\n break;\n case '}':\n _handleObjClose(stack, curStep);\n break;\n case ']':\n _handleArrClose(stack, curStep);\n break;\n }\n}\n\nfunction _handleQuote(stack: JsonToken[], curStep: JsonToken): void {\n // End of obj value\n if (curStep === OBJ_VAL_STR) {\n stack.pop();\n stack.push(OBJ_VAL_COMPLETED);\n return;\n }\n\n // End of arr value\n if (curStep === ARR_VAL_STR) {\n stack.pop();\n stack.push(ARR_VAL_COMPLETED);\n return;\n }\n\n // Start of obj value\n if (curStep === OBJ_VAL) {\n stack.push(OBJ_VAL_STR);\n return;\n }\n\n // Start of arr value\n if (curStep === ARR_VAL) {\n stack.push(ARR_VAL_STR);\n return;\n }\n\n // Start of obj key\n if (curStep === OBJ) {\n stack.push(OBJ_KEY_STR);\n return;\n }\n\n // End of obj key\n if (curStep === OBJ_KEY_STR) {\n stack.pop();\n stack.push(OBJ_KEY);\n return;\n }\n}\n\nfunction _handleObj(stack: JsonToken[], curStep: JsonToken): void {\n // Initial object\n if (!curStep) {\n stack.push(OBJ);\n return;\n }\n\n // New object as obj value\n if (curStep === OBJ_VAL) {\n stack.push(OBJ);\n return;\n }\n\n // New object as array element\n if (curStep === ARR_VAL) {\n stack.push(OBJ);\n }\n\n // New object as first array element\n if (curStep === ARR) {\n stack.push(OBJ);\n return;\n }\n}\n\nfunction _handleArr(stack: JsonToken[], curStep: JsonToken): void {\n // Initial array\n if (!curStep) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n\n // New array as obj value\n if (curStep === OBJ_VAL) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n\n // New array as array element\n if (curStep === ARR_VAL) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n }\n\n // New array as first array element\n if (curStep === ARR) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n}\n\nfunction _handleColon(stack: JsonToken[], curStep: JsonToken): void {\n if (curStep === OBJ_KEY) {\n stack.pop();\n stack.push(OBJ_VAL);\n }\n}\n\nfunction _handleComma(stack: JsonToken[], curStep: JsonToken): void {\n // Comma after obj value\n if (curStep === OBJ_VAL) {\n stack.pop();\n return;\n }\n if (curStep === OBJ_VAL_COMPLETED) {\n // Pop OBJ_VAL_COMPLETED & OBJ_VAL\n stack.pop();\n stack.pop();\n return;\n }\n\n // Comma after arr value\n if (curStep === ARR_VAL) {\n // do nothing - basically we'd pop ARR_VAL but add it right back\n return;\n }\n\n if (curStep === ARR_VAL_COMPLETED) {\n // Pop ARR_VAL_COMPLETED\n stack.pop();\n\n // basically we'd pop ARR_VAL but add it right back\n return;\n }\n}\n\nfunction _handleObjClose(stack: JsonToken[], curStep: JsonToken): void {\n // Empty object {}\n if (curStep === OBJ) {\n stack.pop();\n }\n\n // Object with element\n if (curStep === OBJ_VAL) {\n // Pop OBJ_VAL, OBJ\n stack.pop();\n stack.pop();\n }\n\n // Obj with element\n if (curStep === OBJ_VAL_COMPLETED) {\n // Pop OBJ_VAL_COMPLETED, OBJ_VAL, OBJ\n stack.pop();\n stack.pop();\n stack.pop();\n }\n\n // if was obj value, complete it\n if (stack[stack.length - 1] === OBJ_VAL) {\n stack.push(OBJ_VAL_COMPLETED);\n }\n\n // if was arr value, complete it\n if (stack[stack.length - 1] === ARR_VAL) {\n stack.push(ARR_VAL_COMPLETED);\n }\n}\n\nfunction _handleArrClose(stack: JsonToken[], curStep: JsonToken): void {\n // Empty array []\n if (curStep === ARR) {\n stack.pop();\n }\n\n // Array with element\n if (curStep === ARR_VAL) {\n // Pop ARR_VAL, ARR\n stack.pop();\n stack.pop();\n }\n\n // Array with element\n if (curStep === ARR_VAL_COMPLETED) {\n // Pop ARR_VAL_COMPLETED, ARR_VAL, ARR\n stack.pop();\n stack.pop();\n stack.pop();\n }\n\n // if was obj value, complete it\n if (stack[stack.length - 1] === OBJ_VAL) {\n stack.push(OBJ_VAL_COMPLETED);\n }\n\n // if was arr value, complete it\n if (stack[stack.length - 1] === ARR_VAL) {\n stack.push(ARR_VAL_COMPLETED);\n }\n}\n\nfunction _isEscaped(str: string, pos: number): boolean {\n const previousChar = str[pos - 1];\n\n return previousChar === '\\\\' && !_isEscaped(str, pos - 1);\n}\n","/* eslint-disable max-lines */\n\nimport { completeJson } from './completeJson';\nimport { evaluateJson } from './evaluateJson';\n\n/**\n * Takes an incomplete JSON string, and returns a hopefully valid JSON string.\n * Note that this _can_ fail, so you should check the return value is valid JSON.\n */\nexport function fixJson(incompleteJson: string): string {\n const stack = evaluateJson(incompleteJson);\n\n return completeJson(incompleteJson, stack);\n}\n","import type { TextEncoderInternal } from '@sentry/types';\nimport { dropUndefinedKeys, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { NETWORK_BODY_MAX_SIZE, WINDOW } from '../../constants';\nimport type {\n NetworkBody,\n NetworkMetaWarning,\n NetworkRequestData,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n ReplayPerformanceEntry,\n} from '../../types';\nimport { fixJson } from '../../util/truncateJson/fixJson';\n\n/** Get the size of a body. */\nexport function getBodySize(\n body: RequestInit['body'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nexport function parseContentLengthHeader(header: string | null | undefined): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nexport function getBodyString(body: unknown): string | undefined {\n if (typeof body === 'string') {\n return body;\n }\n\n if (body instanceof URLSearchParams) {\n return body.toString();\n }\n\n if (body instanceof FormData) {\n return _serializeFormData(body);\n }\n\n return undefined;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nexport function makeNetworkReplayBreadcrumb(\n type: string,\n data: ReplayNetworkRequestData | null,\n): ReplayPerformanceEntry | null {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result: ReplayPerformanceEntry = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Get either a JSON network body, or a text representation. */\nexport function getNetworkBody(bodyText: string | undefined): NetworkBody | undefined {\n if (!bodyText) {\n return;\n }\n\n try {\n return JSON.parse(bodyText);\n } catch {\n // return text\n }\n\n return bodyText;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nexport function buildSkippedNetworkRequestOrResponse(bodySize: number | undefined): ReplayNetworkRequestOrResponse {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nexport function buildNetworkRequestOrResponse(\n headers: Record,\n bodySize: number | undefined,\n body: string | undefined,\n): ReplayNetworkRequestOrResponse | undefined {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info: ReplayNetworkRequestOrResponse = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nexport function getAllowedHeaders(headers: Record, allowedHeaders: string[]): Record {\n return Object.keys(headers).reduce((filteredHeaders: Record, key: string) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData: FormData): string {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-ignore passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body: string | undefined): {\n body: NetworkBody | undefined;\n warnings: NetworkMetaWarning[];\n} {\n if (!body || typeof body !== 'string') {\n return {\n body,\n warnings: [],\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n\n if (_strIsProbablyJson(body)) {\n try {\n const json = exceedsSizeLimit ? fixJson(body.slice(0, NETWORK_BODY_MAX_SIZE)) : body;\n const normalizedBody = JSON.parse(json);\n return {\n body: normalizedBody,\n warnings: exceedsSizeLimit ? ['JSON_TRUNCATED'] : [],\n };\n } catch {\n return {\n body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,\n warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],\n };\n }\n }\n\n return {\n body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,\n warnings: exceedsSizeLimit ? ['TEXT_TRUNCATED'] : [],\n };\n}\n\nfunction _strIsProbablyJson(str: string): boolean {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nexport function urlMatches(url: string, urls: (string | RegExp)[]): boolean {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nexport function getFullUrl(url: string, baseURI = WINDOW.document.baseURI): string {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n","import type { Breadcrumb, FetchBreadcrumbData, TextEncoderInternal } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport type {\n FetchHint,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureFetchBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: FetchHint,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n replay: ReplayContainer;\n },\n): Promise {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n __DEBUG_BUILD__ && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichFetchBreadcrumb(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: FetchHint,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { input, response } = hint;\n\n const body = _getFetchRequestArgBody(input);\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: FetchHint,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n): Promise {\n const { startTimestamp, endTimestamp } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails = urlMatches(url, options.networkDetailAllowUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders }: ReplayNetworkOptions,\n input: FetchHint['input'],\n requestBodySize?: number,\n): ReplayNetworkRequestOrResponse | undefined {\n const headers = getRequestHeaders(input, networkRequestHeaders);\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const bodyStr = getBodyString(requestBody);\n return buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n}\n\nasync function _getResponseInfo(\n captureDetails: boolean,\n {\n networkCaptureBodies,\n textEncoder,\n networkResponseHeaders,\n }: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n response: Response,\n responseBodySize?: number,\n): Promise {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = getAllHeaders(response.headers, networkResponseHeaders);\n\n if (!networkCaptureBodies && responseBodySize !== undefined) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n // Only clone the response if we need to\n try {\n // We have to clone this, as the body can only be read once\n const res = response.clone();\n const bodyText = await _parseFetchBody(res);\n\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch {\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchBody(response: Response): Promise {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs: unknown[] = []): RequestInit['body'] | undefined {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] as RequestInit).body;\n}\n\nfunction getAllHeaders(headers: Headers, allowedHeaders: string[]): Record {\n const allHeaders: Record = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) as string;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs: unknown[], allowedHeaders: string[]): Record {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] as Request | RequestInit, allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] as Request | RequestInit, allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input: Request | RequestInit | undefined,\n allowedHeaders: string[],\n): Record {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n","import type { Breadcrumb, TextEncoderInternal, XhrBreadcrumbData } from '@sentry/types';\nimport { logger, SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { ReplayContainer, ReplayNetworkOptions, ReplayNetworkRequestData, XhrHint } from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureXhrBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: XhrHint,\n options: ReplayNetworkOptions & { replay: ReplayContainer },\n): Promise {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n __DEBUG_BUILD__ && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichXhrBreadcrumb(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: XhrHint,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { xhr, input } = hint;\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : getBodySize(xhr.response, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: XhrHint,\n options: ReplayNetworkOptions,\n): ReplayNetworkRequestData | null {\n const { startTimestamp, endTimestamp, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!urlMatches(url, options.networkDetailAllowUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const request = buildNetworkRequestOrResponse(\n networkRequestHeaders,\n requestBodySize,\n options.networkCaptureBodies ? getBodyString(input) : undefined,\n );\n const response = buildNetworkRequestOrResponse(\n networkResponseHeaders,\n responseBodySize,\n options.networkCaptureBodies ? hint.xhr.responseText : undefined,\n );\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction getResponseHeaders(xhr: XMLHttpRequest): Record {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record, line: string) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n FetchBreadcrumbData,\n TextEncoderInternal,\n XhrBreadcrumbData,\n} from '@sentry/types';\nimport { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport type { FetchHint, ReplayContainer, ReplayNetworkOptions, XhrHint } from '../types';\nimport { handleFetchSpanListener } from './handleFetch';\nimport { handleXhrSpanListener } from './handleXhr';\nimport { captureFetchBreadcrumbToReplay, enrichFetchBreadcrumb } from './util/fetchUtils';\nimport { captureXhrBreadcrumbToReplay, enrichXhrBreadcrumb } from './util/xhrUtils';\n\ninterface ExtendedNetworkBreadcrumbsOptions extends ReplayNetworkOptions {\n replay: ReplayContainer;\n textEncoder: TextEncoderInternal;\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nexport function handleNetworkBreadcrumbs(replay: ReplayContainer): void {\n const client = getCurrentHub().getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const { networkDetailAllowUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } =\n replay.getOptions();\n\n const options: ExtendedNetworkBreadcrumbsOptions = {\n replay,\n textEncoder,\n networkDetailAllowUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addInstrumentationHandler('fetch', handleFetchSpanListener(replay));\n addInstrumentationHandler('xhr', handleXhrSpanListener(replay));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nexport function beforeAddNetworkBreadcrumb(\n options: ExtendedNetworkBreadcrumbsOptions,\n breadcrumb: Breadcrumb,\n hint?: BreadcrumbHint,\n): void {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n void captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n void captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n __DEBUG_BUILD__ && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: XhrBreadcrumbData } {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: FetchBreadcrumbData } {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint?: BreadcrumbHint): hint is XhrHint {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint?: BreadcrumbHint): hint is FetchHint {\n return hint && hint.response;\n}\n","import type { HandlerDataFetch } from '@sentry/types';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleFetch(handlerData: HandlerDataFetch): null | ReplayPerformanceEntry {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response && (response as Response).status,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.\n */\nexport function handleFetchSpanListener(replay: ReplayContainer): (handlerData: HandlerDataFetch) => void {\n return (handlerData: HandlerDataFetch) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { HandlerDataXhr } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleXhr(handlerData: HandlerDataXhr): ReplayPerformanceEntry | null {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('xhr', listener)`.\n */\nexport function handleXhrSpanListener(replay: ReplayContainer): (handlerData: HandlerDataXhr) => void {\n return (handlerData: HandlerDataXhr) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { Breadcrumb, Scope } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport { CONSOLE_ARG_MAX_SIZE } from '../constants';\nimport type { ReplayContainer } from '../types';\nimport type { ReplayFrame } from '../types/replayFrame';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { fixJson } from '../util/truncateJson/fixJson';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\nlet _LAST_BREADCRUMB: null | Breadcrumb = null;\n\ntype BreadcrumbWithCategory = Required>;\n\nfunction isBreadcrumbWithCategory(breadcrumb: Breadcrumb): breadcrumb is BreadcrumbWithCategory {\n return !!breadcrumb.category;\n}\n\nexport const handleScopeListener: (replay: ReplayContainer) => (scope: Scope) => void =\n (replay: ReplayContainer) =>\n (scope: Scope): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nexport function handleScope(scope: Scope): Breadcrumb | null {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n !isBreadcrumbWithCategory(newBreadcrumb) ||\n ['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (newBreadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(newBreadcrumb);\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/** exported for tests only */\nexport function normalizeConsoleBreadcrumb(\n breadcrumb: Omit & BreadcrumbWithCategory,\n): ReplayFrame {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n const fixedJson = fixJson(stringified.slice(0, CONSOLE_ARG_MAX_SIZE));\n const json = JSON.parse(fixedJson);\n // We only set this after JSON.parse() was successfull, so we know we didn't run into `catch`\n isTruncated = true;\n return json;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n","import type { BaseClient } from '@sentry/core';\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Client, DynamicSamplingContext } from '@sentry/types';\nimport { addInstrumentationHandler } from '@sentry/utils';\n\nimport { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';\nimport { handleDomListener } from '../coreHandlers/handleDom';\nimport { handleGlobalEventListener } from '../coreHandlers/handleGlobalEvent';\nimport { handleHistorySpanListener } from '../coreHandlers/handleHistory';\nimport { handleNetworkBreadcrumbs } from '../coreHandlers/handleNetworkBreadcrumbs';\nimport { handleScopeListener } from '../coreHandlers/handleScope';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Add global listeners that cannot be removed.\n */\nexport function addGlobalListeners(replay: ReplayContainer): void {\n // Listeners from core SDK //\n const scope = getCurrentHub().getScope();\n const client = getCurrentHub().getClient();\n\n if (scope) {\n scope.addScopeListener(handleScopeListener(replay));\n }\n addInstrumentationHandler('dom', handleDomListener(replay));\n addInstrumentationHandler('history', handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n addGlobalEventProcessor(handleGlobalEventListener(replay, !hasHooks(client)));\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc: DynamicSamplingContext) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n dsc.replay_id = replayId;\n }\n });\n\n client.on('startTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We may be missing the initial startTransaction due to timing issues,\n // so we capture it on finish again.\n client.on('finishTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client: Client | undefined): client is BaseClient {\n return !!(client && client.on);\n}\n","import { WINDOW } from '../constants';\nimport type { AddEventResult, MemoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from './createPerformanceSpans';\n\ntype ReplayMemoryEntry = ReplayPerformanceEntry & { data: { memory: MemoryInfo } };\n\ninterface MemoryInfo {\n jsHeapSizeLimit: number;\n totalJSHeapSize: number;\n usedJSHeapSize: number;\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nexport async function addMemoryEntry(replay: ReplayContainer): Promise> {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-ignore memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry: MemoryInfo): ReplayMemoryEntry {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n","import { record } from '@sentry-internal/rrweb';\nimport { browserPerformanceTimeOrigin } from '@sentry/utils';\n\nimport { WINDOW } from '../constants';\nimport type {\n AllPerformanceEntry,\n AllPerformanceEntryData,\n ExperimentalPerformanceResourceTiming,\n LargestContentfulPaintData,\n NavigationData,\n PaintData,\n PerformanceNavigationTiming,\n PerformancePaintTiming,\n ReplayPerformanceEntry,\n ResourceData,\n} from '../types';\n\n// Map entryType -> function to normalize data for event\n// @ts-ignore TODO: entry type does not fit the create* functions entry type\nconst ENTRY_TYPES: Record<\n string,\n (entry: AllPerformanceEntry) => null | ReplayPerformanceEntry\n> = {\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n ['largest-contentful-paint']: createLargestContentfulPaint,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nexport function createPerformanceEntries(\n entries: AllPerformanceEntry[],\n): ReplayPerformanceEntry[] {\n return entries.map(createPerformanceEntry).filter(Boolean) as ReplayPerformanceEntry[];\n}\n\nfunction createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEntry | null {\n if (ENTRY_TYPES[entry.entryType] === undefined) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time: number): number {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry: PerformanceNavigationTiming): ReplayPerformanceEntry | null {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry: ExperimentalPerformanceResourceTiming,\n): ReplayPerformanceEntry | null {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\nfunction createLargestContentfulPaint(\n entry: PerformanceEntry & { size: number; element: Node },\n): ReplayPerformanceEntry {\n const { entryType, startTime, size } = entry;\n\n let startTimeOrNavigationActivation = 0;\n\n if (WINDOW.performance) {\n const navEntry = WINDOW.performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming & {\n activationStart: number;\n };\n\n // See https://github.com/GoogleChrome/web-vitals/blob/9f11c4c6578fb4c5ee6fa4e32b9d1d756475f135/src/lib/getActivationStart.ts#L21\n startTimeOrNavigationActivation = (navEntry && navEntry.activationStart) || 0;\n }\n\n // value is in ms\n const value = Math.max(startTime - startTimeOrNavigationActivation, 0);\n // LCP doesn't have a \"duration\", it just happens at a single point in time.\n // But the UI expects both, so use end (in seconds) for both timestamps.\n const end = getAbsoluteTime(startTimeOrNavigationActivation) + value / 1000;\n\n return {\n type: entryType,\n name: entryType,\n start: end,\n end,\n data: {\n value, // LCP \"duration\" in ms\n size,\n // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nodeId: record.mirror.getId(entry.element as any),\n },\n };\n}\n","import type { DsnComponents, ReplayEnvelope, ReplayEvent, ReplayRecordingData } from '@sentry/types';\nimport { createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader } from '@sentry/utils';\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nexport function createReplayEnvelope(\n replayEvent: ReplayEvent,\n recordingData: ReplayRecordingData,\n dsn: DsnComponents,\n tunnel?: string,\n): ReplayEnvelope {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\n/**\n * Prepare the recording data ready to be sent.\n */\nexport function prepareRecordingData({\n recordingData,\n headers,\n}: {\n recordingData: ReplayRecordingData;\n headers: Record;\n}): ReplayRecordingData {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n","import type { Scope } from '@sentry/core';\nimport { prepareEvent } from '@sentry/core';\nimport type { IntegrationIndex } from '@sentry/core/build/types/integration';\nimport type { Client, ReplayEvent } from '@sentry/types';\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nexport async function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}: {\n client: Client & { _integrations?: IntegrationIndex };\n scope: Scope;\n replayId: string;\n event: ReplayEvent;\n}): Promise {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n { event_id, integrations },\n scope,\n )) as ReplayEvent | null;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { ReplayEvent, TransportMakeRequestResponse } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { createReplayEnvelope } from './createReplayEnvelope';\nimport { prepareRecordingData } from './prepareRecordingData';\nimport { prepareReplayEvent } from './prepareReplayEvent';\n\n/**\n * Send replay attachment using `fetch()`\n */\nexport async function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}: SendReplayData): Promise {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const hub = getCurrentHub();\n const client = hub.getClient();\n const scope = hub.getScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !scope || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent: ReplayEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n __DEBUG_BUILD__ && logger.log('An event processor returned `null`, will not send event.');\n return;\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response: void | TransportMakeRequestResponse;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nexport class TransportStatusCodeError extends Error {\n public constructor(statusCode: number) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n","import { captureException, setContext } from '@sentry/core';\n\nimport { RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { sendReplayRequest, TransportStatusCodeError } from './sendReplayRequest';\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nexport async function sendReplay(\n replayData: SendReplayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n): Promise {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (__DEBUG_BUILD__ && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return await new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n","export const THROTTLED = '__THROTTLED';\nexport const SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle any>(\n fn: T,\n maxCount: number,\n durationSeconds: number,\n): (...rest: Parameters) => ReturnType | typeof THROTTLED | typeof SKIPPED {\n const counter = new Map();\n\n const _cleanup = (now: number): void => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = (): number => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest: Parameters): ReturnType | typeof THROTTLED | typeof SKIPPED => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n","/* eslint-disable max-lines */ // TODO: We might want to split this file up\nimport { EventType, record } from '@sentry-internal/rrweb';\nimport { captureException, getCurrentHub } from '@sentry/core';\nimport type { ReplayRecordingMode, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport {\n BUFFER_CHECKOUT_TIME,\n MAX_SESSION_LIFE,\n MULTI_CLICK_TIMEOUT,\n SESSION_IDLE_EXPIRE_DURATION,\n SESSION_IDLE_PAUSE_DURATION,\n SLOW_CLICK_SCROLL_TIMEOUT,\n SLOW_CLICK_THRESHOLD,\n WINDOW,\n} from './constants';\nimport { ClickDetector } from './coreHandlers/handleClick';\nimport { handleKeyboardEvent } from './coreHandlers/handleKeyboardEvent';\nimport { setupPerformanceObserver } from './coreHandlers/performanceObserver';\nimport { createEventBuffer } from './eventBuffer';\nimport { clearSession } from './session/clearSession';\nimport { getSession } from './session/getSession';\nimport { saveSession } from './session/saveSession';\nimport type {\n AddEventResult,\n AddUpdateCallback,\n AllPerformanceEntry,\n BreadcrumbFrame,\n EventBuffer,\n InternalEventContext,\n PopEventContext,\n RecordingEvent,\n RecordingOptions,\n ReplayContainer as ReplayContainerInterface,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n Session,\n SlowClickConfig,\n Timeouts,\n} from './types';\nimport { addEvent } from './util/addEvent';\nimport { addGlobalListeners } from './util/addGlobalListeners';\nimport { addMemoryEntry } from './util/addMemoryEntry';\nimport { createBreadcrumb } from './util/createBreadcrumb';\nimport { createPerformanceEntries } from './util/createPerformanceEntries';\nimport { createPerformanceSpans } from './util/createPerformanceSpans';\nimport { debounce } from './util/debounce';\nimport { getHandleRecordingEmit } from './util/handleRecordingEmit';\nimport { isExpired } from './util/isExpired';\nimport { isSessionExpired } from './util/isSessionExpired';\nimport { sendReplay } from './util/sendReplay';\nimport type { SKIPPED } from './util/throttle';\nimport { throttle, THROTTLED } from './util/throttle';\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nexport class ReplayContainer implements ReplayContainerInterface {\n public eventBuffer: EventBuffer | null = null;\n\n /**\n * List of PerformanceEntry from PerformanceObserver\n */\n public performanceEvents: AllPerformanceEntry[] = [];\n\n public session: Session | undefined;\n\n public clickDetector: ClickDetector | undefined;\n\n /**\n * Recording can happen in one of three modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n public recordingMode: ReplayRecordingMode = 'session';\n\n /**\n * The current or last active transcation.\n * This is only available when performance is enabled.\n */\n public lastTransaction?: Transaction;\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n public readonly timeouts: Timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n maxSessionLife: MAX_SESSION_LIFE,\n } as const;\n\n private _throttledAddEvent: (\n event: RecordingEvent,\n isCheckout?: boolean,\n ) => typeof THROTTLED | typeof SKIPPED | Promise;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n private readonly _options: ReplayPluginOptions;\n\n private _performanceObserver: PerformanceObserver | null = null;\n\n private _debouncedFlush: ReturnType;\n private _flushLock: Promise | null = null;\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n private _lastActivity: number = Date.now();\n\n /**\n * Is the integration currently active?\n */\n private _isEnabled: boolean = false;\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n private _isPaused: boolean = false;\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n private _hasInitializedCoreListeners: boolean = false;\n\n /**\n * Function to stop recording\n */\n private _stopRecording: ReturnType | null = null;\n\n private _context: InternalEventContext = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n public constructor({\n options,\n recordingOptions,\n }: {\n options: ReplayPluginOptions;\n recordingOptions: RecordingOptions;\n }) {\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event: RecordingEvent, isCheckout?: boolean) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig: SlowClickConfig | undefined = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n multiClickTimeout: MULTI_CLICK_TIMEOUT,\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n }\n\n /** Get the event context. */\n public getContext(): InternalEventContext {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n public isEnabled(): boolean {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n public isPaused(): boolean {\n return this._isPaused;\n }\n\n /** Get the replay integration options. */\n public getOptions(): ReplayPluginOptions {\n return this._options;\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n public initializeSampling(): void {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n if (errorSampleRate <= 0 && sessionSampleRate <= 0) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n const isSessionSampled = this._loadAndCheckSession();\n\n if (!isSessionSampled) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n this._handleException(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled && this.session.sampled !== 'session') {\n // If not sampled as session-based, then recording mode will be `buffer`\n // Note that we don't explicitly check if `sampled === 'buffer'` because we\n // could have sessions from Session storage that are still `error` from\n // prior SDK version.\n this.recordingMode = 'buffer';\n }\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (this._isEnabled && this.recordingMode === 'session') {\n throw new Error('Replay recording is already in progress');\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n throw new Error('Replay buffering is in progress, call `flush()` to save the replay');\n }\n\n const previousSessionId = this.session && this.session.id;\n\n const { session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n });\n\n session.previousSessionId = previousSessionId;\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n public startBuffering(): void {\n if (this._isEnabled) {\n throw new Error('Replay recording is already in progress');\n }\n\n const previousSessionId = this.session && this.session.id;\n\n const { session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n sessionSampleRate: 0,\n allowBuffering: true,\n });\n\n session.previousSessionId = previousSessionId;\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n public startRecording(): void {\n try {\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n public stopRecording(): boolean {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public async stop(reason?: string): Promise {\n if (!this._isEnabled) {\n return;\n }\n\n try {\n if (__DEBUG_BUILD__) {\n const msg = `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`;\n\n // When `traceInternals` is enabled, we want to log this to the console\n // Else, use the regular debug output\n // eslint-disable-next-line\n const log = this.getOptions()._experiments.traceInternals ? console.warn : logger.log;\n log(msg);\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (this.recordingMode === 'session') {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n public pause(): void {\n this._isPaused = true;\n this.stopRecording();\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n public resume(): void {\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public async sendBufferedReplayOrFlush({ continueRecording = true }: SendBufferedReplayOptions = {}): Promise {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // Re-start recording, but in \"session\" recording mode\n\n // Reset all \"capture on error\" configuration before\n // starting a new recording\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this.session.shouldRefresh = false;\n\n // It's possible that the session lifespan is > max session lifespan\n // because we have been buffering beyond max session lifespan (we ignore\n // expiration given that `shouldRefresh` is true). Since we flip\n // `shouldRefresh`, the session could be considered expired due to\n // lifespan, which is not what we want. Update session start date to be\n // the current timestamp, so that session is not considered to be\n // expired. This means that max replay duration can be MAX_SESSION_LIFE +\n // (length of buffer), which we are ok with.\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this.session.started = activityTime;\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n public addUpdate(cb: AddUpdateCallback): void {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n public triggerUserActivity(): void {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n public updateUserActivity(): void {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n public conditionalFlush(): Promise {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n public flushImmediate(): Promise {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() as Promise;\n }\n\n /**\n * Cancels queued up flushes.\n */\n public cancelFlush(): void {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current sesion (=replay) ID */\n public getSessionId(): string | undefined {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n public checkAndHandleExpiredSession(): boolean | void {\n const oldSessionId = this.getSessionId();\n\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Session was expired if session ids do not match\n const expired = oldSessionId !== this.getSessionId();\n\n if (!expired) {\n return true;\n }\n\n // Session is expired, trigger a full snapshot (which will create a new session)\n this._triggerFullSnapshot();\n\n return false;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n public setInitialState(): void {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEvents = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n public throttledAddEvent(\n event: RecordingEvent,\n isCheckout?: boolean,\n ): typeof THROTTLED | typeof SKIPPED | Promise {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n void addEvent(this, {\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n public getCurrentRoute(): string | undefined {\n const lastTransaction = this.lastTransaction || getCurrentHub().getScope().getTransaction();\n if (!lastTransaction || !['route', 'custom'].includes(lastTransaction.metadata.source)) {\n return undefined;\n }\n\n return lastTransaction.name;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n private _initializeRecording(): void {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n\n this.startRecording();\n }\n\n /** A wrapper to conditionally capture exceptions. */\n private _handleException(error: unknown): void {\n __DEBUG_BUILD__ && logger.error('[Replay]', error);\n\n if (__DEBUG_BUILD__ && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n * Returns false if session is not recorded.\n */\n private _loadAndCheckSession(): boolean {\n const { type, session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering: this._options.errorSampleRate > 0 || this.recordingMode === 'buffer',\n });\n\n // If session was newly created (i.e. was not loaded from storage), then\n // enable flag to create the root replay\n if (type === 'new') {\n this.setInitialState();\n }\n\n const currentSessionId = this.getSessionId();\n if (session.id !== currentSessionId) {\n session.previousSessionId = currentSessionId;\n }\n\n this.session = session;\n\n if (!this.session.sampled) {\n void this.stop('session unsampled');\n return false;\n }\n\n return true;\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n private _addListeners(): void {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n // PerformanceObserver //\n if (!('PerformanceObserver' in WINDOW)) {\n return;\n }\n\n this._performanceObserver = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n private _removeListeners(): void {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceObserver) {\n this._performanceObserver.disconnect();\n this._performanceObserver = null;\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n private _handleVisibilityChange: () => void = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n private _handleWindowBlur: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n /**\n * Handle when page is focused\n */\n private _handleWindowFocus: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n private _handleKeyboardEvent: (event: KeyboardEvent) => void = (event: KeyboardEvent) => {\n handleKeyboardEvent(this, event);\n };\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n private _doChangeToBackgroundTasks(breadcrumb?: BreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, this.timeouts);\n\n if (breadcrumb && !expired) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n private _doChangeToForegroundTasks(breadcrumb?: BreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n __DEBUG_BUILD__ && logger.log('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Trigger rrweb to take a full snapshot which will cause this plugin to\n * create a new Replay event.\n */\n private _triggerFullSnapshot(checkout = true): void {\n try {\n __DEBUG_BUILD__ && logger.log('[Replay] Taking full rrweb snapshot');\n record.takeFullSnapshot(checkout);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n private _updateUserActivity(_lastActivity: number = Date.now()): void {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n private _updateSessionActivity(_lastActivity: number = Date.now()): void {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n private _createCustomBreadcrumb(breadcrumb: BreadcrumbFrame): void {\n this.addUpdate(() => {\n void this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEvents`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n private _addPerformanceEntries(): Promise> {\n // Copy and reset entries before processing\n const entries = [...this.performanceEvents];\n this.performanceEvents = [];\n\n return Promise.all(createPerformanceSpans(this, createPerformanceEntries(entries)));\n }\n\n /**\n * Clear _context\n */\n private _clearContext(): void {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n private _updateInitialTimestampFromEventBuffer(): void {\n const { session, eventBuffer } = this;\n if (!session || !eventBuffer) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n private _popEventContext(): PopEventContext {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n private async _runFlush(): Promise {\n if (!this.session || !this.eventBuffer) {\n __DEBUG_BUILD__ && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n // NOTE: Copy values from instance members, as it's possible they could\n // change before the flush finishes.\n const replayId = this.session.id;\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp: Date.now(),\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n void this.stop('sendReplay');\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n private _flush = async ({\n force = false,\n }: {\n /**\n * If true, flush while ignoring the `_isEnabled` state of\n * Replay integration. (By default, flush is noop if integration\n * is stopped).\n */\n force?: boolean;\n } = {}): Promise => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n __DEBUG_BUILD__ && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n __DEBUG_BUILD__ && logger.error('[Replay] No session found to flush.');\n return;\n }\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = null;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n __DEBUG_BUILD__ && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };\n\n /** Save the session, if it is sticky */\n private _maybeSaveSession(): void {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n private _onMutationHandler = (mutations: unknown[]): boolean => {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n void this.stop('mutationLimit');\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };\n}\n","type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => unknown;\ntype DebounceOptions = { maxWait?: number };\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nexport function debounce(func: CallbackFunction, wait: number, options?: DebounceOptions): DebouncedCallback {\n let callbackReturnValue: unknown;\n\n let timerId: ReturnType | undefined;\n let maxTimerId: ReturnType | undefined;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc(): unknown {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers(): void {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush(): unknown {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced(): unknown {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { logger } from '@sentry/utils';\n\nimport { saveSession } from '../session/saveSession';\nimport type { AddEventResult, OptionFrameEvent, RecordingEvent, ReplayContainer } from '../types';\nimport { addEvent } from './addEvent';\n\ntype RecordingEmitCallback = (event: RecordingEvent, isCheckout?: boolean) => void;\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nexport function getHandleRecordingEmit(replay: ReplayContainer): RecordingEmitCallback {\n let hadFirstEvent = false;\n\n return (event: RecordingEvent, _isCheckout?: boolean) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n __DEBUG_BUILD__ && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // We need to clear existing events on a checkout, otherwise they are\n // incremental event updates and should be appended\n void addEvent(replay, event, isCheckout);\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time.\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n void addSettingsEvent(replay, isCheckout);\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n const options = replay.getOptions();\n\n // TODO: We want this as an experiment so that we can test\n // internally and create metrics before making this the default\n if (options._experiments.delayFlushOnCheckout) {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n // TODO: We should check `recordingMode` here and do nothing if it's\n // buffer, instead of checking inside of timeout, this will make our\n // tests a bit cleaner as we will need to wait on the delay in order to\n // do nothing.\n setTimeout(() => replay.conditionalFlush(), options._experiments.delayFlushOnCheckout);\n\n // Cancel any previously debounced flushes to ensure there are no [near]\n // simultaneous flushes happening. The latter request should be\n // insignificant in this case, so wait for additional user interaction to\n // trigger a new flush.\n //\n // This can happen because there's no guarantee that a recording event\n // happens first. e.g. a mouse click can happen and trigger a debounced\n // flush before the checkout.\n replay.cancelFlush();\n\n return true;\n }\n\n // Flush immediately so that we do not miss the first segment, otherwise\n // it can prevent loading on the UI. This will cause an increase in short\n // replays (e.g. opening and closing a tab quickly), but these can be\n // filtered on the UI.\n if (replay.recordingMode === 'session') {\n // We want to ensure the worker is ready, as otherwise we'd always send the first event uncompressed\n void replay.flushImmediate();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nexport function createOptionsEvent(replay: ReplayContainer): OptionFrameEvent {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay: ReplayContainer, isCheckout?: boolean): Promise {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return Promise.resolve(null);\n }\n\n return addEvent(replay, createOptionsEvent(replay), false);\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../../src/constants';\nimport type { ReplayContainer } from '../../src/types';\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nexport function clearSession(replay: ReplayContainer): void {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession(): void {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n\n if (!hasSessionStorage) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import r from\"./worker\";function e(){const e=new Blob([r]);return URL.createObjectURL(e)}export{e as getWorkerURL};\n","export default `/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\nfunction t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const m=t=>t<256?o[t]:o[256+(t>>>7)],b=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},g=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<{g(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)r=r+a[n-1]<<1,i[n]=r;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},x=t=>{t.bi_valid>8?b(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n{let s,r,o,_,f=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+f++],s+=(255&t.pending_buf[t.sym_buf+f++])<<8,r=t.pending_buf[t.sym_buf+f++],0===s?p(t,r,i):(o=l[r],p(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],g(t,r,_)),s--,o=m(s),p(t,o,n),_=a[o],0!==_&&(s-=d[o],g(t,s,_)))}while(f{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o{g(t,0+(i?1:0),3),x(t),b(t,a),b(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var T=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(g(t,2+(i?1:0),3),E(t,s,r)):(g(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(g(t,e-257,5),g(t,a-1,5),g(t,i-4,4),s=0;s{S||((()=>{let t,n,w,m,b;const g=new Array(16);for(w=0,m=0;m<28;m++)for(h[m]=w,t=0;t<1<>=7;m<30;m++)for(d[m]=b<<7,t=0;t<1<(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=a,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{g(t,2,3),p(t,256,s),(t=>{16===t.bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var F=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const L=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var N=(t,e,a,i)=>{const n=L,s=i+a;t^=-1;for(let a=i;a>>8^n[255&(t^e[a])];return-1^t},I={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=O,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:W,Z_OK:q,Z_STREAM_END:J,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>2*t-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_t=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let ft=(t,e,a)=>(e<{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ut=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ct(t.strm)},wt=(t,e)=>{t.pending_buf[t.pending++]=e},mt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=F(t.adler,e,n,a):2===t.state.wrap&&(t.adler=N(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&sr){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_t(t),i+=e),0===t.strm.avail_in)break;if(a=bt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ft(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ft(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},kt=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_outi+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,ct(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(bt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_watern&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(bt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===X)&&e!==P&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===X&&0===t.strm.avail_in&&a===i?1:0,H(t,t.block_start,a,r),t.block_start+=a,ct(t.strm)),r?3:1)},vt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ft(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2},yt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ut(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ut(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2};function xt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const zt=[new xt(0,0,0,0,kt),new xt(4,4,8,4,vt),new xt(4,5,16,8,vt),new xt(4,6,32,32,vt),new xt(4,4,16,16,yt),new xt(8,16,32,32,yt),new xt(8,16,128,128,yt),new xt(8,32,128,256,yt),new xt(32,128,258,1024,yt),new xt(32,258,258,4096,yt)];function At(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Et=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||42!==e.status&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&113!==e.status&&666!==e.status?1:0},Rt=t=>{if(Et(t))return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=-2,C(e),q},Zt=t=>{const e=Rt(t);var a;return e===q&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=zt[a.level].max_lazy,a.good_match=zt[a.level].good_length,a.nice_match=zt[a.level].nice_length,a.max_chain_length=zt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},Ut=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt||8===i&&1!==r)return lt(t,Q);8===i&&(i=9);const o=new At;return t.state=o,o.strm=t,o.status=42,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<Ut(t,e,ot,15,8,st),deflateInit2:Ut,deflateReset:Zt,deflateResetKeep:Rt,deflateSetHeader:(t,e)=>Et(t)||2!==t.state.wrap?Q:(t.state.gzhead=e,q),deflate:(t,e)=>{if(Et(t)||e>W||e<0)return t?lt(t,Q):Q;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||666===a.status&&e!==X)return lt(t,0===t.avail_out?$:Q);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(ct(t),0===t.avail_out)return a.last_flush=-1,q}else if(0===t.avail_in&&ht(e)<=ht(i)&&e!==X)return lt(t,$);if(666===a.status&&0!==t.avail_in)return lt(t,$);if(42===a.status&&0===a.wrap&&(a.status=113),42===a.status){let e=ot+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=at||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,mt(a,e),0!==a.strstart&&(mt(a,t.adler>>>16),mt(a,65535&t.adler)),t.adler=1,a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(57===a.status)if(t.adler=0,wt(a,31),wt(a,139),wt(a,8),a.gzhead)wt(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),wt(a,255&a.gzhead.time),wt(a,a.gzhead.time>>8&255),wt(a,a.gzhead.time>>16&255),wt(a,a.gzhead.time>>24&255),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(wt(a,255&a.gzhead.extra.length),wt(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=N(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,3),a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,ct(t),0!==a.pending)return a.last_flush=-1,q;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(ct(t),0!==a.pending))return a.last_flush=-1,q;wt(a,255&t.adler),wt(a,t.adler>>8&255),t.adler=0}if(a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(0!==t.avail_in||0!==a.lookahead||e!==P&&666!==a.status){let i=0===a.level?kt(a,e):a.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):zt[a.level].func(a,e);if(3!==i&&4!==i||(a.status=666),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),q;if(2===i&&(e===Y?K(a):e!==W&&(H(a,0,0,!1),e===G&&(dt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),ct(t),0===t.avail_out))return a.last_flush=-1,q}return e!==X?q:a.wrap<=0?J:(2===a.wrap?(wt(a,255&t.adler),wt(a,t.adler>>8&255),wt(a,t.adler>>16&255),wt(a,t.adler>>24&255),wt(a,255&t.total_in),wt(a,t.total_in>>8&255),wt(a,t.total_in>>16&255),wt(a,t.total_in>>24&255)):(mt(a,t.adler>>>16),mt(a,65535&t.adler)),ct(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?q:J)},deflateEnd:t=>{if(Et(t))return Q;const e=t.state.status;return t.state=null,113===e?lt(t,V):q},deflateSetDictionary:(t,e)=>{let a=e.length;if(Et(t))return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=F(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=ft(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,q},deflateInfo:\"pako deflate (from Nodeca project)\"};const Dt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Tt=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if(\"object\"!=typeof a)throw new TypeError(a+\"must be non-object\");for(const e in a)Dt(a,e)&&(t[e]=a[e])}}return t},Ot=t=>{let e=0;for(let a=0,i=t.length;a=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Lt[254]=Lt[254]=1;var Nt=t=>{if(\"function\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},It=(t,e)=>{const a=e||t.length;if(\"function\"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Ft)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a=\"\";for(let i=0;i{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Lt[t[a]]>e?a:e};var Ct=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0};const Ht=Object.prototype.toString,{Z_NO_FLUSH:Mt,Z_SYNC_FLUSH:jt,Z_FULL_FLUSH:Kt,Z_FINISH:Pt,Z_OK:Yt,Z_STREAM_END:Gt,Z_DEFAULT_COMPRESSION:Xt,Z_DEFAULT_STRATEGY:Wt,Z_DEFLATED:qt}=B;function Jt(t){this.options=Tt({level:Xt,method:qt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Wt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=St.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==Yt)throw new Error(I[a]);if(e.header&&St.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t=\"string\"==typeof e.dictionary?Nt(e.dictionary):\"[object ArrayBuffer]\"===Ht.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=St.deflateSetDictionary(this.strm,t),a!==Yt)throw new Error(I[a]);this._dict_set=!0}}function Qt(t,e){const a=new Jt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}Jt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Pt:Mt,\"string\"==typeof t?a.input=Nt(t):\"[object ArrayBuffer]\"===Ht.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===jt||s===Kt)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=St.deflate(a,s),n===Gt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=St.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Yt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},Jt.prototype.onData=function(t){this.chunks.push(t)},Jt.prototype.onEnd=function(t){t===Yt&&(this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Vt={Deflate:Jt,deflate:Qt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Qt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Qt(t,e)},constants:B};var $t=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a>3,a-=k,c-=k<<3,f&=(1<{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,U,S,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0}while(0!==d);for(h=1<>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg=\"\",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whavexe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg=\"incorrect header check\",a.mode=me;break}if((15&h)!==we){t.msg=\"unknown compression method\",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg=\"invalid window size\",a.mode=me;break}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=N(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=N(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg=\"invalid block type\",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg=\"invalid stored block lengths\",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg=\"too many length or distance symbols\",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid code lengths set\",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg=\"invalid bit length repeat\",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg=\"invalid bit length repeat\",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg=\"invalid code -- missing end-of-block\",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid literal/lengths set\",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg=\"invalid distances set\",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg=\"invalid literal/length code\",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg=\"invalid distance code\",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg=\"invalid distance too far back\",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg=\"invalid distance too far back\",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=F(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:\"pako inflate (from Nodeca project)\"};var Se=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Te,Z_FINISH:Oe,Z_OK:Fe,Z_STREAM_END:Le,Z_NEED_DICT:Ne,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Tt({chunkSize:65536,windowBits:15,to:\"\"},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ue.inflateInit2(this.strm,e.windowBits);if(a!==Fe)throw new Error(I[a]);if(this.header=new Se,Ue.inflateGetHeader(this.strm,this.header),e.dictionary&&(\"string\"==typeof e.dictionary?e.dictionary=Nt(e.dictionary):\"[object ArrayBuffer]\"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Ue.inflateSetDictionary(this.strm,e.dictionary),a!==Fe)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Oe:Te,\"[object ArrayBuffer]\"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Ue.inflate(a,r),s===Ne&&n&&(s=Ue.inflateSetDictionary(a,n),s===Fe?s=Ue.inflate(a,r):s===Be&&(s=Ne));a.avail_in>0&&s===Le&&a.state.wrap>0&&0!==t[a.next_in];)Ue.inflateReset(a),s=Ue.inflate(a,r);switch(s){case Ie:case Be:case Ne:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Le))if(\"string\"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Fe||0!==o){if(s===Le)return s=Ue.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Fe&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=je,Xe=B;const We=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const e=this._hasEvents?\",\":\"\";this.deflate.push(e+t,Xe.Z_SYNC_FLUSH),this._hasEvents=!0}finish(){if(this.deflate.push(\"]\",Xe.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this._init(),t}_init(){this._hasEvents=!1,this.deflate=new Ye,this.deflate.push(\"[\",Xe.Z_NO_FLUSH)}},qe={clear:()=>{We.clear()},addEvent:t=>We.addEvent(t),finish:()=>We.finish(),compress:t=>function(t){return Ge(t)}(t)};addEventListener(\"message\",(function(t){const e=t.data.method,a=t.data.id,i=t.data.arg;if(e in qe&&\"function\"==typeof qe[e])try{const t=qe[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n","import type { HistoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from '../util/createPerformanceSpans';\n\ninterface HistoryHandlerData {\n from: string;\n to: string;\n}\n\nfunction handleHistory(handlerData: HistoryHandlerData): ReplayPerformanceEntry {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.\n */\nexport function handleHistorySpanListener(replay: ReplayContainer): (handlerData: HistoryHandlerData) => void {\n return (handlerData: HistoryHandlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n","import type { Event, EventHint } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';\nimport { isRrwebError } from '../util/isRrwebError';\nimport { handleAfterSendEvent } from './handleAfterSendEvent';\nimport { shouldSampleForBufferEvent } from './util/shouldSampleForBufferEvent';\n\n/**\n * Returns a listener to be added to `addGlobalEventProcessor(listener)`.\n */\nexport function handleGlobalEventListener(\n replay: ReplayContainer,\n includeAfterSendEventHandling = false,\n): (event: Event, hint: EventHint) => Event | null {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return (event: Event, hint: EventHint) => {\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors & transactions, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event)) {\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n __DEBUG_BUILD__ && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n };\n}\n","import type { Event, EventHint } from '@sentry/types';\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nexport function isRrwebError(event: Event, hint: EventHint): boolean {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-ignore this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n // Check if any exception originates from rrweb\n return event.exception.values.some(exception => {\n if (!exception.stacktrace || !exception.stacktrace.frames || !exception.stacktrace.frames.length) {\n return false;\n }\n\n return exception.stacktrace.frames.some(frame => frame.filename && frame.filename.includes('/rrweb/src/'));\n });\n}\n","import type { Event } from '@sentry/types';\n\nimport { UNABLE_TO_SEND_REPLAY } from '../../constants';\nimport type { ReplayContainer } from '../../types';\nimport { isSampled } from '../../util/isSampled';\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `hanldleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nexport function shouldSampleForBufferEvent(replay: ReplayContainer, event: Event): boolean {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n","import type { AllPerformanceEntry, ReplayContainer } from '../types';\nimport { dedupePerformanceEntries } from '../util/dedupePerformanceEntries';\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n */\nexport function setupPerformanceObserver(replay: ReplayContainer): PerformanceObserver {\n const performanceObserverHandler = (list: PerformanceObserverEntryList): void => {\n // For whatever reason the observer was returning duplicate navigation\n // entries (the other entry types were not duplicated).\n const newPerformanceEntries = dedupePerformanceEntries(\n replay.performanceEvents,\n list.getEntries() as AllPerformanceEntry[],\n );\n replay.performanceEvents = newPerformanceEntries;\n };\n\n const performanceObserver = new PerformanceObserver(performanceObserverHandler);\n\n [\n 'element',\n 'event',\n 'first-input',\n 'largest-contentful-paint',\n 'layout-shift',\n 'longtask',\n 'navigation',\n 'paint',\n 'resource',\n ].forEach(type => {\n try {\n performanceObserver.observe({\n type,\n buffered: true,\n });\n } catch {\n // This can throw if an entry type is not supported in the browser.\n // Ignore these errors.\n }\n });\n\n return performanceObserver;\n}\n","import type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { getBaseDomBreadcrumb } from './handleDom';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\n/** Handle keyboard events & create breadcrumbs. */\nexport function handleKeyboardEvent(replay: ReplayContainer, event: KeyboardEvent): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nexport function getKeyboardBreadcrumb(event: KeyboardEvent): Breadcrumb | null {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target as HTMLElement) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target as Node, message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target: HTMLElement): boolean {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n","import type { DeprecatedPrivacyOptions, ReplayIntegrationPrivacyOptions } from '../types';\n\ntype GetPrivacyOptions = Required> &\n Omit;\ninterface GetPrivacyReturn {\n maskTextSelector: string;\n unmaskTextSelector: string;\n maskInputSelector: string;\n unmaskInputSelector: string;\n blockSelector: string;\n unblockSelector: string;\n ignoreSelector: string;\n\n blockClass?: RegExp;\n maskTextClass?: RegExp;\n}\n\nfunction getOption(\n selectors: string[],\n defaultSelectors: string[],\n deprecatedClassOption?: string | RegExp,\n deprecatedSelectorOption?: string,\n): string {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nexport function getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}: GetPrivacyOptions): GetPrivacyReturn {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options: GetPrivacyReturn = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n maskInputSelector: maskSelector,\n unmaskInputSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n","import { isNodeEnv } from '@sentry/utils';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n return typeof process !== 'undefined' && (process as ElectronProcess).type === 'renderer';\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { BrowserClientReplayOptions, Integration } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_FLUSH_MAX_DELAY, DEFAULT_FLUSH_MIN_DELAY } from './constants';\nimport { ReplayContainer } from './replay';\nimport type { RecordingOptions, ReplayConfiguration, ReplayPluginOptions, SendBufferedReplayOptions } from './types';\nimport { getPrivacyOptions } from './util/getPrivacyOptions';\nimport { isBrowser } from './util/isBrowser';\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\ntype InitialReplayPluginOptions = Omit &\n Partial>;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n */\nexport class Replay implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Replay';\n\n /**\n * @inheritDoc\n */\n public name: string = Replay.id;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n private readonly _initialOptions: InitialReplayPluginOptions;\n\n private _replay?: ReplayContainer;\n\n public constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n stickySession = true,\n useCompression = true,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10_000,\n\n slowClickTimeout = 7_000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n }: ReplayConfiguration = {}) {\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n\n ...getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n }),\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n protected get _isInitialized(): boolean {\n return _initialized;\n }\n\n /** Update _isInitialized */\n protected set _isInitialized(value: boolean) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n public setupOnce(): void {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // Once upon a time, we tried to create a transaction in `setupOnce` and it would\n // potentially create a transaction before some native SDK integrations have run\n // and applied their own global event processor. An example is:\n // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n //\n // So we call `this._initialize()` in next event loop as a workaround to wait for other\n // global event processors to finish. This is no longer needed, but keeping it\n // here to avoid any future issues.\n setTimeout(() => this._initialize());\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n public startBuffering(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public stop(): Promise {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop();\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public flush(options?: SendBufferedReplayOptions): Promise {\n if (!this._replay || !this._replay.isEnabled()) {\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n public getReplayId(): string | undefined {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n /**\n * Initializes replay.\n */\n protected _initialize(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n private _setup(): void {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions: InitialReplayPluginOptions): ReplayPluginOptions {\n const client = getCurrentHub().getClient();\n const opt = client && (client.getOptions() as BrowserClientReplayOptions);\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers: string[]): string[] {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n","export const SDK_VERSION = '7.56.0';\n","import type { ConsoleLevel } from './logger';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { Integration, Options } from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\nimport { addGlobalEventProcessor } from './scope';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(integration: Integration, integrationIndex: IntegrationIndex): void {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n __DEBUG_BUILD__ && logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n Integration,\n IntegrationClass,\n Outcome,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n SentryError,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport type { IntegrationIndex } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean = false;\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number } = {};\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record = {};\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n __DEBUG_BUILD__ && logger.warn('No DSN provided, client will not do anything.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n __DEBUG_BUILD__ && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n setupIntegration(integration, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n if (this._dsn) {\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n if (this._dsn) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n void this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, _event?: Event): void {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n __DEBUG_BUILD__ && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n\n /** @inheritdoc */\n public on(hook: 'startTransaction' | 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-ignore We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction' | 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n // @ts-ignore we cannot enforce the callback to match the hook\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent(options, event, hint, scope);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (__DEBUG_BUILD__) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n if (this._transport && this._dsn) {\n this.emit('beforeEnvelope', envelope);\n\n return this._transport.send(envelope).then(null, reason => {\n __DEBUG_BUILD__ && logger.error('Error while sending event:', reason);\n });\n } else {\n __DEBUG_BUILD__ && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: string,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n","import type { Scope } from '@sentry/core';\nimport { BaseClient, SDK_VERSION } from '@sentry/core';\nimport type {\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { Breadcrumbs } from './integrations';\nimport { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options & BrowserClientReplayOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint?: EventHint): void {\n // We only want to add the sentry event breadcrumb when the user has the breadcrumb integration installed and\n // activated its `sentry` option.\n // We also do not want to use the `Breadcrumbs` class here directly, because we do not want it to be included in\n // bundles, if it is not used by the SDK.\n // This all sadly is a bit ugly, but we currently don't have a \"pre-send\" hook on the integrations so we do it this\n // way for now.\n const breadcrumbIntegration = this.getIntegrationById(BREADCRUMB_INTEGRATION_ID) as Breadcrumbs | undefined;\n // We check for definedness of `addSentryBreadcrumb` in case users provided their own integration with id\n // \"Breadcrumbs\" that does not have this function.\n if (breadcrumbIntegration && breadcrumbIntegration.addSentryBreadcrumb) {\n breadcrumbIntegration.addSentryBreadcrumb(event);\n }\n\n super.sendEvent(event, hint);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n void this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n __DEBUG_BUILD__ && logger.log('No outcomes to send');\n return;\n }\n\n if (!this._dsn) {\n __DEBUG_BUILD__ && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n void this._sendEnvelope(envelope);\n }\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type { TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, category: string): number {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, category: string, now: number = Date.now()): boolean {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n SentryError,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n __DEBUG_BUILD__ && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n __DEBUG_BUILD__ && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import type { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcessor: EventProcessor = currentEvent => {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n __DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport {\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n Integrations as CoreIntegrations,\n} from '@sentry/core';\nimport type { UserFeedback } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n logger,\n resolvedSyncPromise,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, HttpContext, LinkedErrors, TryCatch } from './integrations';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\nexport const defaultIntegrations = [\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\n];\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nexport function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n __DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n __DEBUG_BUILD__ && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n __DEBUG_BUILD__ && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function flush(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function close(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\nfunction startSessionOnHub(hub: Hub): void {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n __DEBUG_BUILD__ &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getCurrentHub().getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import type { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { CONSOLE_LEVELS, fill, GLOBAL_OBJ, safeJoin, severityLevelFromString } from '@sentry/utils';\n\n/** Send Console API calls as Sentry Events */\nexport class CaptureConsole implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'CaptureConsole';\n\n /**\n * @inheritDoc\n */\n public name: string = CaptureConsole.id;\n\n /**\n * @inheritDoc\n */\n private readonly _levels: readonly string[] = CONSOLE_LEVELS;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { levels?: string[] } = {}) {\n if (options.levels) {\n this._levels = options.levels;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n this._levels.forEach((level: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if (!(level in (GLOBAL_OBJ as any).console)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n fill((GLOBAL_OBJ as any).console, level, (originalConsoleMethod: () => any) => (...args: any[]): void => {\n const hub = getCurrentHub();\n\n if (hub.getIntegration(CaptureConsole)) {\n hub.withScope(scope => {\n scope.setLevel(severityLevelFromString(level));\n scope.setExtra('arguments', args);\n scope.addEventProcessor(event => {\n event.logger = 'console';\n return event;\n });\n\n let message = safeJoin(args, ' ');\n if (level === 'assert') {\n if (args[0] === false) {\n message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n hub.captureMessage(message);\n }\n } else if (level === 'error' && args[0] instanceof Error) {\n hub.captureException(args[0]);\n } else {\n hub.captureMessage(message);\n }\n });\n }\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(GLOBAL_OBJ.console, args);\n }\n });\n });\n }\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["isBrowserBundle","__SENTRY_BROWSER_BUNDLE__","getSDKSource","isNodeEnv","Object","prototype","toString","call","process","dynamicRequire","mod","request","require","WINDOW","getGlobalObject","dateTimestampSource","nowSeconds","Date","now","platformPerformance","module","performance","_","getNodePerformance","timeOrigin","getBrowserPerformance","timestampSource","undefined","dateTimestampInSeconds","bind","timestampInSeconds","browserPerformanceTimeOrigin","threshold","performanceNow","dateNow","timeOriginDelta","Math","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","isGlobalObj","obj","GLOBAL_OBJ","globalThis","window","self","global","getGlobalSingleton","name","creator","gbl","__SENTRY__","_typeof","_regeneratorRuntime","exports","__esModule","Op","hasOwn","hasOwnProperty","defineProperty","key","desc","value","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","enumerable","configurable","writable","err","wrap","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","fn","arg","type","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","result","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","done","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","methodName","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","runtime","regeneratorRuntime","accidentalStrictMode","Function","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","n","getter","d","a","definition","o","get","g","e","hmd","children","set","prop","r","flarum","core","compat","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","base","_e","truncate","str","max","safeJoin","input","delimiter","Array","isArray","output","String","join","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","InboundFilters","__initStatic","_proto","_options","__init","setupOnce","addGlobalEventProcessor","getCurrentHub","eventProcess","event","hub","getIntegration","client","getClient","clientOptions","getOptions","options","internalOptions","allowUrls","concat","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","_isSentryError","message","_ref","_ref$type","_ref$value","oO","_getPossibleEventMessages","_isIgnoredError","transaction","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","frames","stacktrace","frame","filename","_getLastValidUrl","_extends","assign","target","arguments","source","apply","originalFunctionToString","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","nextStr","currentElem","out","height","len","keyAttrs","maxStringLength","_htmlElementAsString","separator","parentNode","_oO","el","classes","attr","tagName","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","keyAttrPair","split","allowedAttrs","fill","replacementFactory","original","wrapped","markFunctionWrapped","_Oo","addNonEnumerableProperty","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","extractExceptionKeysForMessage","maxLength","sort","includedKeys","serialized","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","memoVal","returnValue","_i","_Object$keys","item","FunctionToString","_len","args","_key","WEBPACK_ERROR_REGEXP","defaultFunctionName","getFunctionName","uuid4","crypto","msCrypto","randomUUID","replace","getRandomByte","getRandomValues","Uint8Array","random","c","getFirstException","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","logger","CONSOLE_LEVELS","enable","disable","States","DEFAULT_ENVIRONMENT","resolvedSyncPromise","SyncPromise","rejectedSyncPromise","reason","executor","__init2","__init3","__init4","__init5","__init6","_resolve","_reject","_state","PENDING","_handlers","onfulfilled","onrejected","_this","_executeHandlers","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","_value","_this6","cachedHandlers","handler","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","clone","scope","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","addScopeListener","callback","addEventProcessor","setUser","_notifyScopeListeners","getUser","getRequestSession","setRequestSession","requestSession","setTags","tags","setTag","_extends2","setExtras","extras","setExtra","extra","_extends3","setFingerprint","fingerprint","setLevel","level","setTransactionName","setContext","setSpan","span","getSpan","getTransaction","setSession","getSession","update","captureContext","updatedScope","contexts","clear","addBreadcrumb","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","hint","trace","getTraceContext","sdkProcessingMetadata","dynamicSamplingContext","getDynamicSamplingContext","transactionName","_applyFingerprint","breadcrumbs","_notifyEventProcessors","getGlobalEventProcessors","setSDKProcessingMetadata","newData","processors","index","processor","final","maybeArray","API_VERSION","Hub","_version","_stack","bindClient","isOlderThan","version","getStackTop","setupIntegrations","pushScope","getScope","getStack","popScope","withScope","captureException","_lastEventId","syntheticException","_withClient","originalException","captureMessage","captureEvent","lastEventId","_this$getStackTop","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","originalConsole","console","wrappedLevels","originalWrappedFunc","consoleSandbox","emit","configureScope","_this$getStackTop2","run","oldHub","makeMain","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2","_ref2$environment","navigator","startingTime","toJSON","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","_this$getStackTop5","sentry","getMainCarrier","extensions","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","ignoreOnError","shouldIgnoreOnError","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","ex","setTimeout","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","TryCatch","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","originalCallback","originalSend","xhr","wrapOptions","originalFunction","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","isNativeFetch","lastHref","SENTRY_XHR_DATA_KEY","handlers","instrumented","instrument","originalConsoleMethod","triggerHandlers","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","document","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","instrumentDOM","xhrproto","originalOpen","_len3","_key3","xhrInfo","toUpperCase","request_headers","match","__sentry_own_request__","onreadystatechangeHandler","readyState","status_code","endTimestamp","startTimestamp","onreadystatechange","_len4","readyStateArgs","_key4","_len5","setRequestHeaderArgs","_key5","header","sentryXhrData","_len6","_key6","body","instrumentXHR","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","chrome","isChromePackagedApp","app","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","location","href","from","_len7","_key7","historyReplacementFunction","originalHistoryFunction","_len8","_key8","instrumentHistory","_oldOnErrorHandler","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","onunhandledrejection","addInstrumentationHandler","_step","_iterator","_createForOfIteratorHelperLoose","resource","debounceTimerID","lastCapturedEvent","debounceDuration","globalListener","isContentEditable","shouldSkipDOMEvent","previous","current","shouldShortcircuitPreviousDebounce","clearTimeout","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","isSyntheticEvent","objName","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","numAdded","visitable","visitKey","visitValue","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","__serialized__","eventFromPlainObject","synthetic","GlobalHandlers","_installFunc","_installGlobalOnErrorHandler","_installGlobalOnUnhandledRejectionHandler","stackTraceLimit","installFunc","_getHubAndOptions","getHubAndOptions","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","addMechanismAndCapture","_getHubAndOptions2","ev","ev0","ev0s","ev0sf","colno","parseInt","lineno","getLocationHref","in_app","validSeverityLevels","severityLevelFromString","parseUrl","query","fragment","host","path","protocol","search","hash","relative","BREADCRUMB_INTEGRATION_ID","Breadcrumbs","dom","_consoleBreadcrumb","serializeAttribute","_isEvent","category","_xhrBreadcrumb","_fetchBreadcrumb","_historyBreadcrumb","addSentryBreadcrumb","parsedLoc","parsedFrom","parsedTo","LinkedErrors","_limit","limit","parser","linkedErrors","_walkErrorTree","_handler","HttpContext","referrer","headers","Referer","_setPrototypeOf","p","_inheritsLoose","subClass","superClass","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","indexOf","Wrapper","asyncGeneratorStep","gen","_next","_throw","_asyncToGenerator","_defineProperties","props","descriptor","prim","toPrimitive","res","_createClass","Constructor","protoProps","staticProps","prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","integrations","dist","_options$maxValueLeng","maxValueLength","applyClientOptions","integrationNames","sdk","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","debugIdStackParserCache","filenameDebugIdMap","reduce","acc","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","attachments","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","b","spans","normalizeEvent","WeakMap","DSN_REGEX","dsnToString","dsn","withPassword","pass","port","projectId","publicKey","dsnFromComponents","components","makeDsn","exec","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","createEnvelope","items","forEachEnvelopeItem","envelope","envelopeItem","encodeUTF8","textEncoder","TextEncoder","encode","serializeEnvelope","envHeaders","parts","append","_step2","_iterator2","itemHeaders","payload","stringifiedPayload","buffers","_step3","totalLength","buf","merged","offset","_iterator3","buffer","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","_metadataOrEvent$sdk","createEventEnvelopeHeaders","sdkInfo","tunnel","sent_at","NodeType$1","REPLAY_SESSION_KEY","REPLAY_EVENT_NAME","UNABLE_TO_SEND_REPLAY","RETRY_BASE_INTERVAL","RETRY_MAX_COUNT","NETWORK_BODY_MAX_SIZE","CONSOLE_ARG_MAX_SIZE","REPLAY_MAX_EVENT_BUFFER_SIZE","isShadowRoot","shadowRoot","isInputTypeMasked","maskInputOptions","actualType","maskInputValue","_ref3","maskInputSelector","unmaskInputSelector","maskInputFn","text","matches","hasAttribute","repeat","NodeType","ORIGINAL_ATTRIBUTE_NAME","getInputType","element","getInputValue","canvasService","canvasCtx","_id","tagNameRegex","RegExp","IGNORED_NODE","defaultMaskFn","getCssRulesString","s","rules","cssRules","getCssRuleString","rule","cssStringified","cssText","isCSSImportRule","styleSheet","_a","validateStringifiedCssRule","URL_IN_CSS_REF","RELATIVE_PATH","DATA_URI","absoluteToStylesheet","origin","quote1","path1","quote2","path2","path3","filePath","maybeQuote","part","EventType","IncrementalSource","MouseInteractions","CanvasContext","MediaInteractions","ReplayerEvents","SRCSET_NOT_SPACES","SRCSET_COMMAS_OR_SPACES","absoluteToDoc","attributeValue","trim","isSVGElement","ownerSVGElement","getHref","transformAttribute","_tagName","_name","maskAllText","unmaskTextSelector","maskTextFn","pos","collectCharacters","regEx","chars","substring","descriptorsStr","inParens","getAbsoluteSrcsetString","attribute","_shouldMaskAttribute","needMaskingText","node","maskTextClass","maskTextSelector","nodeType","ELEMENT_NODE","closest","classList","contains","eIndex","lowerIfExists","maybeAttr","serializeNodeWithId","blockClass","blockSelector","unblockSelector","_options$skipChild","skipChild","_options$inlineStyles","inlineStylesheet","_options$maskInputOpt2","slimDOMOptions","_options$dataURLOptio2","dataURLOptions","_options$inlineImages","inlineImages","_options$recordCanvas","recordCanvas","onSerialize","onIframeLoad","_options$iframeLoadTi","iframeLoadTimeout","_options$keepIframeSr","keepIframeSrcFn","_options$preserveWhit","preserveWhiteSpace","_serializedNode","rootId","sheet","_options$maskInputOpt","_options$dataURLOptio","__sn","docId","DOCUMENT_NODE","compatMode","Document","childNodes","DOCUMENT_TYPE_NODE","DocumentType","publicId","systemId","needBlock","_isBlockedElement","HTMLFormElement","processedTagName","getValidTagName","attributes","_Array$from","_Array$from$_i","skipAttribute","stylesheet","styleSheets","find","rel","_cssText","innerText","textContent","checked","selected","__context","canvas","ctx","getContext","x","width","y","getImageData","originalGetImageData","Uint32Array","min","pixel","is2DCanvasBlank","rr_dataURL","toDataURL","quality","canvasDataURL","blankCanvas","image","oldValue","crossOrigin","recordInlineImage","naturalWidth","naturalHeight","drawImage","warn","currentSrc","onload","rr_mediaState","paused","rr_mediaCurrentTime","currentTime","scrollLeft","rr_scrollLeft","scrollTop","rr_scrollTop","_n$getBoundingClientR","getBoundingClientRect","rr_width","rr_height","src","contentDocument","rr_src","isSVG","TEXT_NODE","parentTagName","isStyle","isScript","nextSibling","previousSibling","Text","CDATA_SECTION_NODE","CDATA","COMMENT_NODE","Comment","serializeNode","sn","comment","script","as","endsWith","headFavicon","headMetaDescKeywords","headMetaSocial","headMetaRobots","headMetaHttpEquiv","headMetaAuthorship","headMetaVerification","slimDOMExcluded","serializedNode","recordChild","isShadowHost","headWhitespace","bypassOptions","_i2","_Array$from2","serializedChildNode","isElement","_i3","_Array$from3","isShadow","iframeEl","win","fired","blankUrl","timer","onceIframeLoaded","iframeDoc","serializedIframeNode","attributeName","on","capture","passive","removeEventListener","DEPARTED_MIRROR_ACCESS_WARNING","_mirror","getId","getNode","removeNodeFromMap","throttle$1","wait","timeout","leading","remaining","trailing","hookSetter","isRevoked","patch","replacement","defineProperties","__rrweb_original__","getWindowHeight","innerHeight","documentElement","clientHeight","getWindowWidth","innerWidth","clientWidth","isBlocked","needUnblock","isIgnored","isAncestorRemoved","mirror","isTouchEvent","changedTouches","isIframeINode","hasShadowRoot","isNodeInLinkedList","receiver","DoubleLinkedList","position","addNode","__ln","removeNode","moveKey","parentId","isINode","MutationBuffer","frozen","locked","texts","removes","mapRemoves","movedMap","addedSet","Set","movedSet","droppedSet","processMutations","mutations","processMutation","adds","addList","getNextId","ns","nextId","pushAdd","_b","_c","_d","shadowHost","getRootNode","rootShadowHost","notInDoc","currentN","iframeManager","addIframe","shadowDomManager","addShadowRoot","iframe","childSn","attachIframe","observeAttachShadow","shift","isParentRemoved","isAncestorInSet","candidate","_node","mutationCb","m","setAttribute","old","style","styleObj","_i4","_Array$from4","pname","newValue","getPropertyValue","newPriority","getPropertyPriority","_i5","_Array$from5","addedNodes","genAdds","removedNodes","nodeId","deepDelete","targetId","childN","_proto2","freeze","canvasManager","unfreeze","isFrozen","lock","unlock","addsSet","callbackWrapper","cb","__rrweb__","mutationBuffers","getEventTarget","composedPath","initMutationObserver","rootEl","mutationBuffer","mutationObserverCtor","MutationObserver","__rrMutationObserver","angularZoneSymbol","Zone","__symbol__","observer","onMutation","observe","attributeOldValue","characterData","characterDataOldValue","childList","subtree","initScrollObserver","_ref8","scrollCb","updatePosition","scrollEl","scrollingElement","sampling","scroll","wrapEventWithUserTriggeredFlag","v","userTriggered","INPUT_TAGS","lastInputValueMap","getNestedCSSRulePositions","childRule","hasNestedCSSRule","parentRule","CSSGroupingRule","CSSMediaRule","CSSSupportsRule","CSSConditionRule","unshift","parentStyleSheet","recurse","initObservers","hooks","currentWindow","defaultView","mousemoveCb","mouseInteractionCb","viewportResizeCb","inputCb","mediaInteractionCb","styleSheetRuleCb","styleDeclarationCb","canvasMutationCb","fontCb","mutation","mousemove","mouseInteraction","viewportResize","mediaInteaction","styleSheetRule","styleDeclaration","canvasMutation","font","mergeHooks","lastH","lastW","updateDimension","_step4","mutationObserver","mousemoveHandler","_ref5","timeBaseline","callbackThreshold","mousemoveCallback","positions","wrappedCb","totalOffset","timeOffset","_ref6","clientX","clientY","DragEvent","Drag","MouseEvent","MouseMove","TouchMove","h","initMoveObserver","mouseInteractionHandler","_ref7","disableMap","Number","eventKey","getHandler","initMouseInteractionObserver","scrollHandler","viewportResizeHandler","inputHandler","_ref10","ignoreClass","ignoreSelector","userTriggeredOnInput","eventHandler","isTrusted","parentElement","isChecked","cbWithDedup","querySelectorAll","lastInputValue","propertyDescriptor","HTMLInputElement","hookProperties","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","initInputObserver","mediaInteractionHandler","_ref17","volume","muted","media","initMediaInteractionObserver","styleSheetObserver","_ref11","_ref12","CSSStyleSheet","insertRule","thisArg","argumentsList","ownerNode","deleteRule","supportedNestedCSSRuleTypes","canMonkeyPatchNestedCSSRule","unmodifiedFunctions","entries","_ref13","typeKey","_ref14","initStyleSheetObserver","styleDeclarationObserver","_ref15","_ref16","setProperty","CSSStyleDeclaration","priority","removeProperty","remove","initStyleDeclarationObserver","fontObserver","collectFonts","_ref18","fontMap","originalFontFace","FontFace","family","descriptors","fontFace","fontSource","restoreHandler","fonts","initFontObserver","pluginHandlers","_iterator4","plugins","plugin","disconnect","IframeManager","iframes","_proto3","addLoadListener","loadListener","isAttachIframe","ShadowDomManager","restorePatches","manager","HTMLElement","ownerDocument","_proto4","iframeElement","restorePatch","lookup","charCodeAt","webGLVarMap","saveWebGLVar","isInstanceOfWebGLObject","list","contextMap","variableListFor","serializeArg","Float32Array","Float64Array","Int32Array","Uint16Array","Int16Array","Int8Array","Uint8ClampedArray","rr_type","ArrayBuffer","base64","arraybuffer","bytes","DataView","byteOffset","byteLength","HTMLImageElement","ImageData","serializeArgs","supportedWebGLConstructorNames","patchGLPrototype","_step6","_loop2","recordArgs","hookHandler","setter","_iterator6","getOwnPropertyNames","wrappedEmit","takeFullSnapshot","CanvasManager","_proto5","pendingCanvasMutations","rafStamps","latestId","invokeId","initCanvasMutationObserver","resetObservers","startRAFTimestamping","startPendingCanvasMutationFlusher","canvasContextReset","HTMLCanvasElement","contextType","initCanvasContextObserver","canvas2DReset","_step5","_loop","CanvasRenderingContext2D","imgd","pix","_iterator5","initCanvas2DMutationObserver","canvasWebGL1and2Reset","WebGLRenderingContext","WebGL","WebGL2RenderingContext","WebGL2","initCanvasWebGLMutationObserver","flushPendingCanvasMutations","_this7","setLatestRAFTimestamp","_this8","flushPendingCanvasMutationFor","valuesWithType","rest","t","getOwnPropertySymbols","propertyIsEnumerable","__rest","commands","wrapEvent","child","checkoutEveryNms","checkoutEveryNth","_options$blockClass","_options$blockSelecto","_options$unblockSelec","_options$ignoreClass","_options$ignoreSelect","_options$maskTextClas","_options$maskTextSele","_options$maskInputSel","_options$unmaskTextSe","_options$unmaskInputS","_options$inlineStyles2","_options$maskAllText","maskAllInputs","_maskInputOptions","_slimDOMOptions","packFn","_options$sampling","mousemoveWait","_options$recordCanvas2","_options$userTriggere","_options$collectFonts","_options$inlineImages2","_options$keepIframeSr2","lastFullSnapshotEvent","color","date","month","number","range","tel","time","week","textarea","select","radio","checkbox","NodeList","DOMTokenList","Node","incrementalSnapshotCount","isCheckout","FullSnapshot","IncrementalSnapshot","Mutation","_step7","_iterator7","eventProcessor","exceedCount","exceedTime","wrappedMutationEmit","wrappedScrollEmit","Scroll","wrappedCanvasMutationEmit","CanvasMutation","Meta","_snapshot","_ref4","_ref4$blockClass","_ref4$blockSelector","_ref4$unblockSelector","_ref4$maskTextClass","_ref4$maskTextSelecto","_ref4$unmaskTextSelec","_ref4$inlineStyleshee","_ref4$inlineImages","_ref4$recordCanvas","_ref4$maskInputSelect","_ref4$unmaskInputSele","_ref4$maskAllText","_ref4$maskAllInputs","_ref4$slimDOM","slimDOM","_ref4$keepIframeSrcFn","idNodeMap","snapshot","initialOffset","left","pageXOffset","top","pageYOffset","DomContentLoaded","MouseInteraction","ViewportResize","Input","MediaInteraction","StyleSheetRule","StyleDeclaration","Font","Plugin","Load","addBreadcrumbEvent","replay","triggerUserActivity","checkAndHandleExpiredSession","addUpdate","throttledAddEvent","Custom","tag","addCustomEvent","freezePage","getClickTargetNode","getTargetNode","isEventWithTarget","ClickDetector","_proto6","slowClickConfig","_addBreadcrumbEvent","_timeout","_multiClickTimeout","multiClickTimeout","_threshold","_scollTimeout","scrollTimeout","_replay","_ignoreSelector","_lastMutation","_lastScroll","_clicks","addListeners","_this9","nowInSeconds","cleanupWindowOpen","originalWindowOpen","clickHandler","_handleMultiClick","obs","_teardown","removeListeners","_checkClickTimeout","handleClick","SLOW_CLICK_TAGS","ignoreElement","isClickBreadcrumb","_getClick","newClick","clickBreadcrumb","clickCount","_scheduleCheckClicks","click","_this10","_checkClicks","_this11","timedOutClicks","mutationAfter","scrollAfter","actionTime","_i6","_timedOutClicks","_generateBreadcrumbs","hadScroll","hadMutation","isSlowClick","timeAfterClickMs","endReason","route","getCurrentRoute","metric","_this12","createBreadcrumb","ATTRIBUTES_TO_RECORD","getAttributesToRecord","normalizedKey","getBaseDomBreadcrumb","NAVIGATION_ENTRY_KEYS","isNavigationEntryEqual","every","timestampToMs","EventBufferArray","_proto7","events","_totalSize","destroy","addEvent","_addEvent","_callee","eventSize","_context2","EventBufferSizeExceededError","_x","_this13","eventsRet","getEarliestTimestamp","WorkerHandler","worker","_worker","_proto8","ensureReady","_this14","_ensureReadyPromise","_ref19","success","once","terminate","postMessage","_this15","_getAndIncrementId","_ref20","EventBufferCompressionWorker","_proto9","_earliestTimestamp","_sendEventToWorker","_finishRequest","_finishRequest2","_callee2","_context3","EventBufferProxy","_fallback","_compression","_used","_ensureWorkerIsLoadedPromise","_ensureWorkerIsLoaded","_proto10","_finish","_callee3","_context4","ensureWorkerIsLoaded","_ensureWorkerIsLoaded2","_callee4","_context5","t0","_switchToCompressionWorker","_switchToCompressionWorker2","_callee5","addEventPromises","_iterator8","_step8","_context6","all","hasEvents","_Error","isExpired","initialTime","expiry","targetTime","isSessionExpired","timeouts","maxSessionLife","lastActivity","sessionIdleExpire","isSampled","sampleRate","saveSession","sessionStorage","setItem","segmentId","sampled","shouldRefresh","createSession","_ref22","sessionSampleRate","allowBuffering","_ref22$stickySession","stickySession","getSessionSampleType","_ref23","sessionStringFromStorage","getItem","parse","fetchSession","isCustomEvent","_x2","_x3","_x4","_addEvent2","_callee10","replayOptions","eventAfterPossibleCallback","_context11","eventBuffer","isPaused","sessionIdlePause","beforeAddRecordingEvent","recordDroppedEvent","isTransactionEvent","handleAfterSendEvent","enforceStatusCode","transport","getTransport","send","__sentry__baseTransport__","isBaseTransportSend","sendResponse","statusCode","trace_id","traceIds","errorIds","recordingMode","replayId","sendBufferedReplayOrFlush","createPerformanceSpans","_ref24","start","end","op","description","addNetworkBreadcrumb","isEnabled","getDsn","_isSentryRequest","OBJ","OBJ_KEY","OBJ_KEY_STR","OBJ_VAL","OBJ_VAL_STR","OBJ_VAL_COMPLETED","ARR","ARR_VAL","ARR_VAL_STR","ARR_VAL_COMPLETED","ALLOWED_PRIMITIVES","_evaluateJsonPos","json","curStep","char","_isEscaped","_handleObj","_handleArr","_handleColon","_handleComma","_handleObjClose","_handleArrClose","_handleQuote","fixJson","incompleteJson","lastPos","lastStep","startPos","lastIndexOf","_maybeFixIncompleteObjValue","_findLastArrayDelimiter","_maybeFixIncompleteArrValue","_fixLastStep","completeJson","evaluateJson","getBodySize","URLSearchParams","FormData","formDataStr","_serializeFormData","Blob","size","parseContentLengthHeader","getBodyString","makeNetworkReplayBreadcrumb","buildSkippedNetworkRequestOrResponse","bodySize","_meta","warnings","buildNetworkRequestOrResponse","_normalizeNetworkBody","first","last","exceedsSizeLimit","e3","normalizeNetworkBody","normalizedBody","getAllowedHeaders","allowedHeaders","filteredHeaders","formData","urlMatches","urls","fullUrl","baseURI","fixedUrl","URL","getFullUrl","_captureFetchBreadcrumbToReplay","_callee11","_context12","_prepareFetchData","_x8","_x9","_x10","_prepareFetchData2","_callee12","_breadcrumb$data2","_breadcrumb$data2$sta","requestBodySize","responseBodySize","captureDetails","_context13","request_body_size","response_body_size","networkDetailAllowUrls","_getRequestInfo","_getResponseInfo","_ref25","networkCaptureBodies","networkRequestHeaders","getHeadersFromOptions","_getFetchRequestArgBody","_x11","_x12","_x13","_x14","_getResponseInfo2","_callee13","_ref26","networkResponseHeaders","bodyText","_context14","getAllHeaders","_parseFetchBody","_x15","_parseFetchBody2","_callee14","_context15","allHeaders","_captureXhrBreadcrumbToReplay","_callee15","_context16","_prepareXhrData","_breadcrumb$data","_breadcrumb$data$stat","getAllResponseHeaders","_line$split","getResponseHeaders","responseText","handleNetworkBreadcrumbs","_replay$getOptions","_isXhrBreadcrumb","_isXhrHint","reqSize","resSize","getResponseHeader","enrichXhrBreadcrumb","_x16","_x17","_x18","captureXhrBreadcrumbToReplay","_isFetchBreadcrumb","_isFetchHint","enrichFetchBreadcrumb","_x5","_x6","_x7","captureFetchBreadcrumbToReplay","beforeAddNetworkBreadcrumb","handleFetch","handleFetchSpanListener","handleXhr","handleXhrSpanListener","e2","_LAST_BREADCRUMB","hasHooks","addMemoryEntry","_x19","_addMemoryEntry","_callee16","_context17","memoryEntry","memory","jsHeapSizeLimit","totalJSHeapSize","usedJSHeapSize","ENTRY_TYPES","_ENTRY_TYPES","entryType","initiatorType","responseEnd","startTime","decodedBodySize","encodedBodySize","responseStatus","transferSize","getAbsoluteTime","paint","navigation","domComplete","domContentLoadedEventStart","domContentLoadedEventEnd","domInteractive","loadEventStart","loadEventEnd","redirectCount","startTimeOrNavigationActivation","navEntry","getEntriesByType","activationStart","createPerformanceEntry","createReplayEnvelope","replayEvent","recordingData","prepareRecordingData","_ref27","payloadWithSequence","replayHeaders","sequence","prepareReplayEvent","_x20","_prepareReplayEvent","_callee17","_ref28","preparedEvent","metadata","_ref36","_context18","_integrations","platform","getSdkMetadata","sendReplayRequest","_x21","_sendReplayRequest","_callee18","_ref29","segment_id","eventContext","preparedRecordingData","initialTimestamp","baseEvent","_context19","replay_start_timestamp","error_ids","trace_ids","replay_id","replay_type","cause","TransportStatusCodeError","_Error2","sendReplay","_x22","_x23","_sendReplay","_callee20","replayData","retryConfig","_context21","count","interval","_retryCount","_callee19","_context20","THROTTLED","ReplayContainer","_proto11","_ref30","maxCount","durationSeconds","counter","isThrottled","_this16","recordingOptions","__init7","__init8","__init9","__init10","__init11","__init12","__init13","__init14","__init15","__init16","__init17","__init18","_recordingOptions","_debouncedFlush","callbackReturnValue","timerId","maxTimerId","maxWait","invokeFunc","cancelTimers","debounced","cancel","flush","debounce","_flush","flushMinDelay","flushMaxDelay","_throttledAddEvent","floor","_cleanup","wasThrottled","_this$getOptions","slowClickTimeout","slowClickIgnoreSelectors","clickDetector","performanceEvents","_performanceObserver","_flushLock","_lastActivity","_isEnabled","_isPaused","_hasInitializedCoreListeners","_stopRecording","_context","initialUrl","initializeSampling","_this$_options","errorSampleRate","_loadAndCheckSession","_initializeRecording","_handleException","previousSessionId","startBuffering","startRecording","hadFirstEvent","_isCheckout","setInitialState","useCompressionOption","useCompression","blockAllMedia","networkDetailHasUrls","networkRequestHasHeaders","networkResponseHasHeaders","createOptionsEvent","addSettingsEvent","earliestEvent","_experiments","delayFlushOnCheckout","conditionalFlush","cancelFlush","flushImmediate","_onMutationHandler","stopRecording","_stop","_callee6","_context7","_removeListeners","force","removeItem","deleteSession","_x24","pause","resume","_sendBufferedReplayOrFlush","_callee7","_temp","_ref31$continueRecord","continueRecording","activityTime","hasStoppedRecording","_context8","_updateUserActivity","_updateSessionActivity","_maybeSaveSession","_x25","cbResult","updateUserActivity","getSessionId","oldSessionId","_triggerFullSnapshot","urlPath","pathname","_clearContext","_this17","lastTransaction","_ref21","Worker","workerUrl","createObjectURL","createEventBuffer","_addListeners","_getSession3","currentSessionId","_handleVisibilityChange","_handleWindowBlur","_handleWindowFocus","_handleKeyboardEvent","newBreadcrumb","isTruncated","normalizedArgs","normalizedArg","fixedJson","normalizeConsoleBreadcrumb","handleScope","handleScopeListener","_getDomTarget","isClick","getDomTarget","handleDom","altKey","metaKey","ctrlKey","handleDomListener","handleHistory","handleHistorySpanListener","includeAfterSendEventHandling","afterSendHandler","isReplayEvent","isRrwebError","captureExceptions","isErrorEventSampled","shouldSampleForBufferEvent","handleGlobalEventListener","dsc","performanceObserver","PerformanceObserver","currentList","newList","_currentList$reduce","existingNavigationEntries","existingLcpEntries","existingEntries","newEntries","newNavigationEntries","newLcpEntry","newPerformanceEntries","getEntries","navigationEntry","buffered","setupPerformanceObserver","_this18","visibilityState","_doChangeToForegroundTasks","_doChangeToBackgroundTasks","_this19","_this20","_this21","shiftKey","isInputElement","hasModifierKey","isCharacterKey","getKeyboardBreadcrumb","handleKeyboardEvent","expired","_createCustomBreadcrumb","checkout","_this22","_addPerformanceEntries","createPerformanceEntries","_updateInitialTimestampFromEventBuffer","_popEventContext","_runFlush","_runFlush2","_callee8","_context9","_this23","_ref32","_callee9","_temp2","_ref33$force","_context10","_x26","_this24","mutationLimit","overMutationLimit","mutationBreadcrumbLimit","getOption","selectors","defaultSelectors","deprecatedClassOption","deprecatedSelectorOption","deprecatedSelectors","allSelectors","isBrowser","MEDIA_SELECTORS","DEFAULT_NETWORK_HEADERS","_initialized","Replay","_proto12","_temp3","_ref35","_ref35$flushMinDelay","_ref35$flushMaxDelay","_ref35$stickySession","_ref35$useCompression","_ref35$_experiments","_ref35$maskAllText","_ref35$maskAllInputs","_ref35$blockAllMedia","_ref35$mutationBreadc","_ref35$mutationLimit","_ref35$slowClickTimeo","_ref35$slowClickIgnor","_ref35$networkDetailA","_ref35$networkCapture","_ref35$networkRequest","_ref35$networkRespons","_ref35$mask","mask","_ref35$unmask","unmask","_ref35$block","block","_ref35$unblock","unblock","_ref35$ignore","ignore","maskFn","password","_ref34","maskSelector","unmaskSelector","getPrivacyOptions","_initialOptions","_getMergedNetworkHeaders","_isInitialized","_this25","_setup","_initialize","getReplayId","finalOptions","initialOptions","opt","replaysSessionSampleRate","replaysOnErrorSampleRate","loadReplayOptionsFromClient","SDK_VERSION","SentryError","logLevel","ReferenceError","_assertThisInitialized","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","_metadata","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","encodeURIComponent","_encodedAuth","installedIntegrations","setupIntegration","integrationIndex","BaseClient","_dsn","_transport","transportOptions","_integrationsInitialized","_numProcessing","_outcomes","_hooks","_process","eventFromException","_captureEvent","promisedEvent","eventFromMessage","sendSession","_isClientDoneProcessing","clientFinished","transportFlushed","close","enabled","getIntegrationById","integrationId","addIntegration","sendEvent","newItem","env","eventType","packages","enhanceEventWithSdkInfo","envelopeHeaders","createEventEnvelope","promise","_sendEnvelope","createSessionEnvelope","_event","sendClientReports","hook","_updateSessionFromEvent","crashed","errored","exceptions","sessionNonTerminal","ticked","clearInterval","_prepareEvent","_processEvent","finalEvent","isTransaction","beforeSendLabel","dataCategory","__sentry__","beforeSend","beforeSendTransaction","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","transactionInfo","transaction_info","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","sdkSource","SENTRY_SDK_SOURCE","_flushOutcomes","breadcrumbIntegration","captureUserFeedback","feedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","discarded_events","DEFAULT_RETRY_AFTER","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","task","$","taskProducer","drain","capturedSetTimeout","makePromiseBuffer","bufferSize","rateLimits","filteredEnvelopeItems","limits","envelopeItemDataCategory","disabledUntil","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","updatedRateLimits","rateLimitHeader","retryAfterHeader","_limit$split","retryAfter","categories","headerDelay","delay","headerDate","parseRetryAfterHeader","updateRateLimits","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","lastFrameFunction","firstFrameFunction","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","Dedupe","currentEvent","previousEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","_previousEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","injectionPoint","Integrations","CaptureConsole","levels","_levels","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","tracesSampleRate","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"forum.replay.js","mappings":";wCAYO,SAASA,IAGd,QCU4C,oBAA9BC,2BAA+CA,4BDRsB,qBAAjFC,OAAOC,UAAUC,SAASC,KAAwB,oBAAZC,QAA0BA,QAAU,EAE9E,6CEnBA,IAAIC,EAAUC,EAAAA,KAAAA,QACd,SAASC,IACP,aACAC,EAAOC,QAAUF,EAAsB,WACrC,OAAOE,CACT,EAAGD,EAAOC,QAAQC,YAAa,EAAMF,EAAOC,QAAiB,QAAID,EAAOC,QACxE,IAAIA,EAAU,CAAC,EACbE,EAAKX,OAAOC,UACZW,EAASD,EAAGE,eACZC,EAAiBd,OAAOc,gBAAkB,SAAUC,EAAKC,EAAKC,GAC5DF,EAAIC,GAAOC,EAAKC,KAClB,EACAC,EAAU,mBAAqBC,OAASA,OAAS,CAAC,EAClDC,EAAiBF,EAAQG,UAAY,aACrCC,EAAsBJ,EAAQK,eAAiB,kBAC/CC,EAAoBN,EAAQO,aAAe,gBAC7C,SAASC,EAAOZ,EAAKC,EAAKE,GACxB,OAAOlB,OAAOc,eAAeC,EAAKC,EAAK,CACrCE,MAAOA,EACPU,YAAY,EACZC,cAAc,EACdC,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AdD,EAAIlrF,EAAM6E,OAANqmF,EAAYjmF,cAC7BjF,EAAM6E,KAAKI,MAGhBgmF,EAAOG,cAAgBprF,EAAMvM,WAC/Bq2F,GAAiB,CAAE5pF,QAASF,EAAMG,SAAU0E,KAAMkmF,OAAOM,YAAY,UAGhErrF,CACT,EAEAsrF,iBAAkBL,EAAOK,iBACzBnP,yBAA0B8O,EAAO9O,yBACjCC,yBAA0B6O,EAAO7O,yBAEjCtlE,aAAc,GAAA3e,OAAI2e,GAAc,CAAAm0E,EAAOM,gBAAkB,IAAIZ,KAAkBnvF,OAAOhC,UACtF,EAE4BqQ,cAAAA,GAAeigF,iBAAAA,IAE/Cr0F,OAAOs1F,OAAOM,YAAc,SAACG,QAAQ,IAARA,IAAAA,EAAW,YAEtC,IAAIC,EAAW,CAAC,EAGhB,GAAIrlE,IAAK,KAAAslE,EAGoCC,EAFrC9mF,EAAkB,OAAd6mF,EAAGtlE,IAAAA,cAAW,EAAXslE,EAAa7mF,KAEtBuhB,IAAAA,SAAevhB,GAAqB,GAAbA,EAAKhQ,OACtB82F,EAAG,CACT5mF,WAAY,WACZlQ,GAAIgQ,EAAKhQ,OACR22F,GAAW3mF,EAAKK,WAHnBumF,EAG6BE,EAGxBvlE,IAAAA,KAAS,6BACZqlE,EAASxmF,MAAQJ,EAAKI,UAEfmhB,IAAAA,KAASxhB,SAAsC,GAA3BwhB,IAAAA,KAASxhB,QAAQgnF,SAC9CH,EAAW,CACT52F,GAAIuxB,IAAAA,KAASxhB,QAAQgnF,QAG3B,CAEA,OAAOH,CACT,EAEArlE,IAAAA,aAAiBhf,IAAI,cAAc,WACjCyC,KAAgBuF,QAAQ27E,OAAOM,cACjC","sources":["webpack://@fof/sentry/../../src/node.ts","webpack://@fof/sentry/../../src/env.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/regeneratorRuntime.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/typeof.js","webpack://@fof/sentry/./node_modules/@babel/runtime/regenerator/index.js","webpack://@fof/sentry/webpack/bootstrap","webpack://@fof/sentry/webpack/runtime/compat get default export","webpack://@fof/sentry/webpack/runtime/define property getters","webpack://@fof/sentry/webpack/runtime/global","webpack://@fof/sentry/webpack/runtime/harmony module decorator","webpack://@fof/sentry/webpack/runtime/hasOwnProperty shorthand","webpack://@fof/sentry/webpack/runtime/make namespace object","webpack://@fof/sentry/external root \"flarum.core.compat['forum/app']\"","webpack://@fof/sentry/../../src/debug-build.ts","webpack://@fof/sentry/../../src/worldwide.ts","webpack://@fof/sentry/../../src/logger.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://@fof/sentry/../../src/is.ts","webpack://@fof/sentry/../../src/browser.ts","webpack://@fof/sentry/../../src/string.ts","webpack://@fof/sentry/../../src/object.ts","webpack://@fof/sentry/../../src/misc.ts","webpack://@fof/sentry/../../src/syncpromise.ts","webpack://@fof/sentry/../../src/eventProcessors.ts","webpack://@fof/sentry/../../src/time.ts","webpack://@fof/sentry/../../src/constants.ts","webpack://@fof/sentry/../../src/session.ts","webpack://@fof/sentry/../../src/stacktrace.ts","webpack://@fof/sentry/../../src/normalize.ts","webpack://@fof/sentry/../../src/memo.ts","webpack://@fof/sentry/../../../src/utils/spanUtils.ts","webpack://@fof/sentry/../../../src/utils/prepareEvent.ts","webpack://@fof/sentry/../../src/exports.ts","webpack://@fof/sentry/../../../src/utils/getRootSpan.ts","webpack://@fof/sentry/../../../src/tracing/dynamicSamplingContext.ts","webpack://@fof/sentry/../../../src/utils/applyScopeDataToEvent.ts","webpack://@fof/sentry/../../src/scope.ts","webpack://@fof/sentry/../../src/version.ts","webpack://@fof/sentry/../../src/hub.ts","webpack://@fof/sentry/../../src/integration.ts","webpack://@fof/sentry/../../../src/integrations/inboundfilters.ts","webpack://@fof/sentry/../../../src/integrations/functiontostring.ts","webpack://@fof/sentry/../../../src/helpers.ts","webpack://@fof/sentry/../../../../src/integrations/trycatch.ts","webpack://@fof/sentry/../../../src/instrument/_handlers.ts","webpack://@fof/sentry/../../../src/instrument/globalError.ts","webpack://@fof/sentry/../../../src/instrument/globalUnhandledRejection.ts","webpack://@fof/sentry/../../../src/eventbuilder.ts","webpack://@fof/sentry/../../../../src/integrations/globalhandlers.ts","webpack://@fof/sentry/../../../src/instrument/console.ts","webpack://@fof/sentry/../../../src/instrument/dom.ts","webpack://@fof/sentry/../../../src/instrument/xhr.ts","webpack://@fof/sentry/../../src/supports.ts","webpack://@fof/sentry/../../../src/instrument/fetch.ts","webpack://@fof/sentry/../../../src/vendor/supportsHistory.ts","webpack://@fof/sentry/../../../src/instrument/history.ts","webpack://@fof/sentry/../../src/severity.ts","webpack://@fof/sentry/../../src/url.ts","webpack://@fof/sentry/../../../../src/integrations/breadcrumbs.ts","webpack://@fof/sentry/../../src/aggregate-errors.ts","webpack://@fof/sentry/../../../../src/integrations/linkederrors.ts","webpack://@fof/sentry/../../../../src/integrations/httpcontext.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/typeof.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/createClass.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/toPrimitive.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://@fof/sentry/../../../src/buildPolyfills/_optionalChain.ts","webpack://@fof/sentry/../../../src/utils/isSentryRequestUrl.ts","webpack://@fof/sentry/../../src/dsn.ts","webpack://@fof/sentry/../../src/ratelimit.ts","webpack://@fof/sentry/../../src/isBrowser.ts","webpack://@fof/sentry/../../../src/common/debug-build.ts","webpack://@fof/sentry/../../../src/browser/types.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getNavigationEntry.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getActivationStart.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/onHidden.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getVisibilityWatcher.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/observe.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getLCP.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/initMetric.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/generateUniqueID.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/bindReporter.ts","webpack://@fof/sentry/../../../src/browser/instrument.ts","webpack://@fof/sentry/../../../src/constants.ts","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js","webpack://@fof/sentry/../../../src/buildPolyfills/_nullishCoalesce.ts","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/index.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js","webpack://@fof/sentry/../../../src/types/rrweb.ts","webpack://@fof/sentry/../../../src/util/timestamp.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/addBreadcrumbEvent.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/domUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/onWindowOpen.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleClick.ts","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb-snapshot/es/rrweb-snapshot.js","webpack://@fof/sentry/../../../src/util/createBreadcrumb.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/getAttributesToRecord.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleDom.ts","webpack://@fof/sentry/../../../src/util/createPerformanceEntries.ts","webpack://@fof/sentry/../../../src/coreHandlers/performanceObserver.ts","webpack://@fof/sentry/../../../src/debug-build.ts","webpack://@fof/sentry/../../../src/util/log.ts","webpack://@fof/sentry/../../../src/eventBuffer/error.ts","webpack://@fof/sentry/../../../src/eventBuffer/EventBufferArray.ts","webpack://@fof/sentry/../../../src/eventBuffer/WorkerHandler.ts","webpack://@fof/sentry/../../../src/eventBuffer/EventBufferCompressionWorker.ts","webpack://@fof/sentry/../../../src/eventBuffer/EventBufferProxy.ts","webpack://@fof/sentry/../../../src/util/hasSessionStorage.ts","webpack://@fof/sentry/../../../src/util/isSampled.ts","webpack://@fof/sentry/../../../src/session/Session.ts","webpack://@fof/sentry/../../../src/session/saveSession.ts","webpack://@fof/sentry/../../../src/session/createSession.ts","webpack://@fof/sentry/../../../src/util/isExpired.ts","webpack://@fof/sentry/../../../src/util/isSessionExpired.ts","webpack://@fof/sentry/../../../src/session/shouldRefreshSession.ts","webpack://@fof/sentry/../../../src/session/loadOrCreateSession.ts","webpack://@fof/sentry/../../../src/session/fetchSession.ts","webpack://@fof/sentry/../../../src/util/addEvent.ts","webpack://@fof/sentry/../../../src/util/eventUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleAfterSendEvent.ts","webpack://@fof/sentry/../../../src/util/createPerformanceSpans.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/addNetworkBreadcrumb.ts","webpack://@fof/sentry/../../../src/util/shouldFilterRequest.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/networkUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/fetchUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/xhrUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleNetworkBreadcrumbs.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleFetch.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleXhr.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleScope.ts","webpack://@fof/sentry/../../../src/util/addGlobalListeners.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleHistory.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleGlobalEvent.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/addFeedbackBreadcrumb.ts","webpack://@fof/sentry/../../../src/util/isRrwebError.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/shouldSampleForBufferEvent.ts","webpack://@fof/sentry/../../src/baseclient.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleBeforeSendEvent.ts","webpack://@fof/sentry/../../../src/util/addMemoryEntry.ts","webpack://@fof/sentry/../../../src/util/handleRecordingEmit.ts","webpack://@fof/sentry/../../../src/util/createReplayEnvelope.ts","webpack://@fof/sentry/../../src/envelope.ts","webpack://@fof/sentry/../../../src/util/prepareRecordingData.ts","webpack://@fof/sentry/../../../src/util/prepareReplayEvent.ts","webpack://@fof/sentry/../../../src/util/sendReplayRequest.ts","webpack://@fof/sentry/../../../src/util/sendReplay.ts","webpack://@fof/sentry/../../../src/util/throttle.ts","webpack://@fof/sentry/../../../src/replay.ts","webpack://@fof/sentry/../../../src/util/debounce.ts","webpack://@fof/sentry/../../../src/session/clearSession.ts","webpack://@fof/sentry/../../src/semanticAttributes.ts","webpack://@fof/sentry/../../../src/eventBuffer/index.ts","webpack://@fof/sentry/../../../../replay-worker/build/npm/esm/index.js","webpack://@fof/sentry/../../../../replay-worker/build/npm/esm/worker.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleKeyboardEvent.ts","webpack://@fof/sentry/../../../src/util/getPrivacyOptions.ts","webpack://@fof/sentry/../../../src/integration.ts","webpack://@fof/sentry/../../../src/util/maskAttribute.ts","webpack://@fof/sentry/../../src/error.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://@fof/sentry/../../src/api.ts","webpack://@fof/sentry/../../../src/metrics/envelope.ts","webpack://@fof/sentry/../../../src/metrics/utils.ts","webpack://@fof/sentry/../../../src/client.ts","webpack://@fof/sentry/../../../src/utils/sdkMetadata.ts","webpack://@fof/sentry/../../../src/userfeedback.ts","webpack://@fof/sentry/../../src/clientreport.ts","webpack://@fof/sentry/../../../src/transports/base.ts","webpack://@fof/sentry/../../src/promisebuffer.ts","webpack://@fof/sentry/../../../../src/transports/utils.ts","webpack://@fof/sentry/../../../../src/transports/fetch.ts","webpack://@fof/sentry/../../../src/stack-parsers.ts","webpack://@fof/sentry/../../../../src/integrations/dedupe.ts","webpack://@fof/sentry/../../../src/sdk.ts","webpack://@fof/sentry/../../../src/captureconsole.ts","webpack://@fof/sentry/./src/forum/index.js"],"sourcesContent":["/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\nimport { isBrowserBundle } from './env';\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-expect-error __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\n","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = (module) => {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: () => {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","export const DEFAULT_ENVIRONMENT = 'production';\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // 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)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial | EventHint): hint is Partial {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","export const SDK_VERSION = '7.119.1';\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n IntegrationFnResult,\n Options,\n} from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { addGlobalEventProcessor } from './eventProcessors';\nimport { getClient } from './exports';\nimport { getCurrentHub } from './hub';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Pick): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1) {\n // eslint-disable-next-line deprecation/deprecation\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (client.on && typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (client.addEventProcessor && typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client || !client.addIntegration) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Convert a new integration function to the legacy class syntax.\n * In v8, we can remove this and instead export the integration functions directly.\n *\n * @deprecated This will be removed in v8!\n */\nexport function convertIntegrationFnToClass(\n name: string,\n fn: Fn,\n): IntegrationClass {\n return Object.assign(\n function ConvertedIntegration(...args: Parameters): Integration {\n return fn(...args);\n },\n { id: name },\n ) as unknown as IntegrationClass;\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration(fn: Fn): (...args: Parameters) => IntegrationFnResult {\n return fn;\n}\n","import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/,\n /^Cannot redefine property: googletag$/,\n];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options: Partial = {}) => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\n/**\n * Inbound filters configurable by the user.\n * @deprecated Use `inboundFiltersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const InboundFilters = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n inboundFiltersIntegration,\n) as IntegrationClass void }> & {\n new (\n options?: Partial<{\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n }>,\n ): Integration;\n};\n\nfunction _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if (DEBUG_BUILD && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","import type { Client, Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\nimport { getClient } from '../exports';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nlet originalFunctionToString: () => void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * @deprecated Use `functionToStringIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const FunctionToString = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n functionToStringIntegration,\n) as IntegrationClass void }>;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type FunctionToString = typeof FunctionToString;\n","import type { browserTracingIntegration } from '@sentry-internal/tracing';\nimport { BrowserTracing } from '@sentry-internal/tracing';\nimport { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Integration, Mechanism, WrappedFunction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n *\n * @deprecated This type will be removed in the next major version of the Sentry SDK. `showReportDialog` will still be around, however the `eventId` option will now be required.\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n /** Callback after reportDialog closed */\n onClose?(this: void): void;\n}\n\n/**\n * This is a slim shim of `browserTracingIntegration` for the CDN bundles.\n * Since the actual functional integration uses a different code from `BrowserTracing`,\n * we want to avoid shipping both of them in the CDN bundles, as that would blow up the size.\n * Instead, we provide a functional integration with the same API, but the old implementation.\n * This means that it's not possible to register custom routing instrumentation, but that's OK for now.\n * We also don't expose the utilities for this anyhow in the CDN bundles.\n * For users that need custom routing in CDN bundles, they have to continue using `new BrowserTracing()` until v8.\n */\nexport function bundleBrowserTracingIntegration(\n options: Parameters[0] = {},\n): Integration {\n // Migrate some options from the old integration to the new one\n // eslint-disable-next-line deprecation/deprecation\n const opts: ConstructorParameters[0] = options;\n\n if (typeof options.markBackgroundSpan === 'boolean') {\n opts.markBackgroundTransactions = options.markBackgroundSpan;\n }\n\n if (typeof options.instrumentPageLoad === 'boolean') {\n opts.startTransactionOnPageLoad = options.instrumentPageLoad;\n }\n\n if (typeof options.instrumentNavigation === 'boolean') {\n opts.startTransactionOnLocationChange = options.instrumentNavigation;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return new BrowserTracing(opts);\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'TryCatch';\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\nconst _browserApiErrorsIntegration = ((options: Partial = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n * @deprecated Use `browserApiErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const TryCatch = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n browserApiErrorsIntegration,\n) as IntegrationClass & {\n new (options?: {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n }): Integration;\n};\n\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: VoidFunction,): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n","import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import { getClient } from '@sentry/core';\nimport type {\n Event,\n EventHint,\n Exception,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isParameterizedString,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const client = getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n message: ParameterizedString,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception: Record,\n { isUnhandledRejection }: { isUnhandledRejection?: boolean },\n): string {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n try {\n const prototype: Prototype | null = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { captureEvent, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Primitive,\n StackParser,\n} from '@sentry/types';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record;\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options: Partial = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\n/**\n * Global handlers.\n * @deprecated Use `globalHandlersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const GlobalHandlers = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n globalHandlersIntegration,\n) as IntegrationClass void }> & {\n new (options?: Partial): Integration;\n};\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e as unknown);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = error as any;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n return e.reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n return e.detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable max-lines */\nimport { addBreadcrumb, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event as SentryEvent,\n HandlerDataConsole,\n HandlerDataDom,\n HandlerDataFetch,\n HandlerDataHistory,\n HandlerDataXhr,\n Integration,\n IntegrationClass,\n IntegrationFn,\n} from '@sentry/types';\nimport type {\n Breadcrumb,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n SENTRY_XHR_DATA_KEY,\n addClickKeypressInstrumentationHandler,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n getComponentName,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options: Partial = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry && client.on) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Default Breadcrumbs instrumentations\n *\n * @deprecated Use `breadcrumbsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Breadcrumbs = convertIntegrationFnToClass(INTEGRATION_NAME, breadcrumbsIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (\n options?: Partial<{\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n }>,\n ): Integration;\n};\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client: Client): (handlerData: HandlerDataConsole) => void {\n return function _consoleBreadcrumb(handlerData: HandlerDataConsole): void {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record).target;\n}\n","import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Aggregrate linked errors in an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'HttpContext';\n\nconst _httpContextIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const httpContextIntegration = defineIntegration(_httpContextIntegration);\n\n/**\n * HttpContext integration collects information about HTTP request headers.\n * @deprecated Use `httpContextIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const HttpContext = convertIntegrationFnToClass(INTEGRATION_NAME, httpContextIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event) => void }\n>;\n","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type { GenericFunction } from './types';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nexport function _optionalChain(ops: unknown[]): unknown {\n let lastAccessLHS: unknown = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] as string;\n const fn = ops[i + 1] as (intermediateValue: unknown) => unknown;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args: unknown[]) => (value as GenericFunction).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n","import type { Client, DsnComponents, Hub } from '@sentry/types';\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n *\n * TODO(v8): Remove Hub fallback type\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function isSentryRequestUrl(url: string, hubOrClient: Hub | Client | undefined): boolean {\n const client =\n hubOrClient && isHub(hubOrClient)\n ? // eslint-disable-next-line deprecation/deprecation\n hubOrClient.getClient()\n : hubOrClient;\n const dsn = client && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url: string, tunnel: string | undefined): boolean {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url: string, dsn: DsnComponents | undefined): boolean {\n return dsn ? url.includes(dsn.host) : false;\n}\n\nfunction removeTrailingSlash(str: string): string {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction isHub(hubOrClient: Hub | Client | undefined): hubOrClient is Hub {\n // eslint-disable-next-line deprecation/deprecation\n return (hubOrClient as Hub).getClient !== undefined;\n}\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type { DataCategory, TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = Date.now()): boolean {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import { isNodeEnv } from './node';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n return (\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (GLOBAL_OBJ as any).process !== undefined && ((GLOBAL_OBJ as any).process as ElectronProcess).type === 'renderer'\n );\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ &\n // document is not available in all browser environments (webworkers). We make it optional so you have to explicitly check for it\n Omit &\n Partial>;\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document!.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): void => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n if (WINDOW.document && WINDOW.document.visibilityState) {\n firstHiddenTime = WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n }\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, stopListening, { once: true, capture: true });\n }\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if ((WINDOW.document && WINDOW.document.prerendering) || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","import { getFunctionName, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { onCLS } from './web-vitals/getCLS';\nimport { onFID } from './web-vitals/getFID';\nimport { onINP } from './web-vitals/getINP';\nimport { onLCP } from './web-vitals/getLCP';\nimport { observe } from './web-vitals/lib/observe';\nimport { onTTFB } from './web-vitals/onTTFB';\n\ntype InstrumentHandlerTypePerformanceObserver =\n | 'longtask'\n | 'event'\n | 'navigation'\n | 'paint'\n | 'resource'\n | 'first-input';\n\ntype InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid' | 'ttfb' | 'inp';\n\n// We provide this here manually instead of relying on a global, as this is not available in non-browser environements\n// And we do not want to expose such types\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): Record;\n}\ninterface PerformanceEventTiming extends PerformanceEntry {\n processingStart: number;\n processingEnd: number;\n duration: number;\n cancelable?: boolean;\n target?: unknown | null;\n interactionId?: number;\n}\n\ninterface Metric {\n /**\n * The name of the metric (in acronym form).\n */\n name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';\n\n /**\n * The current value of the metric.\n */\n value: number;\n\n /**\n * The rating as to whether the metric value is within the \"good\",\n * \"needs improvement\", or \"poor\" thresholds of the metric.\n */\n rating: 'good' | 'needs-improvement' | 'poor';\n\n /**\n * The delta between the current value and the last-reported value.\n * On the first report, `delta` and `value` will always be the same.\n */\n delta: number;\n\n /**\n * A unique ID representing this particular metric instance. This ID can\n * be used by an analytics tool to dedupe multiple values sent for the same\n * metric instance, or to group multiple deltas together and calculate a\n * total. It can also be used to differentiate multiple different metric\n * instances sent from the same page, which can happen if the page is\n * restored from the back/forward cache (in that case new metrics object\n * get created).\n */\n id: string;\n\n /**\n * Any performance entries relevant to the metric value calculation.\n * The array may also be empty if the metric value was not based on any\n * entries (e.g. a CLS value of 0 given no layout shifts).\n */\n entries: PerformanceEntry[];\n\n /**\n * The type of navigation\n *\n * Navigation Timing API (or `undefined` if the browser doesn't\n * support that API). For pages that are restored from the bfcache, this\n * value will be 'back-forward-cache'.\n */\n navigationType: 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender';\n}\n\ntype InstrumentHandlerType = InstrumentHandlerTypeMetric | InstrumentHandlerTypePerformanceObserver;\n\ntype StopListening = undefined | void | (() => void);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentHandlerCallback = (data: any) => void;\n\ntype CleanupHandlerCallback = () => void;\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\nlet _previousCls: Metric | undefined;\nlet _previousFid: Metric | undefined;\nlet _previousLcp: Metric | undefined;\nlet _previousTtfb: Metric | undefined;\nlet _previousInp: Metric | undefined;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nexport function addClsInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nexport function addLcpInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nexport function addTtfbInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addFidInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addInpInstrumentationHandler(\n callback: (data: { metric: Omit & { entries: PerformanceEventTiming[] } }) => void,\n): CleanupHandlerCallback {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\nexport function addPerformanceInstrumentationHandler(\n type: 'event' | 'first-input',\n callback: (data: { entries: ((PerformanceEntry & { target?: unknown | null }) | PerformanceEventTiming)[] }) => void,\n): CleanupHandlerCallback;\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback;\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls(): StopListening {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentFid(): void {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp(): StopListening {\n return onLCP(metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n });\n}\n\nfunction instrumentTtfb(): StopListening {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp(): void {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type: InstrumentHandlerTypeMetric,\n callback: InstrumentHandlerCallback,\n instrumentFn: () => StopListening,\n previousValue: Metric | undefined,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n let stopListening: StopListening | undefined;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type: InstrumentHandlerTypePerformanceObserver): void {\n const options: PerformanceObserverInit = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type: InstrumentHandlerType,\n callback: InstrumentHandlerCallback,\n stopListening: StopListening,\n): CleanupHandlerCallback {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nexport const REPLAY_SESSION_KEY = 'sentryReplaySession';\nexport const REPLAY_EVENT_NAME = 'replay_event';\nexport const RECORDING_EVENT_NAME = 'replay_recording';\nexport const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nexport const SESSION_IDLE_PAUSE_DURATION = 300_000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nexport const SESSION_IDLE_EXPIRE_DURATION = 900_000; // 15 minutes in ms\n\n/** Default flush delays */\nexport const DEFAULT_FLUSH_MIN_DELAY = 5_000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nexport const DEFAULT_FLUSH_MAX_DELAY = 5_500;\n\n/* How long to wait for error checkouts */\nexport const BUFFER_CHECKOUT_TIME = 60_000;\n\nexport const RETRY_BASE_INTERVAL = 5000;\nexport const RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nexport const NETWORK_BODY_MAX_SIZE = 150_000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nexport const CONSOLE_ARG_MAX_SIZE = 5_000;\n\n/* Min. time to wait before we consider something a slow click. */\nexport const SLOW_CLICK_THRESHOLD = 3_000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nexport const SLOW_CLICK_SCROLL_TIMEOUT = 300;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nexport const REPLAY_MAX_EVENT_BUFFER_SIZE = 20_000_000; // ~20MB\n\n/** Replays must be min. 5s long before we send them. */\nexport const MIN_REPLAY_DURATION = 4_999;\n/* The max. allowed value that the minReplayDuration can be set to. */\nexport const MIN_REPLAY_DURATION_LIMIT = 15_000;\n\n/** The max. length of a replay. */\nexport const MAX_REPLAY_DURATION = 3_600_000; // 60 minutes in ms;\n\n/** Default attributes to be ignored when `maskAllText` is enabled */\nexport const DEFAULT_IGNORED_ATTRIBUTES = ['title', 'placeholder'];\n","var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute };\n","import { distanceToMatch, IGNORED_NODE, isShadowRoot, createMatchPredicate } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\r\n const options = { capture: true, passive: true };\r\n target.addEventListener(type, fn, options);\r\n return () => target.removeEventListener(type, fn, options);\r\n}\r\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\r\n '\\r\\n' +\r\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\r\n '\\r\\n' +\r\n 'or you can use record.mirror to access the mirror instance during recording.';\r\nlet _mirror = {\r\n map: {},\r\n getId() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return -1;\r\n },\r\n getNode() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return null;\r\n },\r\n removeNodeFromMap() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n has() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return false;\r\n },\r\n reset() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n};\r\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\r\n _mirror = new Proxy(_mirror, {\r\n get(target, prop, receiver) {\r\n if (prop === 'map') {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n }\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\nfunction throttle(func, wait, options = {}) {\r\n let timeout = null;\r\n let previous = 0;\r\n return function (...args) {\r\n const now = Date.now();\r\n if (!previous && options.leading === false) {\r\n previous = now;\r\n }\r\n const remaining = wait - (now - previous);\r\n const context = this;\r\n if (remaining <= 0 || remaining > wait) {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n }\r\n previous = now;\r\n func.apply(context, args);\r\n }\r\n else if (!timeout && options.trailing !== false) {\r\n timeout = setTimeout(() => {\r\n previous = options.leading === false ? 0 : Date.now();\r\n timeout = null;\r\n func.apply(context, args);\r\n }, remaining);\r\n }\r\n };\r\n}\r\nfunction hookSetter(target, key, d, isRevoked, win = window) {\r\n const original = win.Object.getOwnPropertyDescriptor(target, key);\r\n win.Object.defineProperty(target, key, isRevoked\r\n ? d\r\n : {\r\n set(value) {\r\n setTimeout(() => {\r\n d.set.call(this, value);\r\n }, 0);\r\n if (original && original.set) {\r\n original.set.call(this, value);\r\n }\r\n },\r\n });\r\n return () => hookSetter(target, key, original || {}, true);\r\n}\r\nfunction patch(source, name, replacement) {\r\n try {\r\n if (!(name in source)) {\r\n return () => {\r\n };\r\n }\r\n const original = source[name];\r\n const wrapped = replacement(original);\r\n if (typeof wrapped === 'function') {\r\n wrapped.prototype = wrapped.prototype || {};\r\n Object.defineProperties(wrapped, {\r\n __rrweb_original__: {\r\n enumerable: false,\r\n value: original,\r\n },\r\n });\r\n }\r\n source[name] = wrapped;\r\n return () => {\r\n source[name] = original;\r\n };\r\n }\r\n catch {\r\n return () => {\r\n };\r\n }\r\n}\r\nlet nowTimestamp = Date.now;\r\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\r\n nowTimestamp = () => new Date().getTime();\r\n}\r\nfunction getWindowScroll(win) {\r\n const doc = win.document;\r\n return {\r\n left: doc.scrollingElement\r\n ? doc.scrollingElement.scrollLeft\r\n : win.pageXOffset !== undefined\r\n ? win.pageXOffset\r\n : doc?.documentElement.scrollLeft ||\r\n doc?.body?.parentElement?.scrollLeft ||\r\n doc?.body?.scrollLeft ||\r\n 0,\r\n top: doc.scrollingElement\r\n ? doc.scrollingElement.scrollTop\r\n : win.pageYOffset !== undefined\r\n ? win.pageYOffset\r\n : doc?.documentElement.scrollTop ||\r\n doc?.body?.parentElement?.scrollTop ||\r\n doc?.body?.scrollTop ||\r\n 0,\r\n };\r\n}\r\nfunction getWindowHeight() {\r\n return (window.innerHeight ||\r\n (document.documentElement && document.documentElement.clientHeight) ||\r\n (document.body && document.body.clientHeight));\r\n}\r\nfunction getWindowWidth() {\r\n return (window.innerWidth ||\r\n (document.documentElement && document.documentElement.clientWidth) ||\r\n (document.body && document.body.clientWidth));\r\n}\r\nfunction closestElementOfNode(node) {\r\n if (!node) {\r\n return null;\r\n }\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n return el;\r\n}\r\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\r\n if (!node) {\r\n return false;\r\n }\r\n const el = closestElementOfNode(node);\r\n if (!el) {\r\n return false;\r\n }\r\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\r\n if (!checkAncestors) {\r\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\r\n return blockedPredicate(el) && !isUnblocked;\r\n }\r\n const blockDistance = distanceToMatch(el, blockedPredicate);\r\n let unblockDistance = -1;\r\n if (blockDistance < 0) {\r\n return false;\r\n }\r\n if (unblockSelector) {\r\n unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector));\r\n }\r\n if (blockDistance > -1 && unblockDistance < 0) {\r\n return true;\r\n }\r\n return blockDistance < unblockDistance;\r\n}\r\nfunction isSerialized(n, mirror) {\r\n return mirror.getId(n) !== -1;\r\n}\r\nfunction isIgnored(n, mirror) {\r\n return mirror.getId(n) === IGNORED_NODE;\r\n}\r\nfunction isAncestorRemoved(target, mirror) {\r\n if (isShadowRoot(target)) {\r\n return false;\r\n }\r\n const id = mirror.getId(target);\r\n if (!mirror.has(id)) {\r\n return true;\r\n }\r\n if (target.parentNode &&\r\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\r\n return false;\r\n }\r\n if (!target.parentNode) {\r\n return true;\r\n }\r\n return isAncestorRemoved(target.parentNode, mirror);\r\n}\r\nfunction legacy_isTouchEvent(event) {\r\n return Boolean(event.changedTouches);\r\n}\r\nfunction polyfill(win = window) {\r\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\r\n win.NodeList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\r\n win.DOMTokenList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if (!Node.prototype.contains) {\r\n Node.prototype.contains = (...args) => {\r\n let node = args[0];\r\n if (!(0 in args)) {\r\n throw new TypeError('1 argument is required');\r\n }\r\n do {\r\n if (this === node) {\r\n return true;\r\n }\r\n } while ((node = node && node.parentNode));\r\n return false;\r\n };\r\n }\r\n}\r\nfunction queueToResolveTrees(queue) {\r\n const queueNodeMap = {};\r\n const putIntoMap = (m, parent) => {\r\n const nodeInTree = {\r\n value: m,\r\n parent,\r\n children: [],\r\n };\r\n queueNodeMap[m.node.id] = nodeInTree;\r\n return nodeInTree;\r\n };\r\n const queueNodeTrees = [];\r\n for (const mutation of queue) {\r\n const { nextId, parentId } = mutation;\r\n if (nextId && nextId in queueNodeMap) {\r\n const nextInTree = queueNodeMap[nextId];\r\n if (nextInTree.parent) {\r\n const idx = nextInTree.parent.children.indexOf(nextInTree);\r\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\r\n }\r\n else {\r\n const idx = queueNodeTrees.indexOf(nextInTree);\r\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\r\n }\r\n continue;\r\n }\r\n if (parentId in queueNodeMap) {\r\n const parentInTree = queueNodeMap[parentId];\r\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\r\n continue;\r\n }\r\n queueNodeTrees.push(putIntoMap(mutation, null));\r\n }\r\n return queueNodeTrees;\r\n}\r\nfunction iterateResolveTree(tree, cb) {\r\n cb(tree.value);\r\n for (let i = tree.children.length - 1; i >= 0; i--) {\r\n iterateResolveTree(tree.children[i], cb);\r\n }\r\n}\r\nfunction isSerializedIframe(n, mirror) {\r\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\r\n}\r\nfunction isSerializedStylesheet(n, mirror) {\r\n return Boolean(n.nodeName === 'LINK' &&\r\n n.nodeType === n.ELEMENT_NODE &&\r\n n.getAttribute &&\r\n n.getAttribute('rel') === 'stylesheet' &&\r\n mirror.getMeta(n));\r\n}\r\nfunction getBaseDimension(node, rootIframe) {\r\n const frameElement = node.ownerDocument?.defaultView?.frameElement;\r\n if (!frameElement || frameElement === rootIframe) {\r\n return {\r\n x: 0,\r\n y: 0,\r\n relativeScale: 1,\r\n absoluteScale: 1,\r\n };\r\n }\r\n const frameDimension = frameElement.getBoundingClientRect();\r\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\r\n const relativeScale = frameDimension.height / frameElement.clientHeight;\r\n return {\r\n x: frameDimension.x * frameBaseDimension.relativeScale +\r\n frameBaseDimension.x,\r\n y: frameDimension.y * frameBaseDimension.relativeScale +\r\n frameBaseDimension.y,\r\n relativeScale,\r\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\r\n };\r\n}\r\nfunction hasShadowRoot(n) {\r\n return Boolean(n?.shadowRoot);\r\n}\r\nfunction getNestedRule(rules, position) {\r\n const rule = rules[position[0]];\r\n if (position.length === 1) {\r\n return rule;\r\n }\r\n else {\r\n return getNestedRule(rule.cssRules[position[1]].cssRules, position.slice(2));\r\n }\r\n}\r\nfunction getPositionsAndIndex(nestedIndex) {\r\n const positions = [...nestedIndex];\r\n const index = positions.pop();\r\n return { positions, index };\r\n}\r\nfunction uniqueTextMutations(mutations) {\r\n const idSet = new Set();\r\n const uniqueMutations = [];\r\n for (let i = mutations.length; i--;) {\r\n const mutation = mutations[i];\r\n if (!idSet.has(mutation.id)) {\r\n uniqueMutations.push(mutation);\r\n idSet.add(mutation.id);\r\n }\r\n }\r\n return uniqueMutations;\r\n}\r\nclass StyleSheetMirror {\r\n constructor() {\r\n this.id = 1;\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n }\r\n getId(stylesheet) {\r\n return this.styleIDMap.get(stylesheet) ?? -1;\r\n }\r\n has(stylesheet) {\r\n return this.styleIDMap.has(stylesheet);\r\n }\r\n add(stylesheet, id) {\r\n if (this.has(stylesheet))\r\n return this.getId(stylesheet);\r\n let newId;\r\n if (id === undefined) {\r\n newId = this.id++;\r\n }\r\n else\r\n newId = id;\r\n this.styleIDMap.set(stylesheet, newId);\r\n this.idStyleMap.set(newId, stylesheet);\r\n return newId;\r\n }\r\n getStyle(id) {\r\n return this.idStyleMap.get(id) || null;\r\n }\r\n reset() {\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n this.id = 1;\r\n }\r\n generateId() {\r\n return this.id++;\r\n }\r\n}\r\nfunction getShadowHost(n) {\r\n let shadowHost = null;\r\n if (n.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\r\n n.getRootNode().host)\r\n shadowHost = n.getRootNode().host;\r\n return shadowHost;\r\n}\r\nfunction getRootShadowHost(n) {\r\n let rootShadowHost = n;\r\n let shadowHost;\r\n while ((shadowHost = getShadowHost(rootShadowHost)))\r\n rootShadowHost = shadowHost;\r\n return rootShadowHost;\r\n}\r\nfunction shadowHostInDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n const shadowHost = getRootShadowHost(n);\r\n return doc.contains(shadowHost);\r\n}\r\nfunction inDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n return doc.contains(n) || shadowHostInDom(n);\r\n}\r\nconst cachedImplementations = {};\r\nfunction getImplementation(name) {\r\n const cached = cachedImplementations[name];\r\n if (cached) {\r\n return cached;\r\n }\r\n const document = window.document;\r\n let impl = window[name];\r\n if (document && typeof document.createElement === 'function') {\r\n try {\r\n const sandbox = document.createElement('iframe');\r\n sandbox.hidden = true;\r\n document.head.appendChild(sandbox);\r\n const contentWindow = sandbox.contentWindow;\r\n if (contentWindow && contentWindow[name]) {\r\n impl =\r\n contentWindow[name];\r\n }\r\n document.head.removeChild(sandbox);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return (cachedImplementations[name] = impl.bind(window));\r\n}\r\nfunction onRequestAnimationFrame(...rest) {\r\n return getImplementation('requestAnimationFrame')(...rest);\r\n}\r\nfunction setTimeout(...rest) {\r\n return getImplementation('setTimeout')(...rest);\r\n}\r\nfunction clearTimeout(...rest) {\r\n return getImplementation('clearTimeout')(...rest);\r\n}\n\nexport { StyleSheetMirror, _mirror, clearTimeout, closestElementOfNode, getBaseDimension, getNestedRule, getPositionsAndIndex, getRootShadowHost, getShadowHost, getWindowHeight, getWindowScroll, getWindowWidth, hasShadowRoot, hookSetter, inDom, isAncestorRemoved, isBlocked, isIgnored, isSerialized, isSerializedIframe, isSerializedStylesheet, iterateResolveTree, legacy_isTouchEvent, nowTimestamp, on, onRequestAnimationFrame, patch, polyfill, queueToResolveTrees, setTimeout, shadowHostInDom, throttle, uniqueTextMutations };\n","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Polyfill for the nullish coalescing operator (`??`).\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nexport function _nullishCoalesce(lhs: unknown, rhsFn: () => unknown): unknown {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}\n\n// Sucrase version:\n// function _nullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return rhsFn();\n// }\n// }\n","var EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {\n ReplayerEvents2[\"Start\"] = \"start\";\n ReplayerEvents2[\"Pause\"] = \"pause\";\n ReplayerEvents2[\"Resume\"] = \"resume\";\n ReplayerEvents2[\"Resize\"] = \"resize\";\n ReplayerEvents2[\"Finish\"] = \"finish\";\n ReplayerEvents2[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents2[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents2[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents2[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents2[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents2[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents2[\"EventCast\"] = \"event-cast\";\n ReplayerEvents2[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents2[\"Flush\"] = \"flush\";\n ReplayerEvents2[\"StateChange\"] = \"state-change\";\n ReplayerEvents2[\"PlayBack\"] = \"play-back\";\n ReplayerEvents2[\"Destroy\"] = \"destroy\";\n return ReplayerEvents2;\n})(ReplayerEvents || {});\n\nexport { CanvasContext, EventType, IncrementalSource, MouseInteractions, PointerTypes, ReplayerEvents };\n","import { isShadowRoot, isNativeShadowDom, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue, ignoreAttribute, transformAttribute, toLowerCase, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isSerialized, isAncestorRemoved, closestElementOfNode, hasShadowRoot, inDom, getShadowHost, isSerializedIframe, isSerializedStylesheet } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\r\n return '__ln' in n;\r\n}\r\nclass DoubleLinkedList {\r\n constructor() {\r\n this.length = 0;\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n get(position) {\r\n if (position >= this.length) {\r\n throw new Error('Position outside of list range');\r\n }\r\n let current = this.head;\r\n for (let index = 0; index < position; index++) {\r\n current = current?.next || null;\r\n }\r\n return current;\r\n }\r\n addNode(n) {\r\n const node = {\r\n value: n,\r\n previous: null,\r\n next: null,\r\n };\r\n n.__ln = node;\r\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\r\n const current = n.previousSibling.__ln.next;\r\n node.next = current;\r\n node.previous = n.previousSibling.__ln;\r\n n.previousSibling.__ln.next = node;\r\n if (current) {\r\n current.previous = node;\r\n }\r\n }\r\n else if (n.nextSibling &&\r\n isNodeInLinkedList(n.nextSibling) &&\r\n n.nextSibling.__ln.previous) {\r\n const current = n.nextSibling.__ln.previous;\r\n node.previous = current;\r\n node.next = n.nextSibling.__ln;\r\n n.nextSibling.__ln.previous = node;\r\n if (current) {\r\n current.next = node;\r\n }\r\n }\r\n else {\r\n if (this.head) {\r\n this.head.previous = node;\r\n }\r\n node.next = this.head;\r\n this.head = node;\r\n }\r\n if (node.next === null) {\r\n this.tail = node;\r\n }\r\n this.length++;\r\n }\r\n removeNode(n) {\r\n const current = n.__ln;\r\n if (!this.head) {\r\n return;\r\n }\r\n if (!current.previous) {\r\n this.head = current.next;\r\n if (this.head) {\r\n this.head.previous = null;\r\n }\r\n else {\r\n this.tail = null;\r\n }\r\n }\r\n else {\r\n current.previous.next = current.next;\r\n if (current.next) {\r\n current.next.previous = current.previous;\r\n }\r\n else {\r\n this.tail = current.previous;\r\n }\r\n }\r\n if (n.__ln) {\r\n delete n.__ln;\r\n }\r\n this.length--;\r\n }\r\n}\r\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\r\nclass MutationBuffer {\r\n constructor() {\r\n this.frozen = false;\r\n this.locked = false;\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.mapRemoves = [];\r\n this.movedMap = {};\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.processMutations = (mutations) => {\r\n mutations.forEach(this.processMutation);\r\n this.emit();\r\n };\r\n this.emit = () => {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const adds = [];\r\n const addedIds = new Set();\r\n const addList = new DoubleLinkedList();\r\n const getNextId = (n) => {\r\n let ns = n;\r\n let nextId = IGNORED_NODE;\r\n while (nextId === IGNORED_NODE) {\r\n ns = ns && ns.nextSibling;\r\n nextId = ns && this.mirror.getId(ns);\r\n }\r\n return nextId;\r\n };\r\n const pushAdd = (n) => {\r\n if (!n.parentNode || !inDom(n)) {\r\n return;\r\n }\r\n const parentId = isShadowRoot(n.parentNode)\r\n ? this.mirror.getId(getShadowHost(n))\r\n : this.mirror.getId(n.parentNode);\r\n const nextId = getNextId(n);\r\n if (parentId === -1 || nextId === -1) {\r\n return addList.addNode(n);\r\n }\r\n const sn = serializeNodeWithId(n, {\r\n doc: this.doc,\r\n mirror: this.mirror,\r\n blockClass: this.blockClass,\r\n blockSelector: this.blockSelector,\r\n maskAllText: this.maskAllText,\r\n unblockSelector: this.unblockSelector,\r\n maskTextClass: this.maskTextClass,\r\n unmaskTextClass: this.unmaskTextClass,\r\n maskTextSelector: this.maskTextSelector,\r\n unmaskTextSelector: this.unmaskTextSelector,\r\n skipChild: true,\r\n newlyAddedElement: true,\r\n inlineStylesheet: this.inlineStylesheet,\r\n maskInputOptions: this.maskInputOptions,\r\n maskAttributeFn: this.maskAttributeFn,\r\n maskTextFn: this.maskTextFn,\r\n maskInputFn: this.maskInputFn,\r\n slimDOMOptions: this.slimDOMOptions,\r\n dataURLOptions: this.dataURLOptions,\r\n recordCanvas: this.recordCanvas,\r\n inlineImages: this.inlineImages,\r\n onSerialize: (currentN) => {\r\n if (isSerializedIframe(currentN, this.mirror)) {\r\n this.iframeManager.addIframe(currentN);\r\n }\r\n if (isSerializedStylesheet(currentN, this.mirror)) {\r\n this.stylesheetManager.trackLinkElement(currentN);\r\n }\r\n if (hasShadowRoot(n)) {\r\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n this.iframeManager.attachIframe(iframe, childSn);\r\n this.shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (link, childSn) => {\r\n this.stylesheetManager.attachLinkElement(link, childSn);\r\n },\r\n });\r\n if (sn) {\r\n adds.push({\r\n parentId,\r\n nextId,\r\n node: sn,\r\n });\r\n addedIds.add(sn.id);\r\n }\r\n };\r\n while (this.mapRemoves.length) {\r\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\r\n }\r\n for (const n of this.movedSet) {\r\n if (isParentRemoved(this.removes, n, this.mirror) &&\r\n !this.movedSet.has(n.parentNode)) {\r\n continue;\r\n }\r\n pushAdd(n);\r\n }\r\n for (const n of this.addedSet) {\r\n if (!isAncestorInSet(this.droppedSet, n) &&\r\n !isParentRemoved(this.removes, n, this.mirror)) {\r\n pushAdd(n);\r\n }\r\n else if (isAncestorInSet(this.movedSet, n)) {\r\n pushAdd(n);\r\n }\r\n else {\r\n this.droppedSet.add(n);\r\n }\r\n }\r\n let candidate = null;\r\n while (addList.length) {\r\n let node = null;\r\n if (candidate) {\r\n const parentId = this.mirror.getId(candidate.value.parentNode);\r\n const nextId = getNextId(candidate.value);\r\n if (parentId !== -1 && nextId !== -1) {\r\n node = candidate;\r\n }\r\n }\r\n if (!node) {\r\n let tailNode = addList.tail;\r\n while (tailNode) {\r\n const _node = tailNode;\r\n tailNode = tailNode.previous;\r\n if (_node) {\r\n const parentId = this.mirror.getId(_node.value.parentNode);\r\n const nextId = getNextId(_node.value);\r\n if (nextId === -1)\r\n continue;\r\n else if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n else {\r\n const unhandledNode = _node.value;\r\n if (unhandledNode.parentNode &&\r\n unhandledNode.parentNode.nodeType ===\r\n Node.DOCUMENT_FRAGMENT_NODE) {\r\n const shadowHost = unhandledNode.parentNode\r\n .host;\r\n const parentId = this.mirror.getId(shadowHost);\r\n if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (!node) {\r\n while (addList.head) {\r\n addList.removeNode(addList.head.value);\r\n }\r\n break;\r\n }\r\n candidate = node.previous;\r\n addList.removeNode(node.value);\r\n pushAdd(node.value);\r\n }\r\n const payload = {\r\n texts: this.texts\r\n .map((text) => ({\r\n id: this.mirror.getId(text.node),\r\n value: text.value,\r\n }))\r\n .filter((text) => !addedIds.has(text.id))\r\n .filter((text) => this.mirror.has(text.id)),\r\n attributes: this.attributes\r\n .map((attribute) => {\r\n const { attributes } = attribute;\r\n if (typeof attributes.style === 'string') {\r\n const diffAsStr = JSON.stringify(attribute.styleDiff);\r\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\r\n if (diffAsStr.length < attributes.style.length) {\r\n if ((diffAsStr + unchangedAsStr).split('var(').length ===\r\n attributes.style.split('var(').length) {\r\n attributes.style = attribute.styleDiff;\r\n }\r\n }\r\n }\r\n return {\r\n id: this.mirror.getId(attribute.node),\r\n attributes: attributes,\r\n };\r\n })\r\n .filter((attribute) => !addedIds.has(attribute.id))\r\n .filter((attribute) => this.mirror.has(attribute.id)),\r\n removes: this.removes,\r\n adds,\r\n };\r\n if (!payload.texts.length &&\r\n !payload.attributes.length &&\r\n !payload.removes.length &&\r\n !payload.adds.length) {\r\n return;\r\n }\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.movedMap = {};\r\n this.mutationCb(payload);\r\n };\r\n this.processMutation = (m) => {\r\n if (isIgnored(m.target, this.mirror)) {\r\n return;\r\n }\r\n switch (m.type) {\r\n case 'characterData': {\r\n const value = m.target.textContent;\r\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) &&\r\n value !== m.oldValue) {\r\n this.texts.push({\r\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value\r\n ? this.maskTextFn\r\n ? this.maskTextFn(value, closestElementOfNode(m.target))\r\n : value.replace(/[\\S]/g, '*')\r\n : value,\r\n node: m.target,\r\n });\r\n }\r\n break;\r\n }\r\n case 'attributes': {\r\n const target = m.target;\r\n let attributeName = m.attributeName;\r\n let value = m.target.getAttribute(attributeName);\r\n if (attributeName === 'value') {\r\n const type = getInputType(target);\r\n const tagName = target.tagName;\r\n value = getInputValue(target, tagName, type);\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions: this.maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked);\r\n value = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value,\r\n maskInputFn: this.maskInputFn,\r\n });\r\n }\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n value === m.oldValue) {\r\n return;\r\n }\r\n let item = this.attributeMap.get(m.target);\r\n if (target.tagName === 'IFRAME' &&\r\n attributeName === 'src' &&\r\n !this.keepIframeSrcFn(value)) {\r\n if (!target.contentDocument) {\r\n attributeName = 'rr_src';\r\n }\r\n else {\r\n return;\r\n }\r\n }\r\n if (!item) {\r\n item = {\r\n node: m.target,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(m.target, item);\r\n }\r\n if (attributeName === 'type' &&\r\n target.tagName === 'INPUT' &&\r\n (m.oldValue || '').toLowerCase() === 'password') {\r\n target.setAttribute('data-rr-is-password', 'true');\r\n }\r\n if (!ignoreAttribute(target.tagName, attributeName)) {\r\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn);\r\n if (attributeName === 'style') {\r\n if (!this.unattachedDoc) {\r\n try {\r\n this.unattachedDoc =\r\n document.implementation.createHTMLDocument();\r\n }\r\n catch (e) {\r\n this.unattachedDoc = this.doc;\r\n }\r\n }\r\n const old = this.unattachedDoc.createElement('span');\r\n if (m.oldValue) {\r\n old.setAttribute('style', m.oldValue);\r\n }\r\n for (const pname of Array.from(target.style)) {\r\n const newValue = target.style.getPropertyValue(pname);\r\n const newPriority = target.style.getPropertyPriority(pname);\r\n if (newValue !== old.style.getPropertyValue(pname) ||\r\n newPriority !== old.style.getPropertyPriority(pname)) {\r\n if (newPriority === '') {\r\n item.styleDiff[pname] = newValue;\r\n }\r\n else {\r\n item.styleDiff[pname] = [newValue, newPriority];\r\n }\r\n }\r\n else {\r\n item._unchangedStyles[pname] = [newValue, newPriority];\r\n }\r\n }\r\n for (const pname of Array.from(old.style)) {\r\n if (target.style.getPropertyValue(pname) === '') {\r\n item.styleDiff[pname] = false;\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 'childList': {\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) {\r\n return;\r\n }\r\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\r\n m.removedNodes.forEach((n) => {\r\n const nodeId = this.mirror.getId(n);\r\n const parentId = isShadowRoot(m.target)\r\n ? this.mirror.getId(m.target.host)\r\n : this.mirror.getId(m.target);\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n isIgnored(n, this.mirror) ||\r\n !isSerialized(n, this.mirror)) {\r\n return;\r\n }\r\n if (this.addedSet.has(n)) {\r\n deepDelete(this.addedSet, n);\r\n this.droppedSet.add(n);\r\n }\r\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\r\n else if (isAncestorRemoved(m.target, this.mirror)) ;\r\n else if (this.movedSet.has(n) &&\r\n this.movedMap[moveKey(nodeId, parentId)]) {\r\n deepDelete(this.movedSet, n);\r\n }\r\n else {\r\n this.removes.push({\r\n parentId,\r\n id: nodeId,\r\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\r\n ? true\r\n : undefined,\r\n });\r\n }\r\n this.mapRemoves.push(n);\r\n });\r\n break;\r\n }\r\n }\r\n };\r\n this.genAdds = (n, target) => {\r\n if (this.processedNodeManager.inOtherBuffer(n, this))\r\n return;\r\n if (this.addedSet.has(n) || this.movedSet.has(n))\r\n return;\r\n if (this.mirror.hasNode(n)) {\r\n if (isIgnored(n, this.mirror)) {\r\n return;\r\n }\r\n this.movedSet.add(n);\r\n let targetId = null;\r\n if (target && this.mirror.hasNode(target)) {\r\n targetId = this.mirror.getId(target);\r\n }\r\n if (targetId && targetId !== -1) {\r\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\r\n }\r\n }\r\n else {\r\n this.addedSet.add(n);\r\n this.droppedSet.delete(n);\r\n }\r\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\r\n n.childNodes.forEach((childN) => this.genAdds(childN));\r\n if (hasShadowRoot(n)) {\r\n n.shadowRoot.childNodes.forEach((childN) => {\r\n this.processedNodeManager.add(childN, this);\r\n this.genAdds(childN, n);\r\n });\r\n }\r\n }\r\n };\r\n }\r\n init(options) {\r\n [\r\n 'mutationCb',\r\n 'blockClass',\r\n 'blockSelector',\r\n 'unblockSelector',\r\n 'maskAllText',\r\n 'maskTextClass',\r\n 'unmaskTextClass',\r\n 'maskTextSelector',\r\n 'unmaskTextSelector',\r\n 'inlineStylesheet',\r\n 'maskInputOptions',\r\n 'maskAttributeFn',\r\n 'maskTextFn',\r\n 'maskInputFn',\r\n 'keepIframeSrcFn',\r\n 'recordCanvas',\r\n 'inlineImages',\r\n 'slimDOMOptions',\r\n 'dataURLOptions',\r\n 'doc',\r\n 'mirror',\r\n 'iframeManager',\r\n 'stylesheetManager',\r\n 'shadowDomManager',\r\n 'canvasManager',\r\n 'processedNodeManager',\r\n ].forEach((key) => {\r\n this[key] = options[key];\r\n });\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n this.canvasManager.freeze();\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n this.canvasManager.unfreeze();\r\n this.emit();\r\n }\r\n isFrozen() {\r\n return this.frozen;\r\n }\r\n lock() {\r\n this.locked = true;\r\n this.canvasManager.lock();\r\n }\r\n unlock() {\r\n this.locked = false;\r\n this.canvasManager.unlock();\r\n this.emit();\r\n }\r\n reset() {\r\n this.shadowDomManager.reset();\r\n this.canvasManager.reset();\r\n }\r\n}\r\nfunction deepDelete(addsSet, n) {\r\n addsSet.delete(n);\r\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\r\n}\r\nfunction isParentRemoved(removes, n, mirror) {\r\n if (removes.length === 0)\r\n return false;\r\n return _isParentRemoved(removes, n, mirror);\r\n}\r\nfunction _isParentRemoved(removes, n, mirror) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n const parentId = mirror.getId(parentNode);\r\n if (removes.some((r) => r.id === parentId)) {\r\n return true;\r\n }\r\n return _isParentRemoved(removes, parentNode, mirror);\r\n}\r\nfunction isAncestorInSet(set, n) {\r\n if (set.size === 0)\r\n return false;\r\n return _isAncestorInSet(set, n);\r\n}\r\nfunction _isAncestorInSet(set, n) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n if (set.has(parentNode)) {\r\n return true;\r\n }\r\n return _isAncestorInSet(set, parentNode);\r\n}\n\nexport { MutationBuffer as default };\n","let errorHandler;\r\nfunction registerErrorHandler(handler) {\r\n errorHandler = handler;\r\n}\r\nfunction unregisterErrorHandler() {\r\n errorHandler = undefined;\r\n}\r\nconst callbackWrapper = (cb) => {\r\n if (!errorHandler) {\r\n return cb;\r\n }\r\n const rrwebWrapped = ((...rest) => {\r\n try {\r\n return cb(...rest);\r\n }\r\n catch (error) {\r\n if (errorHandler && errorHandler(error) === true) {\r\n return () => {\r\n };\r\n }\r\n throw error;\r\n }\r\n });\r\n return rrwebWrapped;\r\n};\n\nexport { callbackWrapper, registerErrorHandler, unregisterErrorHandler };\n","import { toLowerCase, toUpperCase, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isBlocked, getWindowScroll, hookSetter, patch, setTimeout, legacy_isTouchEvent, nowTimestamp, getWindowHeight, getWindowWidth } from '../utils.js';\nimport { MouseInteractions, IncrementalSource, PointerTypes } from '../../../types/dist/rrweb-types.js';\nimport MutationBuffer from './mutation.js';\nimport { callbackWrapper } from './error-handler.js';\n\nconst mutationBuffers = [];\r\nfunction getEventTarget(event) {\r\n try {\r\n if ('composedPath' in event) {\r\n const path = event.composedPath();\r\n if (path.length) {\r\n return path[0];\r\n }\r\n }\r\n else if ('path' in event && event.path.length) {\r\n return event.path[0];\r\n }\r\n }\r\n catch {\r\n }\r\n return event && event.target;\r\n}\r\nfunction initMutationObserver(options, rootEl) {\r\n const mutationBuffer = new MutationBuffer();\r\n mutationBuffers.push(mutationBuffer);\r\n mutationBuffer.init(options);\r\n let mutationObserverCtor = window.MutationObserver ||\r\n window.__rrMutationObserver;\r\n const angularZoneSymbol = window?.Zone?.__symbol__?.('MutationObserver');\r\n if (angularZoneSymbol &&\r\n window[angularZoneSymbol]) {\r\n mutationObserverCtor = window[angularZoneSymbol];\r\n }\r\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\r\n if (options.onMutation && options.onMutation(mutations) === false) {\r\n return;\r\n }\r\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\r\n }));\r\n observer.observe(rootEl, {\r\n attributes: true,\r\n attributeOldValue: true,\r\n characterData: true,\r\n characterDataOldValue: true,\r\n childList: true,\r\n subtree: true,\r\n });\r\n return observer;\r\n}\r\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\r\n if (sampling.mousemove === false) {\r\n return () => {\r\n };\r\n }\r\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\r\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\r\n ? sampling.mousemoveCallback\r\n : 500;\r\n let positions = [];\r\n let timeBaseline;\r\n const wrappedCb = throttle(callbackWrapper((source) => {\r\n const totalOffset = Date.now() - timeBaseline;\r\n mousemoveCb(positions.map((p) => {\r\n p.timeOffset -= totalOffset;\r\n return p;\r\n }), source);\r\n positions = [];\r\n timeBaseline = null;\r\n }), callbackThreshold);\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n const { clientX, clientY } = legacy_isTouchEvent(evt)\r\n ? evt.changedTouches[0]\r\n : evt;\r\n if (!timeBaseline) {\r\n timeBaseline = nowTimestamp();\r\n }\r\n positions.push({\r\n x: clientX,\r\n y: clientY,\r\n id: mirror.getId(target),\r\n timeOffset: nowTimestamp() - timeBaseline,\r\n });\r\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\r\n ? IncrementalSource.Drag\r\n : evt instanceof MouseEvent\r\n ? IncrementalSource.MouseMove\r\n : IncrementalSource.TouchMove);\r\n }), threshold, {\r\n trailing: false,\r\n }));\r\n const handlers = [\r\n on('mousemove', updatePosition, doc),\r\n on('touchmove', updatePosition, doc),\r\n on('drag', updatePosition, doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n if (sampling.mouseInteraction === false) {\r\n return () => {\r\n };\r\n }\r\n const disableMap = sampling.mouseInteraction === true ||\r\n sampling.mouseInteraction === undefined\r\n ? {}\r\n : sampling.mouseInteraction;\r\n const handlers = [];\r\n let currentPointerType = null;\r\n const getHandler = (eventKey) => {\r\n return (event) => {\r\n const target = getEventTarget(event);\r\n if (isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n let pointerType = null;\r\n let thisEventKey = eventKey;\r\n if ('pointerType' in event) {\r\n switch (event.pointerType) {\r\n case 'mouse':\r\n pointerType = PointerTypes.Mouse;\r\n break;\r\n case 'touch':\r\n pointerType = PointerTypes.Touch;\r\n break;\r\n case 'pen':\r\n pointerType = PointerTypes.Pen;\r\n break;\r\n }\r\n if (pointerType === PointerTypes.Touch) {\r\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\r\n thisEventKey = 'TouchStart';\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\r\n thisEventKey = 'TouchEnd';\r\n }\r\n }\r\n else if (pointerType === PointerTypes.Pen) ;\r\n }\r\n else if (legacy_isTouchEvent(event)) {\r\n pointerType = PointerTypes.Touch;\r\n }\r\n if (pointerType !== null) {\r\n currentPointerType = pointerType;\r\n if ((thisEventKey.startsWith('Touch') &&\r\n pointerType === PointerTypes.Touch) ||\r\n (thisEventKey.startsWith('Mouse') &&\r\n pointerType === PointerTypes.Mouse)) {\r\n pointerType = null;\r\n }\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\r\n pointerType = currentPointerType;\r\n currentPointerType = null;\r\n }\r\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\r\n if (!e) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n const { clientX, clientY } = e;\r\n callbackWrapper(mouseInteractionCb)({\r\n type: MouseInteractions[thisEventKey],\r\n id,\r\n x: clientX,\r\n y: clientY,\r\n ...(pointerType !== null && { pointerType }),\r\n });\r\n };\r\n };\r\n Object.keys(MouseInteractions)\r\n .filter((key) => Number.isNaN(Number(key)) &&\r\n !key.endsWith('_Departed') &&\r\n disableMap[key] !== false)\r\n .forEach((eventKey) => {\r\n let eventName = toLowerCase(eventKey);\r\n const handler = getHandler(eventKey);\r\n if (window.PointerEvent) {\r\n switch (MouseInteractions[eventKey]) {\r\n case MouseInteractions.MouseDown:\r\n case MouseInteractions.MouseUp:\r\n eventName = eventName.replace('mouse', 'pointer');\r\n break;\r\n case MouseInteractions.TouchStart:\r\n case MouseInteractions.TouchEnd:\r\n return;\r\n }\r\n }\r\n handlers.push(on(eventName, handler, doc));\r\n });\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n if (target === doc && doc.defaultView) {\r\n const scrollLeftTop = getWindowScroll(doc.defaultView);\r\n scrollCb({\r\n id,\r\n x: scrollLeftTop.left,\r\n y: scrollLeftTop.top,\r\n });\r\n }\r\n else {\r\n scrollCb({\r\n id,\r\n x: target.scrollLeft,\r\n y: target.scrollTop,\r\n });\r\n }\r\n }), sampling.scroll || 100));\r\n return on('scroll', updatePosition, doc);\r\n}\r\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\r\n let lastH = -1;\r\n let lastW = -1;\r\n const updateDimension = callbackWrapper(throttle(callbackWrapper(() => {\r\n const height = getWindowHeight();\r\n const width = getWindowWidth();\r\n if (lastH !== height || lastW !== width) {\r\n viewportResizeCb({\r\n width: Number(width),\r\n height: Number(height),\r\n });\r\n lastH = height;\r\n lastW = width;\r\n }\r\n }), 200));\r\n return on('resize', updateDimension, win);\r\n}\r\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\r\nconst lastInputValueMap = new WeakMap();\r\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, }) {\r\n function eventHandler(event) {\r\n let target = getEventTarget(event);\r\n const userTriggered = event.isTrusted;\r\n const tagName = target && toUpperCase(target.tagName);\r\n if (tagName === 'OPTION')\r\n target = target.parentElement;\r\n if (!target ||\r\n !tagName ||\r\n INPUT_TAGS.indexOf(tagName) < 0 ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const el = target;\r\n if (el.classList.contains(ignoreClass) ||\r\n (ignoreSelector && el.matches(ignoreSelector))) {\r\n return;\r\n }\r\n const type = getInputType(target);\r\n let text = getInputValue(el, tagName, type);\r\n let isChecked = false;\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked);\r\n if (type === 'radio' || type === 'checkbox') {\r\n isChecked = target.checked;\r\n }\r\n text = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value: text,\r\n maskInputFn,\r\n });\r\n cbWithDedup(target, userTriggeredOnInput\r\n ? { text, isChecked, userTriggered }\r\n : { text, isChecked });\r\n const name = target.name;\r\n if (type === 'radio' && name && isChecked) {\r\n doc\r\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\r\n .forEach((el) => {\r\n if (el !== target) {\r\n const text = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value: getInputValue(el, tagName, type),\r\n maskInputFn,\r\n });\r\n cbWithDedup(el, userTriggeredOnInput\r\n ? { text, isChecked: !isChecked, userTriggered: false }\r\n : { text, isChecked: !isChecked });\r\n }\r\n });\r\n }\r\n }\r\n function cbWithDedup(target, v) {\r\n const lastInputValue = lastInputValueMap.get(target);\r\n if (!lastInputValue ||\r\n lastInputValue.text !== v.text ||\r\n lastInputValue.isChecked !== v.isChecked) {\r\n lastInputValueMap.set(target, v);\r\n const id = mirror.getId(target);\r\n callbackWrapper(inputCb)({\r\n ...v,\r\n id,\r\n });\r\n }\r\n }\r\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\r\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\r\n const currentWindow = doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n }\r\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\r\n const hookProperties = [\r\n [currentWindow.HTMLInputElement.prototype, 'value'],\r\n [currentWindow.HTMLInputElement.prototype, 'checked'],\r\n [currentWindow.HTMLSelectElement.prototype, 'value'],\r\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\r\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\r\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\r\n ];\r\n if (propertyDescriptor && propertyDescriptor.set) {\r\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\r\n set() {\r\n callbackWrapper(eventHandler)({\r\n target: this,\r\n isTrusted: false,\r\n });\r\n },\r\n }, false, currentWindow)));\r\n }\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction getNestedCSSRulePositions(rule) {\r\n const positions = [];\r\n function recurse(childRule, pos) {\r\n if ((hasNestedCSSRule('CSSGroupingRule') &&\r\n childRule.parentRule instanceof CSSGroupingRule) ||\r\n (hasNestedCSSRule('CSSMediaRule') &&\r\n childRule.parentRule instanceof CSSMediaRule) ||\r\n (hasNestedCSSRule('CSSSupportsRule') &&\r\n childRule.parentRule instanceof CSSSupportsRule) ||\r\n (hasNestedCSSRule('CSSConditionRule') &&\r\n childRule.parentRule instanceof CSSConditionRule)) {\r\n const rules = Array.from(childRule.parentRule.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n else if (childRule.parentStyleSheet) {\r\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n return pos;\r\n }\r\n return recurse(rule, positions);\r\n}\r\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\r\n let id, styleId;\r\n if (!sheet)\r\n return {};\r\n if (sheet.ownerNode)\r\n id = mirror.getId(sheet.ownerNode);\r\n else\r\n styleId = styleMirror.getId(sheet);\r\n return {\r\n styleId,\r\n id,\r\n };\r\n}\r\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {\r\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\r\n return () => {\r\n };\r\n }\r\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\r\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [{ rule, index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\r\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [{ index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n let replace;\r\n if (win.CSSStyleSheet.prototype.replace) {\r\n replace = win.CSSStyleSheet.prototype.replace;\r\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replace: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n let replaceSync;\r\n if (win.CSSStyleSheet.prototype.replaceSync) {\r\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\r\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replaceSync: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n const supportedNestedCSSRuleTypes = {};\r\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\r\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\r\n }\r\n else {\r\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\r\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\r\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\r\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\r\n }\r\n }\r\n const unmodifiedFunctions = {};\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n unmodifiedFunctions[typeKey] = {\r\n insertRule: type.prototype.insertRule,\r\n deleteRule: type.prototype.deleteRule,\r\n };\r\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [\r\n {\r\n rule,\r\n index: [\r\n ...getNestedCSSRulePositions(thisArg),\r\n index || 0,\r\n ],\r\n },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [\r\n { index: [...getNestedCSSRulePositions(thisArg), index] },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleSheet.prototype.insertRule = insertRule;\r\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\r\n replace && (win.CSSStyleSheet.prototype.replace = replace);\r\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\r\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\r\n });\r\n });\r\n}\r\nfunction initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {\r\n let hostId = null;\r\n if (host.nodeName === '#document')\r\n hostId = mirror.getId(host);\r\n else\r\n hostId = mirror.getId(host.host);\r\n const patchTarget = host.nodeName === '#document'\r\n ? host.defaultView?.Document\r\n : host.ownerDocument?.defaultView?.ShadowRoot;\r\n const originalPropertyDescriptor = patchTarget?.prototype\r\n ? Object.getOwnPropertyDescriptor(patchTarget?.prototype, 'adoptedStyleSheets')\r\n : undefined;\r\n if (hostId === null ||\r\n hostId === -1 ||\r\n !patchTarget ||\r\n !originalPropertyDescriptor)\r\n return () => {\r\n };\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get() {\r\n return originalPropertyDescriptor.get?.call(this);\r\n },\r\n set(sheets) {\r\n const result = originalPropertyDescriptor.set?.call(this, sheets);\r\n if (hostId !== null && hostId !== -1) {\r\n try {\r\n stylesheetManager.adoptStyleSheets(sheets, hostId);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return result;\r\n },\r\n });\r\n return callbackWrapper(() => {\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get: originalPropertyDescriptor.get,\r\n set: originalPropertyDescriptor.set,\r\n });\r\n });\r\n}\r\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\r\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\r\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property, value, priority] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return setProperty.apply(thisArg, [property, value, priority]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n set: {\r\n property,\r\n value,\r\n priority,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return removeProperty.apply(thisArg, [property]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n remove: {\r\n property,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\r\n });\r\n}\r\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, doc, }) {\r\n const handler = callbackWrapper((type) => throttle(callbackWrapper((event) => {\r\n const target = getEventTarget(event);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const { currentTime, volume, muted, playbackRate } = target;\r\n mediaInteractionCb({\r\n type,\r\n id: mirror.getId(target),\r\n currentTime,\r\n volume,\r\n muted,\r\n playbackRate,\r\n });\r\n }), sampling.media || 500));\r\n const handlers = [\r\n on('play', handler(0), doc),\r\n on('pause', handler(1), doc),\r\n on('seeked', handler(2), doc),\r\n on('volumechange', handler(3), doc),\r\n on('ratechange', handler(4), doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initFontObserver({ fontCb, doc }) {\r\n const win = doc.defaultView;\r\n if (!win) {\r\n return () => {\r\n };\r\n }\r\n const handlers = [];\r\n const fontMap = new WeakMap();\r\n const originalFontFace = win.FontFace;\r\n win.FontFace = function FontFace(family, source, descriptors) {\r\n const fontFace = new originalFontFace(family, source, descriptors);\r\n fontMap.set(fontFace, {\r\n family,\r\n buffer: typeof source !== 'string',\r\n descriptors,\r\n fontSource: typeof source === 'string'\r\n ? source\r\n : JSON.stringify(Array.from(new Uint8Array(source))),\r\n });\r\n return fontFace;\r\n };\r\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\r\n return function (fontFace) {\r\n setTimeout(callbackWrapper(() => {\r\n const p = fontMap.get(fontFace);\r\n if (p) {\r\n fontCb(p);\r\n fontMap.delete(fontFace);\r\n }\r\n }), 0);\r\n return original.apply(this, [fontFace]);\r\n };\r\n });\r\n handlers.push(() => {\r\n win.FontFace = originalFontFace;\r\n });\r\n handlers.push(restoreHandler);\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initSelectionObserver(param) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, selectionCb, } = param;\r\n let collapsed = true;\r\n const updateSelection = callbackWrapper(() => {\r\n const selection = doc.getSelection();\r\n if (!selection || (collapsed && selection?.isCollapsed))\r\n return;\r\n collapsed = selection.isCollapsed || false;\r\n const ranges = [];\r\n const count = selection.rangeCount || 0;\r\n for (let i = 0; i < count; i++) {\r\n const range = selection.getRangeAt(i);\r\n const { startContainer, startOffset, endContainer, endOffset } = range;\r\n const blocked = isBlocked(startContainer, blockClass, blockSelector, unblockSelector, true) ||\r\n isBlocked(endContainer, blockClass, blockSelector, unblockSelector, true);\r\n if (blocked)\r\n continue;\r\n ranges.push({\r\n start: mirror.getId(startContainer),\r\n startOffset,\r\n end: mirror.getId(endContainer),\r\n endOffset,\r\n });\r\n }\r\n selectionCb({ ranges });\r\n });\r\n updateSelection();\r\n return on('selectionchange', updateSelection);\r\n}\r\nfunction initCustomElementObserver({ doc, customElementCb, }) {\r\n const win = doc.defaultView;\r\n if (!win || !win.customElements)\r\n return () => { };\r\n const restoreHandler = patch(win.customElements, 'define', function (original) {\r\n return function (name, constructor, options) {\r\n try {\r\n customElementCb({\r\n define: {\r\n name,\r\n },\r\n });\r\n }\r\n catch (e) {\r\n }\r\n return original.apply(this, [name, constructor, options]);\r\n };\r\n });\r\n return restoreHandler;\r\n}\r\nfunction initObservers(o, _hooks = {}) {\r\n const currentWindow = o.doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n };\r\n }\r\n const mutationObserver = initMutationObserver(o, o.doc);\r\n const mousemoveHandler = initMoveObserver(o);\r\n const mouseInteractionHandler = initMouseInteractionObserver(o);\r\n const scrollHandler = initScrollObserver(o);\r\n const viewportResizeHandler = initViewportResizeObserver(o, {\r\n win: currentWindow,\r\n });\r\n const inputHandler = initInputObserver(o);\r\n const mediaInteractionHandler = initMediaInteractionObserver(o);\r\n const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\r\n const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\r\n const styleDeclarationObserver = initStyleDeclarationObserver(o, {\r\n win: currentWindow,\r\n });\r\n const fontObserver = o.collectFonts\r\n ? initFontObserver(o)\r\n : () => {\r\n };\r\n const selectionObserver = initSelectionObserver(o);\r\n const customElementObserver = initCustomElementObserver(o);\r\n const pluginHandlers = [];\r\n for (const plugin of o.plugins) {\r\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\r\n }\r\n return callbackWrapper(() => {\r\n mutationBuffers.forEach((b) => b.reset());\r\n mutationObserver.disconnect();\r\n mousemoveHandler();\r\n mouseInteractionHandler();\r\n scrollHandler();\r\n viewportResizeHandler();\r\n inputHandler();\r\n mediaInteractionHandler();\r\n styleSheetObserver();\r\n adoptedStyleSheetObserver();\r\n styleDeclarationObserver();\r\n fontObserver();\r\n selectionObserver();\r\n customElementObserver();\r\n pluginHandlers.forEach((h) => h());\r\n });\r\n}\r\nfunction hasNestedCSSRule(prop) {\r\n return typeof window[prop] !== 'undefined';\r\n}\r\nfunction canMonkeyPatchNestedCSSRule(prop) {\r\n return Boolean(typeof window[prop] !== 'undefined' &&\r\n window[prop].prototype &&\r\n 'insertRule' in window[prop].prototype &&\r\n 'deleteRule' in window[prop].prototype);\r\n}\n\nexport { INPUT_TAGS, initAdoptedStyleSheetObserver, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n","class CrossOriginIframeMirror {\r\n constructor(generateIdFn) {\r\n this.generateIdFn = generateIdFn;\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n }\r\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\r\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\r\n let id = idToRemoteIdMap.get(remoteId);\r\n if (!id) {\r\n id = this.generateIdFn();\r\n idToRemoteIdMap.set(remoteId, id);\r\n remoteIdToIdMap.set(id, remoteId);\r\n }\r\n return id;\r\n }\r\n getIds(iframe, remoteId) {\r\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\r\n }\r\n getRemoteId(iframe, id, map) {\r\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\r\n if (typeof id !== 'number')\r\n return id;\r\n const remoteId = remoteIdToIdMap.get(id);\r\n if (!remoteId)\r\n return -1;\r\n return remoteId;\r\n }\r\n getRemoteIds(iframe, ids) {\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\r\n }\r\n reset(iframe) {\r\n if (!iframe) {\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n return;\r\n }\r\n this.iframeIdToRemoteIdMap.delete(iframe);\r\n this.iframeRemoteIdToIdMap.delete(iframe);\r\n }\r\n getIdToRemoteIdMap(iframe) {\r\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\r\n if (!idToRemoteIdMap) {\r\n idToRemoteIdMap = new Map();\r\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\r\n }\r\n return idToRemoteIdMap;\r\n }\r\n getRemoteIdToIdMap(iframe) {\r\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\r\n if (!remoteIdToIdMap) {\r\n remoteIdToIdMap = new Map();\r\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\r\n }\r\n return remoteIdToIdMap;\r\n }\r\n}\n\nexport { CrossOriginIframeMirror as default };\n","import { genId, NodeType } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport CrossOriginIframeMirror from './cross-origin-iframe-mirror.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\n\nclass IframeManagerNoop {\r\n constructor() {\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n }\r\n addIframe() {\r\n }\r\n addLoadListener() {\r\n }\r\n attachIframe() {\r\n }\r\n}\r\nclass IframeManager {\r\n constructor(options) {\r\n this.iframes = new WeakMap();\r\n this.crossOriginIframeMap = new WeakMap();\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n this.mutationCb = options.mutationCb;\r\n this.wrappedEmit = options.wrappedEmit;\r\n this.stylesheetManager = options.stylesheetManager;\r\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\r\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\r\n this.mirror = options.mirror;\r\n if (this.recordCrossOriginIframes) {\r\n window.addEventListener('message', this.handleMessage.bind(this));\r\n }\r\n }\r\n addIframe(iframeEl) {\r\n this.iframes.set(iframeEl, true);\r\n if (iframeEl.contentWindow)\r\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\r\n }\r\n addLoadListener(cb) {\r\n this.loadListener = cb;\r\n }\r\n attachIframe(iframeEl, childSn) {\r\n this.mutationCb({\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: childSn,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n });\r\n this.loadListener?.(iframeEl);\r\n if (iframeEl.contentDocument &&\r\n iframeEl.contentDocument.adoptedStyleSheets &&\r\n iframeEl.contentDocument.adoptedStyleSheets.length > 0)\r\n this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));\r\n }\r\n handleMessage(message) {\r\n const crossOriginMessageEvent = message;\r\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\r\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\r\n return;\r\n const iframeSourceWindow = message.source;\r\n if (!iframeSourceWindow)\r\n return;\r\n const iframeEl = this.crossOriginIframeMap.get(message.source);\r\n if (!iframeEl)\r\n return;\r\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\r\n if (transformedEvent)\r\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\r\n }\r\n transformCrossOriginEvent(iframeEl, e) {\r\n switch (e.type) {\r\n case EventType.FullSnapshot: {\r\n this.crossOriginIframeMirror.reset(iframeEl);\r\n this.crossOriginIframeStyleMirror.reset(iframeEl);\r\n this.replaceIdOnNode(e.data.node, iframeEl);\r\n const rootId = e.data.node.id;\r\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\r\n this.patchRootIdOnNode(e.data.node, rootId);\r\n return {\r\n timestamp: e.timestamp,\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: e.data.node,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n },\r\n };\r\n }\r\n case EventType.Meta:\r\n case EventType.Load:\r\n case EventType.DomContentLoaded: {\r\n return false;\r\n }\r\n case EventType.Plugin: {\r\n return e;\r\n }\r\n case EventType.Custom: {\r\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\r\n return e;\r\n }\r\n case EventType.IncrementalSnapshot: {\r\n switch (e.data.source) {\r\n case IncrementalSource.Mutation: {\r\n e.data.adds.forEach((n) => {\r\n this.replaceIds(n, iframeEl, [\r\n 'parentId',\r\n 'nextId',\r\n 'previousId',\r\n ]);\r\n this.replaceIdOnNode(n.node, iframeEl);\r\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\r\n rootId && this.patchRootIdOnNode(n.node, rootId);\r\n });\r\n e.data.removes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\r\n });\r\n e.data.attributes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n e.data.texts.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.Drag:\r\n case IncrementalSource.TouchMove:\r\n case IncrementalSource.MouseMove: {\r\n e.data.positions.forEach((p) => {\r\n this.replaceIds(p, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.ViewportResize: {\r\n return false;\r\n }\r\n case IncrementalSource.MediaInteraction:\r\n case IncrementalSource.MouseInteraction:\r\n case IncrementalSource.Scroll:\r\n case IncrementalSource.CanvasMutation:\r\n case IncrementalSource.Input: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n return e;\r\n }\r\n case IncrementalSource.StyleSheetRule:\r\n case IncrementalSource.StyleDeclaration: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\r\n return e;\r\n }\r\n case IncrementalSource.Font: {\r\n return e;\r\n }\r\n case IncrementalSource.Selection: {\r\n e.data.ranges.forEach((range) => {\r\n this.replaceIds(range, iframeEl, ['start', 'end']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.AdoptedStyleSheet: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\r\n e.data.styles?.forEach((style) => {\r\n this.replaceStyleIds(style, iframeEl, ['styleId']);\r\n });\r\n return e;\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n replace(iframeMirror, obj, iframeEl, keys) {\r\n for (const key of keys) {\r\n if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')\r\n continue;\r\n if (Array.isArray(obj[key])) {\r\n obj[key] = iframeMirror.getIds(iframeEl, obj[key]);\r\n }\r\n else {\r\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\r\n }\r\n }\r\n return obj;\r\n }\r\n replaceIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\r\n }\r\n replaceStyleIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\r\n }\r\n replaceIdOnNode(node, iframeEl) {\r\n this.replaceIds(node, iframeEl, ['id', 'rootId']);\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.replaceIdOnNode(child, iframeEl);\r\n });\r\n }\r\n }\r\n patchRootIdOnNode(node, rootId) {\r\n if (node.type !== NodeType.Document && !node.rootId)\r\n node.rootId = rootId;\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.patchRootIdOnNode(child, rootId);\r\n });\r\n }\r\n }\r\n}\n\nexport { IframeManager, IframeManagerNoop };\n","import { createMirror, snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, on, nowTimestamp, getWindowWidth, getWindowHeight, getWindowScroll, isSerializedIframe, isSerializedStylesheet, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\nimport { IframeManagerNoop, IframeManager } from './iframe-manager.js';\nimport { ShadowDomManagerNoop, ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManagerNoop } from './observers/canvas/canvas-manager.js';\nexport { CanvasManager } from './observers/canvas/canvas-manager.js';\nimport { StylesheetManager } from './stylesheet-manager.js';\nimport ProcessedNodeManager from './processed-node-manager.js';\nimport { callbackWrapper, unregisterErrorHandler, registerErrorHandler } from './error-handler.js';\n\nlet wrappedEmit;\r\nlet _wrappedEmit;\r\nlet _takeFullSnapshot;\r\nconst mirror = createMirror();\r\nfunction record(options = {}) {\r\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\r\n ? options.recordAfter\r\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, onMutation, getCanvasManager, } = options;\r\n registerErrorHandler(errorHandler);\r\n const inEmittingFrame = recordCrossOriginIframes\r\n ? window.parent === window\r\n : true;\r\n let passEmitsToParent = false;\r\n if (!inEmittingFrame) {\r\n try {\r\n if (window.parent.document) {\r\n passEmitsToParent = false;\r\n }\r\n }\r\n catch (e) {\r\n passEmitsToParent = true;\r\n }\r\n }\r\n if (inEmittingFrame && !emit) {\r\n throw new Error('emit function is required');\r\n }\r\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\r\n sampling.mousemove = mousemoveWait;\r\n }\r\n mirror.reset();\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n radio: true,\r\n checkbox: true,\r\n }\r\n : _maskInputOptions !== undefined\r\n ? _maskInputOptions\r\n : {};\r\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\r\n ? {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaVerification: true,\r\n headMetaAuthorship: _slimDOMOptions === 'all',\r\n headMetaDescKeywords: _slimDOMOptions === 'all',\r\n }\r\n : _slimDOMOptions\r\n ? _slimDOMOptions\r\n : {};\r\n polyfill();\r\n let lastFullSnapshotEvent;\r\n let incrementalSnapshotCount = 0;\r\n const eventProcessor = (e) => {\r\n for (const plugin of plugins || []) {\r\n if (plugin.eventProcessor) {\r\n e = plugin.eventProcessor(e);\r\n }\r\n }\r\n if (packFn &&\r\n !passEmitsToParent) {\r\n e = packFn(e);\r\n }\r\n return e;\r\n };\r\n wrappedEmit = (r, isCheckout) => {\r\n const e = r;\r\n e.timestamp = nowTimestamp();\r\n if (mutationBuffers[0]?.isFrozen() &&\r\n e.type !== EventType.FullSnapshot &&\r\n !(e.type === EventType.IncrementalSnapshot &&\r\n e.data.source === IncrementalSource.Mutation)) {\r\n mutationBuffers.forEach((buf) => buf.unfreeze());\r\n }\r\n if (inEmittingFrame) {\r\n emit?.(eventProcessor(e), isCheckout);\r\n }\r\n else if (passEmitsToParent) {\r\n const message = {\r\n type: 'rrweb',\r\n event: eventProcessor(e),\r\n origin: window.location.origin,\r\n isCheckout,\r\n };\r\n window.parent.postMessage(message, '*');\r\n }\r\n if (e.type === EventType.FullSnapshot) {\r\n lastFullSnapshotEvent = e;\r\n incrementalSnapshotCount = 0;\r\n }\r\n else if (e.type === EventType.IncrementalSnapshot) {\r\n if (e.data.source === IncrementalSource.Mutation &&\r\n e.data.isAttachIframe) {\r\n return;\r\n }\r\n incrementalSnapshotCount++;\r\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\r\n const exceedTime = checkoutEveryNms &&\r\n lastFullSnapshotEvent &&\r\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\r\n if (exceedCount || exceedTime) {\r\n takeFullSnapshot(true);\r\n }\r\n }\r\n };\r\n _wrappedEmit = wrappedEmit;\r\n const wrappedMutationEmit = (m) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n ...m,\r\n },\r\n });\r\n };\r\n const wrappedScrollEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Scroll,\r\n ...p,\r\n },\r\n });\r\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n });\r\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.AdoptedStyleSheet,\r\n ...a,\r\n },\r\n });\r\n const stylesheetManager = new StylesheetManager({\r\n mutationCb: wrappedMutationEmit,\r\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\r\n });\r\n const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === 'boolean' && __RRWEB_EXCLUDE_IFRAME__\r\n ? new IframeManagerNoop()\r\n : new IframeManager({\r\n mirror,\r\n mutationCb: wrappedMutationEmit,\r\n stylesheetManager: stylesheetManager,\r\n recordCrossOriginIframes,\r\n wrappedEmit,\r\n });\r\n for (const plugin of plugins || []) {\r\n if (plugin.getMirror)\r\n plugin.getMirror({\r\n nodeMirror: mirror,\r\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\r\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,\r\n });\r\n }\r\n const processedNodeManager = new ProcessedNodeManager();\r\n const canvasManager = _getCanvasManager(getCanvasManager, {\r\n mirror,\r\n win: window,\r\n mutationCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n }),\r\n recordCanvas,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maxCanvasSize,\r\n sampling: sampling['canvas'],\r\n dataURLOptions,\r\n errorHandler,\r\n });\r\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === 'boolean' &&\r\n __RRWEB_EXCLUDE_SHADOW_DOM__\r\n ? new ShadowDomManagerNoop()\r\n : new ShadowDomManager({\r\n mutationCb: wrappedMutationEmit,\r\n scrollCb: wrappedScrollEmit,\r\n bypassOptions: {\r\n onMutation,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n dataURLOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n recordCanvas,\r\n inlineImages,\r\n sampling,\r\n slimDOMOptions,\r\n iframeManager,\r\n stylesheetManager,\r\n canvasManager,\r\n keepIframeSrcFn,\r\n processedNodeManager,\r\n },\r\n mirror,\r\n });\r\n const takeFullSnapshot = (isCheckout = false) => {\r\n wrappedEmit({\r\n type: EventType.Meta,\r\n data: {\r\n href: window.location.href,\r\n width: getWindowWidth(),\r\n height: getWindowHeight(),\r\n },\r\n }, isCheckout);\r\n stylesheetManager.reset();\r\n shadowDomManager.init();\r\n mutationBuffers.forEach((buf) => buf.lock());\r\n const node = snapshot(document, {\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskAllInputs: maskInputOptions,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n slimDOM: slimDOMOptions,\r\n dataURLOptions,\r\n recordCanvas,\r\n inlineImages,\r\n onSerialize: (n) => {\r\n if (isSerializedIframe(n, mirror)) {\r\n iframeManager.addIframe(n);\r\n }\r\n if (isSerializedStylesheet(n, mirror)) {\r\n stylesheetManager.trackLinkElement(n);\r\n }\r\n if (hasShadowRoot(n)) {\r\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n iframeManager.attachIframe(iframe, childSn);\r\n shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (linkEl, childSn) => {\r\n stylesheetManager.attachLinkElement(linkEl, childSn);\r\n },\r\n keepIframeSrcFn,\r\n });\r\n if (!node) {\r\n return console.warn('Failed to snapshot the document');\r\n }\r\n wrappedEmit({\r\n type: EventType.FullSnapshot,\r\n data: {\r\n node,\r\n initialOffset: getWindowScroll(window),\r\n },\r\n });\r\n mutationBuffers.forEach((buf) => buf.unlock());\r\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\r\n stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));\r\n };\r\n _takeFullSnapshot = takeFullSnapshot;\r\n try {\r\n const handlers = [];\r\n const observe = (doc) => {\r\n return callbackWrapper(initObservers)({\r\n onMutation,\r\n mutationCb: wrappedMutationEmit,\r\n mousemoveCb: (positions, source) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source,\r\n positions,\r\n },\r\n }),\r\n mouseInteractionCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MouseInteraction,\r\n ...d,\r\n },\r\n }),\r\n scrollCb: wrappedScrollEmit,\r\n viewportResizeCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.ViewportResize,\r\n ...d,\r\n },\r\n }),\r\n inputCb: (v) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Input,\r\n ...v,\r\n },\r\n }),\r\n mediaInteractionCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MediaInteraction,\r\n ...p,\r\n },\r\n }),\r\n styleSheetRuleCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleSheetRule,\r\n ...r,\r\n },\r\n }),\r\n styleDeclarationCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleDeclaration,\r\n ...r,\r\n },\r\n }),\r\n canvasMutationCb: wrappedCanvasMutationEmit,\r\n fontCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Font,\r\n ...p,\r\n },\r\n }),\r\n selectionCb: (p) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Selection,\r\n ...p,\r\n },\r\n });\r\n },\r\n customElementCb: (c) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CustomElement,\r\n ...c,\r\n },\r\n });\r\n },\r\n blockClass,\r\n ignoreClass,\r\n ignoreSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskInputOptions,\r\n inlineStylesheet,\r\n sampling,\r\n recordCanvas,\r\n inlineImages,\r\n userTriggeredOnInput,\r\n collectFonts,\r\n doc,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n keepIframeSrcFn,\r\n blockSelector,\r\n unblockSelector,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n mirror,\r\n iframeManager,\r\n stylesheetManager,\r\n shadowDomManager,\r\n processedNodeManager,\r\n canvasManager,\r\n ignoreCSSAttributes,\r\n plugins: plugins\r\n ?.filter((p) => p.observer)\r\n ?.map((p) => ({\r\n observer: p.observer,\r\n options: p.options,\r\n callback: (payload) => wrappedEmit({\r\n type: EventType.Plugin,\r\n data: {\r\n plugin: p.name,\r\n payload,\r\n },\r\n }),\r\n })) || [],\r\n }, {});\r\n };\r\n iframeManager.addLoadListener((iframeEl) => {\r\n try {\r\n handlers.push(observe(iframeEl.contentDocument));\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n });\r\n const init = () => {\r\n takeFullSnapshot();\r\n handlers.push(observe(document));\r\n };\r\n if (document.readyState === 'interactive' ||\r\n document.readyState === 'complete') {\r\n init();\r\n }\r\n else {\r\n handlers.push(on('DOMContentLoaded', () => {\r\n wrappedEmit({\r\n type: EventType.DomContentLoaded,\r\n data: {},\r\n });\r\n if (recordAfter === 'DOMContentLoaded')\r\n init();\r\n }));\r\n handlers.push(on('load', () => {\r\n wrappedEmit({\r\n type: EventType.Load,\r\n data: {},\r\n });\r\n if (recordAfter === 'load')\r\n init();\r\n }, window));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n processedNodeManager.destroy();\r\n _takeFullSnapshot = undefined;\r\n unregisterErrorHandler();\r\n };\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n}\r\nfunction addCustomEvent(tag, payload) {\r\n if (!_wrappedEmit) {\r\n throw new Error('please add custom event after start recording');\r\n }\r\n wrappedEmit({\r\n type: EventType.Custom,\r\n data: {\r\n tag,\r\n payload,\r\n },\r\n });\r\n}\r\nfunction freezePage() {\r\n mutationBuffers.forEach((buf) => buf.freeze());\r\n}\r\nfunction takeFullSnapshot(isCheckout) {\r\n if (!_takeFullSnapshot) {\r\n throw new Error('please take full snapshot after start recording');\r\n }\r\n _takeFullSnapshot(isCheckout);\r\n}\r\nrecord.mirror = mirror;\r\nrecord.takeFullSnapshot = takeFullSnapshot;\r\nfunction _getCanvasManager(getCanvasManagerFn, options) {\r\n try {\r\n return getCanvasManagerFn\r\n ? getCanvasManagerFn(options)\r\n : new CanvasManagerNoop();\r\n }\r\n catch {\r\n console.warn('Unable to initialize CanvasManager');\r\n return new CanvasManagerNoop();\r\n }\r\n}\n\nexport { addCustomEvent, record as default, freezePage, mirror, takeFullSnapshot };\n","import { initMutationObserver, initScrollObserver, initAdoptedStyleSheetObserver } from './observer.js';\nimport { setTimeout, patch, inDom } from '../utils.js';\nimport { isNativeShadowDom } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nclass ShadowDomManagerNoop {\r\n init() {\r\n }\r\n addShadowRoot() {\r\n }\r\n observeAttachShadow() {\r\n }\r\n reset() {\r\n }\r\n}\r\nclass ShadowDomManager {\r\n constructor(options) {\r\n this.shadowDoms = new WeakSet();\r\n this.restoreHandlers = [];\r\n this.mutationCb = options.mutationCb;\r\n this.scrollCb = options.scrollCb;\r\n this.bypassOptions = options.bypassOptions;\r\n this.mirror = options.mirror;\r\n this.init();\r\n }\r\n init() {\r\n this.reset();\r\n this.patchAttachShadow(Element, document);\r\n }\r\n addShadowRoot(shadowRoot, doc) {\r\n if (!isNativeShadowDom(shadowRoot))\r\n return;\r\n if (this.shadowDoms.has(shadowRoot))\r\n return;\r\n this.shadowDoms.add(shadowRoot);\r\n const observer = initMutationObserver({\r\n ...this.bypassOptions,\r\n doc,\r\n mutationCb: this.mutationCb,\r\n mirror: this.mirror,\r\n shadowDomManager: this,\r\n }, shadowRoot);\r\n this.restoreHandlers.push(() => observer.disconnect());\r\n this.restoreHandlers.push(initScrollObserver({\r\n ...this.bypassOptions,\r\n scrollCb: this.scrollCb,\r\n doc: shadowRoot,\r\n mirror: this.mirror,\r\n }));\r\n setTimeout(() => {\r\n if (shadowRoot.adoptedStyleSheets &&\r\n shadowRoot.adoptedStyleSheets.length > 0)\r\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\r\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\r\n mirror: this.mirror,\r\n stylesheetManager: this.bypassOptions.stylesheetManager,\r\n }, shadowRoot));\r\n }, 0);\r\n }\r\n observeAttachShadow(iframeElement) {\r\n if (!iframeElement.contentWindow || !iframeElement.contentDocument)\r\n return;\r\n this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);\r\n }\r\n patchAttachShadow(element, doc) {\r\n const manager = this;\r\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {\r\n return function (option) {\r\n const shadowRoot = original.call(this, option);\r\n if (this.shadowRoot && inDom(this))\r\n manager.addShadowRoot(this.shadowRoot, doc);\r\n return shadowRoot;\r\n };\r\n }));\r\n }\r\n reset() {\r\n this.restoreHandlers.forEach((handler) => {\r\n try {\r\n handler();\r\n }\r\n catch (e) {\r\n }\r\n });\r\n this.restoreHandlers = [];\r\n this.shadowDoms = new WeakSet();\r\n }\r\n}\n\nexport { ShadowDomManager, ShadowDomManagerNoop };\n","import { onRequestAnimationFrame, isBlocked } from '../../../utils.js';\nimport { CanvasContext } from '../../../../../types/dist/rrweb-types.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\nimport { getImageBitmapDataUrlWorkerURL as t } from '../../../../../rrweb-worker/es/rrweb-worker/index.js';\nimport { callbackWrapper, registerErrorHandler } from '../../error-handler.js';\n\nclass CanvasManagerNoop {\r\n reset() {\r\n }\r\n freeze() {\r\n }\r\n unfreeze() {\r\n }\r\n lock() {\r\n }\r\n unlock() {\r\n }\r\n snapshot() {\r\n }\r\n}\r\nclass CanvasManager {\r\n reset() {\r\n this.pendingCanvasMutations.clear();\r\n this.resetObservers && this.resetObservers();\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n }\r\n lock() {\r\n this.locked = true;\r\n }\r\n unlock() {\r\n this.locked = false;\r\n }\r\n constructor(options) {\r\n this.pendingCanvasMutations = new Map();\r\n this.rafStamps = { latestId: 0, invokeId: null };\r\n this.frozen = false;\r\n this.locked = false;\r\n this.processMutation = (target, mutation) => {\r\n const newFrame = this.rafStamps.invokeId &&\r\n this.rafStamps.latestId !== this.rafStamps.invokeId;\r\n if (newFrame || !this.rafStamps.invokeId)\r\n this.rafStamps.invokeId = this.rafStamps.latestId;\r\n if (!this.pendingCanvasMutations.has(target)) {\r\n this.pendingCanvasMutations.set(target, []);\r\n }\r\n this.pendingCanvasMutations.get(target).push(mutation);\r\n };\r\n const { sampling = 'all', win, blockClass, blockSelector, unblockSelector, maxCanvasSize, recordCanvas, dataURLOptions, errorHandler, } = options;\r\n this.mutationCb = options.mutationCb;\r\n this.mirror = options.mirror;\r\n this.options = options;\r\n if (errorHandler) {\r\n registerErrorHandler(errorHandler);\r\n }\r\n if (options.enableManualSnapshot) {\r\n return;\r\n }\r\n callbackWrapper(() => {\r\n if (recordCanvas && sampling === 'all')\r\n this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector);\r\n if (recordCanvas && typeof sampling === 'number')\r\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, {\r\n dataURLOptions,\r\n });\r\n })();\r\n }\r\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options) {\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true);\r\n const rafId = this.takeSnapshot(false, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options.dataURLOptions);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) {\r\n this.startRAFTimestamping();\r\n this.startPendingCanvasMutationFlusher();\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false);\r\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector);\r\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n canvas2DReset();\r\n canvasWebGL1and2Reset();\r\n };\r\n }\r\n snapshot(canvasElement) {\r\n const { options } = this;\r\n const rafId = this.takeSnapshot(true, options.sampling === 'all' ? 2 : options.sampling || 2, options.win, options.blockClass, options.blockSelector, options.unblockSelector, options.maxCanvasSize, options.dataURLOptions, canvasElement);\r\n this.resetObservers = () => {\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n takeSnapshot(isManualSnapshot, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, dataURLOptions, canvasElement) {\r\n const snapshotInProgressMap = new Map();\r\n const worker = new Worker(t());\r\n worker.onmessage = (e) => {\r\n const data = e.data;\r\n const { id } = data;\r\n snapshotInProgressMap.set(id, false);\r\n if (!('base64' in data))\r\n return;\r\n const { base64, type, width, height } = data;\r\n this.mutationCb({\r\n id,\r\n type: CanvasContext['2D'],\r\n commands: [\r\n {\r\n property: 'clearRect',\r\n args: [0, 0, width, height],\r\n },\r\n {\r\n property: 'drawImage',\r\n args: [\r\n {\r\n rr_type: 'ImageBitmap',\r\n args: [\r\n {\r\n rr_type: 'Blob',\r\n data: [{ rr_type: 'ArrayBuffer', base64 }],\r\n type,\r\n },\r\n ],\r\n },\r\n 0,\r\n 0,\r\n width,\r\n height,\r\n ],\r\n },\r\n ],\r\n });\r\n };\r\n const timeBetweenSnapshots = 1000 / fps;\r\n let lastSnapshotTime = 0;\r\n let rafId;\r\n const getCanvas = (canvasElement) => {\r\n if (canvasElement) {\r\n return [canvasElement];\r\n }\r\n const matchedCanvas = [];\r\n win.document.querySelectorAll('canvas').forEach((canvas) => {\r\n if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector, true)) {\r\n matchedCanvas.push(canvas);\r\n }\r\n });\r\n return matchedCanvas;\r\n };\r\n const takeCanvasSnapshots = (timestamp) => {\r\n if (lastSnapshotTime &&\r\n timestamp - lastSnapshotTime < timeBetweenSnapshots) {\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return;\r\n }\r\n lastSnapshotTime = timestamp;\r\n getCanvas(canvasElement).forEach((canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n if (snapshotInProgressMap.get(id))\r\n return;\r\n if (!canvas.width || !canvas.height)\r\n return;\r\n snapshotInProgressMap.set(id, true);\r\n if (!isManualSnapshot &&\r\n ['webgl', 'webgl2'].includes(canvas.__context)) {\r\n const context = canvas.getContext(canvas.__context);\r\n if (context?.getContextAttributes()?.preserveDrawingBuffer === false) {\r\n context.clear(context.COLOR_BUFFER_BIT);\r\n }\r\n }\r\n createImageBitmap(canvas)\r\n .then((bitmap) => {\r\n worker.postMessage({\r\n id,\r\n bitmap,\r\n width: canvas.width,\r\n height: canvas.height,\r\n dataURLOptions,\r\n maxCanvasSize,\r\n }, [bitmap]);\r\n })\r\n .catch((error) => {\r\n callbackWrapper(() => {\r\n throw error;\r\n })();\r\n });\r\n });\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n };\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return rafId;\r\n }\r\n startPendingCanvasMutationFlusher() {\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n startRAFTimestamping() {\r\n const setLatestRAFTimestamp = (timestamp) => {\r\n this.rafStamps.latestId = timestamp;\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n };\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n }\r\n flushPendingCanvasMutations() {\r\n this.pendingCanvasMutations.forEach((values, canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n this.flushPendingCanvasMutationFor(canvas, id);\r\n });\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n flushPendingCanvasMutationFor(canvas, id) {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\r\n if (!valuesWithType || id === -1)\r\n return;\r\n const values = valuesWithType.map((value) => {\r\n const { type, ...rest } = value;\r\n return rest;\r\n });\r\n const { type } = valuesWithType[0];\r\n this.mutationCb({ id, type, commands: values });\r\n this.pendingCanvasMutations.delete(canvas);\r\n }\r\n}\n\nexport { CanvasManager, CanvasManagerNoop };\n","import { stringifyRule } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { StyleSheetMirror } from '../utils.js';\n\nclass StylesheetManager {\r\n constructor(options) {\r\n this.trackedLinkElements = new WeakSet();\r\n this.styleMirror = new StyleSheetMirror();\r\n this.mutationCb = options.mutationCb;\r\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\r\n }\r\n attachLinkElement(linkEl, childSn) {\r\n if ('_cssText' in childSn.attributes)\r\n this.mutationCb({\r\n adds: [],\r\n removes: [],\r\n texts: [],\r\n attributes: [\r\n {\r\n id: childSn.id,\r\n attributes: childSn\r\n .attributes,\r\n },\r\n ],\r\n });\r\n this.trackLinkElement(linkEl);\r\n }\r\n trackLinkElement(linkEl) {\r\n if (this.trackedLinkElements.has(linkEl))\r\n return;\r\n this.trackedLinkElements.add(linkEl);\r\n this.trackStylesheetInLinkElement(linkEl);\r\n }\r\n adoptStyleSheets(sheets, hostId) {\r\n if (sheets.length === 0)\r\n return;\r\n const adoptedStyleSheetData = {\r\n id: hostId,\r\n styleIds: [],\r\n };\r\n const styles = [];\r\n for (const sheet of sheets) {\r\n let styleId;\r\n if (!this.styleMirror.has(sheet)) {\r\n styleId = this.styleMirror.add(sheet);\r\n styles.push({\r\n styleId,\r\n rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\r\n rule: stringifyRule(r),\r\n index,\r\n })),\r\n });\r\n }\r\n else\r\n styleId = this.styleMirror.getId(sheet);\r\n adoptedStyleSheetData.styleIds.push(styleId);\r\n }\r\n if (styles.length > 0)\r\n adoptedStyleSheetData.styles = styles;\r\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\r\n }\r\n reset() {\r\n this.styleMirror.reset();\r\n this.trackedLinkElements = new WeakSet();\r\n }\r\n trackStylesheetInLinkElement(linkEl) {\r\n }\r\n}\n\nexport { StylesheetManager };\n","import { onRequestAnimationFrame } from '../utils.js';\n\nclass ProcessedNodeManager {\r\n constructor() {\r\n this.nodeMap = new WeakMap();\r\n this.loop = true;\r\n this.periodicallyClear();\r\n }\r\n periodicallyClear() {\r\n onRequestAnimationFrame(() => {\r\n this.clear();\r\n if (this.loop)\r\n this.periodicallyClear();\r\n });\r\n }\r\n inOtherBuffer(node, thisBuffer) {\r\n const buffers = this.nodeMap.get(node);\r\n return (buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer));\r\n }\r\n add(node, buffer) {\r\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\r\n }\r\n clear() {\r\n this.nodeMap = new WeakMap();\r\n }\r\n destroy() {\r\n this.loop = false;\r\n }\r\n}\n\nexport { ProcessedNodeManager as default };\n","type ClassOption = string | RegExp;\n\n/** Duplicate this from @sentry-internal/rrweb so we can export this as well. */\nexport const ReplayEventTypeDomContentLoaded = 0;\nexport const ReplayEventTypeLoad = 1;\nexport const ReplayEventTypeFullSnapshot = 2;\nexport const ReplayEventTypeIncrementalSnapshot = 3;\nexport const ReplayEventTypeMeta = 4;\nexport const ReplayEventTypeCustom = 5;\nexport const ReplayEventTypePlugin = 6;\n\nexport type ReplayEventType =\n | typeof ReplayEventTypeDomContentLoaded\n | typeof ReplayEventTypeLoad\n | typeof ReplayEventTypeFullSnapshot\n | typeof ReplayEventTypeIncrementalSnapshot\n | typeof ReplayEventTypeMeta\n | typeof ReplayEventTypeCustom\n | typeof ReplayEventTypePlugin;\n\n/**\n * This is a partial copy of rrweb's eventWithTime type which only contains the properties\n * we specifcally need in the SDK.\n */\nexport type ReplayEventWithTime = {\n type: ReplayEventType;\n data: unknown;\n timestamp: number;\n delay?: number;\n};\n\n/**\n * This is a partial copy of rrweb's recording options which only contains the properties\n * we specifically us in the SDK. Users can specify additional properties, hence we add the\n * Record union type.\n */\nexport type RrwebRecordOptions = {\n maskAllText?: boolean;\n maskAllInputs?: boolean;\n blockClass?: ClassOption;\n ignoreClass?: string;\n maskTextClass?: ClassOption;\n maskTextSelector?: string;\n blockSelector?: string;\n maskInputOptions?: Record;\n} & Record;\n\nexport interface CanvasManagerInterface {\n reset(): void;\n freeze(): void;\n unfreeze(): void;\n lock(): void;\n unlock(): void;\n snapshot(): void;\n}\n\nexport interface CanvasManagerOptions {\n recordCanvas: boolean;\n enableManualSnapshot?: boolean;\n blockClass: string | RegExp;\n blockSelector: string | null;\n unblockSelector: string | null;\n sampling?: 'all' | number;\n dataURLOptions: Partial<{\n type: string;\n quality: number;\n }>;\n mutationCb: (p: any) => void;\n win: typeof globalThis & Window;\n mirror: any;\n}\n","/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nexport function timestampToMs(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n\n/**\n * Converts a timestamp to s, if it was in ms, or keeps it as s.\n */\nexport function timestampToS(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../../types';\n\n/**\n * Add a breadcrumb event to replay.\n */\nexport function addBreadcrumbEvent(replay: ReplayContainer, breadcrumb: Breadcrumb): void {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category as string)) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1_000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n","import type { INode } from '@sentry-internal/rrweb-snapshot';\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/** Get the closest interactive parent element, or else return the given element. */\nexport function getClosestInteractive(element: Element): Element {\n const closestInteractive = element.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || element;\n}\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nexport function getClickTargetNode(event: Event | MouseEvent | Node): Node | INode | null {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n return getClosestInteractive(target);\n}\n\n/** Get the event target node. */\nexport function getTargetNode(event: Node | { target: EventTarget | null }): Node | INode | null {\n if (isEventWithTarget(event)) {\n return event.target as Node | null;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event: unknown): event is { target: EventTarget | null } {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n","import { fill } from '@sentry/utils';\n\nimport { WINDOW } from '../../constants';\n\ntype WindowOpenHandler = () => void;\n\nlet handlers: undefined | WindowOpenHandler[];\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nexport function onWindowOpen(cb: WindowOpenHandler): () => void {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers as WindowOpenHandler[]).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen(): void {\n fill(WINDOW, 'open', function (originalWindowOpen: () => void): () => void {\n return function (...args: unknown[]): void {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n","import { IncrementalSource, MouseInteractions, record } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\n\nimport { WINDOW } from '../constants';\nimport type {\n RecordingEvent,\n ReplayClickDetector,\n ReplayContainer,\n ReplayMultiClickFrame,\n ReplaySlowClickFrame,\n SlowClickConfig,\n} from '../types';\nimport { ReplayEventTypeIncrementalSnapshot } from '../types';\nimport { timestampToS } from '../util/timestamp';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClosestInteractive } from './util/domUtils';\nimport { onWindowOpen } from './util/onWindowOpen';\n\ntype ClickBreadcrumb = Breadcrumb & {\n timestamp: number;\n};\n\ninterface Click {\n timestamp: number;\n mutationAfter?: number;\n scrollAfter?: number;\n clickBreadcrumb: ClickBreadcrumb;\n clickCount: number;\n node: HTMLElement;\n}\n\ntype IncrementalRecordingEvent = RecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { source: IncrementalSource };\n};\n\ntype IncrementalMouseInteractionRecordingEvent = IncrementalRecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { type: MouseInteractions; id: number };\n};\n\n/** Handle a click. */\nexport function handleClick(clickDetector: ReplayClickDetector, clickBreadcrumb: Breadcrumb, node: HTMLElement): void {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nexport class ClickDetector implements ReplayClickDetector {\n // protected for testing\n protected _lastMutation: number;\n protected _lastScroll: number;\n\n private _clicks: Click[];\n private _teardown: undefined | (() => void);\n\n private _threshold: number;\n private _scollTimeout: number;\n private _timeout: number;\n private _ignoreSelector: string;\n\n private _replay: ReplayContainer;\n private _checkClickTimeout?: ReturnType;\n private _addBreadcrumbEvent: typeof addBreadcrumbEvent;\n\n public constructor(\n replay: ReplayContainer,\n slowClickConfig: SlowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n this._lastMutation = 0;\n this._lastScroll = 0;\n this._clicks = [];\n\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n public addListeners(): void {\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n this._teardown = () => {\n cleanupWindowOpen();\n\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n public removeListeners(): void {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** @inheritDoc */\n public handleClick(breadcrumb: Breadcrumb, node: HTMLElement): void {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const newClick: Click = {\n timestamp: timestampToS(breadcrumb.timestamp),\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n\n // If there was a click in the last 1s on the same element, ignore it - only keep a single reference per second\n if (\n this._clicks.some(click => click.node === newClick.node && Math.abs(click.timestamp - newClick.timestamp) < 1)\n ) {\n return;\n }\n\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** @inheritDoc */\n public registerMutation(timestamp = Date.now()): void {\n this._lastMutation = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerScroll(timestamp = Date.now()): void {\n this._lastScroll = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerClick(element: HTMLElement): void {\n const node = getClosestInteractive(element);\n this._handleMultiClick(node as HTMLElement);\n }\n\n /** Count multiple clicks on elements. */\n private _handleMultiClick(node: HTMLElement): void {\n this._getClicks(node).forEach(click => {\n click.clickCount++;\n });\n }\n\n /** Get all pending clicks for a given node. */\n private _getClicks(node: HTMLElement): Click[] {\n return this._clicks.filter(click => click.node === node);\n }\n\n /** Check the clicks that happened. */\n private _checkClicks(): void {\n const timedOutClicks: Click[] = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // All of these are in seconds!\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n const pos = this._clicks.indexOf(click);\n\n if (pos > -1) {\n this._generateBreadcrumbs(click);\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n private _generateBreadcrumbs(click: Click): void {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb: ReplaySlowClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb: ReplayMultiClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n private _scheduleCheckClicks(): void {\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n\n this._checkClickTimeout = setTimeout(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nexport function ignoreElement(node: HTMLElement, ignoreSelector: string): boolean {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is ClickBreadcrumb {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds(): number {\n return Date.now() / 1000;\n}\n\n/** Update the click detector based on a recording event of rrweb. */\nexport function updateClickDetectorForRecordingEvent(clickDetector: ReplayClickDetector, event: RecordingEvent): void {\n try {\n // note: We only consider incremental snapshots here\n // This means that any full snapshot is ignored for mutation detection - the reason is that we simply cannot know if a mutation happened here.\n // E.g. think that we are buffering, an error happens and we take a full snapshot because we switched to session mode -\n // in this scenario, we would not know if a dead click happened because of the error, which is a key dead click scenario.\n // Instead, by ignoring full snapshots, we have the risk that we generate a false positive\n // (if a mutation _did_ happen but was \"swallowed\" by the full snapshot)\n // But this should be more unlikely as we'd generally capture the incremental snapshot right away\n\n if (!isIncrementalEvent(event)) {\n return;\n }\n\n const { source } = event.data;\n if (source === IncrementalSource.Mutation) {\n clickDetector.registerMutation(event.timestamp);\n }\n\n if (source === IncrementalSource.Scroll) {\n clickDetector.registerScroll(event.timestamp);\n }\n\n if (isIncrementalMouseInteraction(event)) {\n const { type, id } = event.data;\n const node = record.mirror.getNode(id);\n\n if (node instanceof HTMLElement && type === MouseInteractions.Click) {\n clickDetector.registerClick(node);\n }\n }\n } catch {\n // ignore errors here, e.g. if accessing something that does not exist\n }\n}\n\nfunction isIncrementalEvent(event: RecordingEvent): event is IncrementalRecordingEvent {\n return event.type === ReplayEventTypeIncrementalSnapshot;\n}\n\nfunction isIncrementalMouseInteraction(\n event: IncrementalRecordingEvent,\n): event is IncrementalMouseInteractionRecordingEvent {\n return event.data.source === IncrementalSource.MouseInteraction;\n}\n","var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction classMatchesRegex(node, regex, checkAncestors) {\r\n if (!node)\r\n return false;\r\n if (checkAncestors) {\r\n return (distanceToMatch(node, (node) => elementClassMatchesRegex(node, regex)) >= 0);\r\n }\r\n else if (node.nodeType === node.ELEMENT_NODE) {\r\n return elementClassMatchesRegex(node, regex);\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\nfunction visitSnapshot(node, onVisit) {\r\n function walk(current) {\r\n onVisit(current);\r\n if (current.type === NodeType.Document ||\r\n current.type === NodeType.Element) {\r\n current.childNodes.forEach(walk);\r\n }\r\n }\r\n walk(node);\r\n}\r\nfunction cleanupSnapshot() {\r\n _id = 1;\r\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, classMatchesRegex, cleanupSnapshot, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute, visitSnapshot };\n","import type { ReplayBreadcrumbFrame } from '../types/replayFrame';\n\n/**\n * Create a breadcrumb for a replay.\n */\nexport function createBreadcrumb(\n breadcrumb: Omit & Partial>,\n): ReplayBreadcrumbFrame {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n","// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n 'data-sentry-component',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nexport function getAttributesToRecord(attributes: Record): Record {\n const obj: Record = {};\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n","import { record } from '@sentry-internal/rrweb';\nimport type { serializedElementNodeWithId, serializedNodeWithId } from '@sentry-internal/rrweb-snapshot';\nimport { NodeType } from '@sentry-internal/rrweb-snapshot';\nimport type { Breadcrumb, HandlerDataDom } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { handleClick } from './handleClick';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClickTargetNode, getTargetNode } from './util/domUtils';\nimport { getAttributesToRecord } from './util/getAttributesToRecord';\n\nexport const handleDomListener: (replay: ReplayContainer) => (handlerData: HandlerDataDom) => void = (\n replay: ReplayContainer,\n) => {\n return (handlerData: HandlerDataDom): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick ? (handlerData.event as PointerEvent) : undefined;\n // Ignore clicks if ctrl/alt/meta/shift keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (\n isClick &&\n replay.clickDetector &&\n event &&\n event.target &&\n !event.altKey &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n handleClick(\n replay.clickDetector,\n result as Breadcrumb & { timestamp: number; data: { nodeId: number } },\n getClickTargetNode(handlerData.event as Event) as HTMLElement,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nexport function getBaseDomBreadcrumb(target: Node | null, message: string): Breadcrumb {\n const nodeId = record.mirror.getId(target);\n const node = nodeId && record.mirror.getNode(nodeId);\n const meta = node && record.mirror.getMeta(node);\n const element = meta && isElement(meta) ? meta : null;\n\n return {\n message,\n data: element\n ? {\n nodeId,\n node: {\n id: nodeId,\n tagName: element.tagName,\n textContent: Array.from(element.childNodes)\n .map((node: serializedNodeWithId) => node.type === NodeType.Text && node.textContent)\n .filter(Boolean) // filter out empty values\n .map(text => (text as string).trim())\n .join(''),\n attributes: getAttributesToRecord(element.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nexport function handleDom(handlerData: HandlerDataDom): Breadcrumb | null {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData: HandlerDataDom): { target: Node | null; message: string } {\n const isClick = handlerData.name === 'click';\n\n let message: string | undefined;\n let target: Node | null = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event as Event) : getTargetNode(handlerData.event as Event);\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isElement(node: serializedNodeWithId): node is serializedElementNodeWithId {\n return node.type === NodeType.Element;\n}\n","import { record } from '@sentry-internal/rrweb';\nimport { browserPerformanceTimeOrigin } from '@sentry/utils';\n\nimport { WINDOW } from '../constants';\nimport type {\n AllPerformanceEntry,\n AllPerformanceEntryData,\n ExperimentalPerformanceResourceTiming,\n LargestContentfulPaintData,\n NavigationData,\n PaintData,\n ReplayPerformanceEntry,\n ResourceData,\n} from '../types';\n\n// Map entryType -> function to normalize data for event\nconst ENTRY_TYPES: Record<\n string,\n (entry: AllPerformanceEntry) => null | ReplayPerformanceEntry\n> = {\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nexport function createPerformanceEntries(\n entries: AllPerformanceEntry[],\n): ReplayPerformanceEntry[] {\n return entries.map(createPerformanceEntry).filter(Boolean) as ReplayPerformanceEntry[];\n}\n\nfunction createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEntry | null {\n if (!ENTRY_TYPES[entry.entryType]) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time: number): number {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry: PerformanceNavigationTiming): ReplayPerformanceEntry | null {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry: ExperimentalPerformanceResourceTiming,\n): ReplayPerformanceEntry | null {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\n/**\n * Add a LCP event to the replay based on an LCP metric.\n */\nexport function getLargestContentfulPaint(metric: {\n value: number;\n entries: PerformanceEntry[];\n}): ReplayPerformanceEntry {\n const entries = metric.entries;\n const lastEntry = entries[entries.length - 1] as (PerformanceEntry & { element?: Element }) | undefined;\n const element = lastEntry ? lastEntry.element : undefined;\n\n const value = metric.value;\n\n const end = getAbsoluteTime(value);\n\n const data: ReplayPerformanceEntry = {\n type: 'largest-contentful-paint',\n name: 'largest-contentful-paint',\n start: end,\n end,\n data: {\n value,\n size: value,\n nodeId: element ? record.mirror.getId(element) : undefined,\n },\n };\n\n return data;\n}\n","import { addLcpInstrumentationHandler, addPerformanceInstrumentationHandler } from '@sentry-internal/tracing';\n\nimport type { ReplayContainer } from '../types';\nimport { getLargestContentfulPaint } from '../util/createPerformanceEntries';\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n * Returns a callback to stop observing.\n */\nexport function setupPerformanceObserver(replay: ReplayContainer): () => void {\n function addPerformanceEntry(entry: PerformanceEntry): void {\n // It is possible for entries to come up multiple times\n if (!replay.performanceEntries.includes(entry)) {\n replay.performanceEntries.push(entry);\n }\n }\n\n function onEntries({ entries }: { entries: PerformanceEntry[] }): void {\n entries.forEach(addPerformanceEntry);\n }\n\n const clearCallbacks: (() => void)[] = [];\n\n (['navigation', 'paint', 'resource'] as const).forEach(type => {\n clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));\n });\n\n clearCallbacks.push(\n addLcpInstrumentationHandler(({ metric }) => {\n replay.replayPerformanceEntries.push(getLargestContentfulPaint(metric));\n }),\n );\n\n // A callback to cleanup all handlers\n return () => {\n clearCallbacks.forEach(clearCallback => clearCallback());\n };\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { addBreadcrumb } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Log a message in debug mode, and add a breadcrumb when _experiment.traceInternals is enabled.\n */\nexport function logInfo(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n addLogBreadcrumb(message);\n }\n}\n\n/**\n * Log a message, and add a breadcrumb in the next tick.\n * This is necessary when the breadcrumb may be added before the replay is initialized.\n */\nexport function logInfoNextTick(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => {\n addLogBreadcrumb(message);\n }, 0);\n }\n}\n\nfunction addLogBreadcrumb(message: string): void {\n addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level: 'info',\n message,\n },\n { level: 'info' },\n );\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nexport class EventBufferSizeExceededError extends Error {\n public constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nexport class EventBufferArray implements EventBuffer {\n /** All the events that are buffered to be sent. */\n public events: RecordingEvent[];\n\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _totalSize: number;\n\n public constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'sync';\n }\n\n /** @inheritdoc */\n public destroy(): void {\n this.events = [];\n }\n\n /** @inheritdoc */\n public async addEvent(event: RecordingEvent): Promise {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n public finish(): Promise {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n public clear(): void {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n","import { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WorkerRequest, WorkerResponse } from '../types';\nimport { logInfo } from '../util/log';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class WorkerHandler {\n private _worker: Worker;\n private _id: number;\n private _ensureReadyPromise?: Promise;\n\n public constructor(worker: Worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }: MessageEvent) => {\n if ((data as WorkerResponse).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n public destroy(): void {\n logInfo('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n public postMessage(method: WorkerRequest['method'], arg?: WorkerRequest['arg']): Promise {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }: MessageEvent): void => {\n const response = data as WorkerResponse;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n DEBUG_BUILD && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response as T);\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n private _getAndIncrementId(): number {\n return this._id++;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\nimport { logger } from '@sentry/utils';\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { WorkerHandler } from './WorkerHandler';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class EventBufferCompressionWorker implements EventBuffer {\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _worker: WorkerHandler;\n private _earliestTimestamp: number | null;\n private _totalSize;\n\n public constructor(worker: Worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n public destroy(): void {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n public addEvent(event: RecordingEvent): Promise {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n public finish(): Promise {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n public clear(): void {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n this._worker.postMessage('clear').then(null, e => {\n DEBUG_BUILD && logger.warn('[Replay] Sending \"clear\" message to worker failed', e);\n });\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n private _sendEventToWorker(data: string): Promise {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n private async _finishRequest(): Promise {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferCompressionWorker } from './EventBufferCompressionWorker';\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nexport class EventBufferProxy implements EventBuffer {\n private _fallback: EventBufferArray;\n private _compression: EventBufferCompressionWorker;\n private _used: EventBuffer;\n private _ensureWorkerIsLoadedPromise: Promise;\n\n public constructor(worker: Worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return this._used.type;\n }\n\n /** @inheritDoc */\n public get hasEvents(): boolean {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n public get hasCheckout(): boolean {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n public set hasCheckout(value: boolean) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritDoc */\n public destroy(): void {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n public clear(): void {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n public addEvent(event: RecordingEvent): Promise {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n public async finish(): Promise {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n public ensureWorkerIsLoaded(): Promise {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n private async _ensureWorkerIsLoaded(): Promise {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n logInfo('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n private async _switchToCompressionWorker(): Promise {\n const { events, hasCheckout } = this._fallback;\n\n const addEventPromises: Promise[] = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n this._compression.hasCheckout = hasCheckout;\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n","import { WINDOW } from '../constants';\n\n/** If sessionStorage is available. */\nexport function hasSessionStorage(): boolean {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch {\n return false;\n }\n}\n","/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nexport function isSampled(sampleRate?: number): boolean {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n","import { uuid4 } from '@sentry/utils';\n\nimport type { Sampled, Session } from '../types';\n\n/**\n * Get a session with defaults & applied sampling.\n */\nexport function makeSession(session: Partial & { sampled: Sampled }): Session {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const previousSessionId = session.previousSessionId;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n };\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Save a session to session storage.\n */\nexport function saveSession(session: Session): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import type { Sampled, Session, SessionOptions } from '../types';\nimport { isSampled } from '../util/isSampled';\nimport { makeSession } from './Session';\nimport { saveSession } from './saveSession';\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nexport function getSessionSampleType(sessionSampleRate: number, allowBuffering: boolean): Sampled {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nexport function createSession(\n { sessionSampleRate, allowBuffering, stickySession = false }: SessionOptions,\n { previousSessionId }: { previousSessionId?: string } = {},\n): Session {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n previousSessionId,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n","/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nexport function isExpired(\n initialTime: null | number,\n expiry: undefined | number,\n targetTime: number = +new Date(),\n): boolean {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n","import type { Session } from '../types';\nimport { isExpired } from './isExpired';\n\n/**\n * Checks to see if session is expired\n */\nexport function isSessionExpired(\n session: Session,\n {\n maxReplayDuration,\n sessionIdleExpire,\n targetTime = Date.now(),\n }: { maxReplayDuration: number; sessionIdleExpire: number; targetTime?: number },\n): boolean {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, maxReplayDuration, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, sessionIdleExpire, targetTime)\n );\n}\n","import type { Session } from '../types';\nimport { isSessionExpired } from '../util/isSessionExpired';\n\n/** If the session should be refreshed or not. */\nexport function shouldRefreshSession(\n session: Session,\n { sessionIdleExpire, maxReplayDuration }: { sessionIdleExpire: number; maxReplayDuration: number },\n): boolean {\n // If not expired, all good, just keep the session\n if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) {\n return false;\n }\n\n // If we are buffering & haven't ever flushed yet, always continue\n if (session.sampled === 'buffer' && session.segmentId === 0) {\n return false;\n }\n\n return true;\n}\n","import type { Session, SessionOptions } from '../types';\nimport { logInfoNextTick } from '../util/log';\nimport { createSession } from './createSession';\nimport { fetchSession } from './fetchSession';\nimport { shouldRefreshSession } from './shouldRefreshSession';\n\n/**\n * Get or create a session, when initializing the replay.\n * Returns a session that may be unsampled.\n */\nexport function loadOrCreateSession(\n {\n traceInternals,\n sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }: {\n sessionIdleExpire: number;\n maxReplayDuration: number;\n traceInternals?: boolean;\n previousSessionId?: string;\n },\n sessionOptions: SessionOptions,\n): Session {\n const existingSession = sessionOptions.stickySession && fetchSession(traceInternals);\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n logInfoNextTick('[Replay] Creating new session', traceInternals);\n return createSession(sessionOptions, { previousSessionId });\n }\n\n if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {\n return existingSession;\n }\n\n logInfoNextTick('[Replay] Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\nimport { logInfoNextTick } from '../util/log';\nimport { makeSession } from './Session';\n\n/**\n * Fetches a session from storage\n */\nexport function fetchSession(traceInternals?: boolean): Session | null {\n if (!hasSessionStorage()) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) as Session;\n\n logInfoNextTick('[Replay] Loading existing session', traceInternals);\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { getClient } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { EventBufferSizeExceededError } from '../eventBuffer/error';\nimport type { AddEventResult, RecordingEvent, ReplayContainer, ReplayFrameEvent, ReplayPluginOptions } from '../types';\nimport { logInfo } from './log';\nimport { timestampToMs } from './timestamp';\n\nfunction isCustomEvent(event: RecordingEvent): event is ReplayFrameEvent {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * In contrast to `addEvent`, this does not return a promise & does not wait for the adding of the event to succeed/fail.\n * Instead this returns `true` if we tried to add the event, else false.\n * It returns `false` e.g. if we are paused, disabled, or out of the max replay duration.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEventSync(replay: ReplayContainer, event: RecordingEvent, isCheckout?: boolean): boolean {\n if (!shouldAddEvent(replay, event)) {\n return false;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n _addEvent(replay, event, isCheckout);\n\n return true;\n}\n\n/**\n * Add an event to the event buffer.\n * Resolves to `null` if no event was added, else to `void`.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!shouldAddEvent(replay, event)) {\n return Promise.resolve(null);\n }\n\n return _addEvent(replay, event, isCheckout);\n}\n\nasync function _addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!replay.eventBuffer) {\n return null;\n }\n\n try {\n if (isCheckout && replay.recordingMode === 'buffer') {\n replay.eventBuffer.clear();\n }\n\n if (isCheckout) {\n replay.eventBuffer.hasCheckout = true;\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await replay.eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const reason = error && error instanceof EventBufferSizeExceededError ? 'addEventSizeExceeded' : 'addEvent';\n\n DEBUG_BUILD && logger.error(error);\n await replay.stop({ reason });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\n/** Exported only for tests. */\nexport function shouldAddEvent(replay: ReplayContainer, event: RecordingEvent): boolean {\n if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) {\n return false;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return false;\n }\n\n // Throw out events that are +60min from the initial timestamp\n if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) {\n logInfo(\n `[Replay] Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`,\n replay.getOptions()._experiments.traceInternals,\n );\n return false;\n }\n\n return true;\n}\n\nfunction maybeApplyCallback(\n event: RecordingEvent,\n callback: ReplayPluginOptions['beforeAddRecordingEvent'],\n): RecordingEvent | null | undefined {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n DEBUG_BUILD &&\n logger.error('[Replay] An error occured in the `beforeAddRecordingEvent` callback, skipping the event...', error);\n return null;\n }\n\n return event;\n}\n","import type { ErrorEvent, Event, FeedbackEvent, ReplayEvent, TransactionEvent } from '@sentry/types';\n\n/** If the event is an error event */\nexport function isErrorEvent(event: Event): event is ErrorEvent {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nexport function isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nexport function isReplayEvent(event: Event): event is ReplayEvent {\n return event.type === 'replay_event';\n}\n\n/** If the event is a feedback event */\nexport function isFeedbackEvent(event: Event): event is FeedbackEvent {\n return event.type === 'feedback';\n}\n","import { getClient } from '@sentry/core';\nimport type { ErrorEvent, Event, TransactionEvent, Transport, TransportMakeRequestResponse } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isTransactionEvent } from '../util/eventUtils';\n\ntype AfterSendEventCallback = (event: Event, sendResponse: TransportMakeRequestResponse | void) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleAfterSendEvent(replay: ReplayContainer): AfterSendEventCallback {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event: Event, sendResponse: TransportMakeRequestResponse | void) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n if (isTransactionEvent(event)) {\n handleTransactionEvent(replay, event);\n return;\n }\n\n handleErrorEvent(replay, event);\n };\n}\n\nfunction handleTransactionEvent(replay: ReplayContainer, event: TransactionEvent): void {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id as string);\n }\n}\n\nfunction handleErrorEvent(replay: ReplayContainer, event: ErrorEvent): void {\n const replayContext = replay.getContext();\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n // We limit to max. 100 errors linked\n if (event.event_id && replayContext.errorIds.size < 100) {\n replayContext.errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode !== 'buffer' || !event.tags || !event.tags.replayId) {\n return;\n }\n\n const { beforeErrorSampling } = replay.getOptions();\n if (typeof beforeErrorSampling === 'function' && !beforeErrorSampling(event)) {\n return;\n }\n\n setTimeout(() => {\n // Capture current event buffer as new replay\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.sendBufferedReplayOrFlush();\n });\n}\n\nfunction isBaseTransportSend(): boolean {\n const client = getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send as Transport['send'] & { __sentry__baseTransport__?: true }).__sentry__baseTransport__ || false\n );\n}\n","import { EventType } from '@sentry-internal/rrweb';\n\nimport type { AddEventResult, AllEntryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\n\n/**\n * Create a \"span\" for each performance entry.\n */\nexport function createPerformanceSpans(\n replay: ReplayContainer,\n entries: ReplayPerformanceEntry[],\n): Promise[] {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n","import type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../../types';\nimport { createPerformanceSpans } from '../../util/createPerformanceSpans';\nimport { shouldFilterRequest } from '../../util/shouldFilterRequest';\n\n/** Add a performance entry breadcrumb */\nexport function addNetworkBreadcrumb(\n replay: ReplayContainer,\n result: ReplayPerformanceEntry | null,\n): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n","import { getClient, isSentryRequestUrl } from '@sentry/core';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nexport function shouldFilterRequest(replay: ReplayContainer, url: string): boolean {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (DEBUG_BUILD && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return isSentryRequestUrl(url, getClient());\n}\n","import type { TextEncoderInternal } from '@sentry/types';\nimport { dropUndefinedKeys, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { NETWORK_BODY_MAX_SIZE, WINDOW } from '../../constants';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkBody,\n NetworkMetaWarning,\n NetworkRequestData,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n ReplayPerformanceEntry,\n} from '../../types';\n\n/** Get the size of a body. */\nexport function getBodySize(\n body: RequestInit['body'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nexport function parseContentLengthHeader(header: string | null | undefined): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nexport function getBodyString(body: unknown): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof URLSearchParams) {\n return [body.toString()];\n }\n\n if (body instanceof FormData) {\n return [_serializeFormData(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/** Merge a warning into an existing network request/response. */\nexport function mergeWarning(\n info: ReplayNetworkRequestOrResponse | undefined,\n warning: NetworkMetaWarning,\n): ReplayNetworkRequestOrResponse {\n if (!info) {\n return {\n headers: {},\n size: undefined,\n _meta: {\n warnings: [warning],\n },\n };\n }\n\n const newMeta = { ...info._meta };\n const existingWarnings = newMeta.warnings || [];\n newMeta.warnings = [...existingWarnings, warning];\n\n info._meta = newMeta;\n return info;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nexport function makeNetworkReplayBreadcrumb(\n type: string,\n data: ReplayNetworkRequestData | null,\n): ReplayPerformanceEntry | null {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result: ReplayPerformanceEntry = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nexport function buildSkippedNetworkRequestOrResponse(bodySize: number | undefined): ReplayNetworkRequestOrResponse {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nexport function buildNetworkRequestOrResponse(\n headers: Record,\n bodySize: number | undefined,\n body: string | undefined,\n): ReplayNetworkRequestOrResponse | undefined {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info: ReplayNetworkRequestOrResponse = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings && warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nexport function getAllowedHeaders(headers: Record, allowedHeaders: string[]): Record {\n return Object.keys(headers).reduce((filteredHeaders: Record, key: string) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData: FormData): string {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body: string | undefined): {\n body: NetworkBody | undefined;\n warnings?: NetworkMetaWarning[];\n} {\n if (!body || typeof body !== 'string') {\n return {\n body,\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n const isProbablyJson = _strIsProbablyJson(body);\n\n if (exceedsSizeLimit) {\n const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE);\n\n if (isProbablyJson) {\n return {\n body: truncatedBody,\n warnings: ['MAYBE_JSON_TRUNCATED'],\n };\n }\n\n return {\n body: `${truncatedBody}…`,\n warnings: ['TEXT_TRUNCATED'],\n };\n }\n\n if (isProbablyJson) {\n try {\n const jsonBody = JSON.parse(body);\n return {\n body: jsonBody,\n };\n } catch {\n // fall back to just send the body as string\n }\n }\n\n return {\n body,\n };\n}\n\nfunction _strIsProbablyJson(str: string): boolean {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nexport function urlMatches(url: string, urls: (string | RegExp)[]): boolean {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nexport function getFullUrl(url: string, baseURI = WINDOW.document.baseURI): string {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n","import type { Breadcrumb, FetchBreadcrumbData, TextEncoderInternal } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n FetchHint,\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureFetchBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n replay: ReplayContainer;\n },\n): Promise {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichFetchBreadcrumb(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { input, response } = hint;\n\n const body = input ? _getFetchRequestArgBody(input) : undefined;\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n): Promise {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails =\n urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders }: ReplayNetworkOptions,\n input: FetchHint['input'] | undefined,\n requestBodySize?: number,\n): ReplayNetworkRequestOrResponse | undefined {\n const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const [bodyStr, warning] = getBodyString(requestBody);\n const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n\n if (warning) {\n return mergeWarning(data, warning);\n }\n\n return data;\n}\n\n/** Exported only for tests. */\nexport async function _getResponseInfo(\n captureDetails: boolean,\n {\n networkCaptureBodies,\n textEncoder,\n networkResponseHeaders,\n }: Pick & {\n textEncoder: TextEncoderInternal;\n },\n response: Response | undefined,\n responseBodySize?: number,\n): Promise {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {};\n\n if (!response || (!networkCaptureBodies && responseBodySize !== undefined)) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n const [bodyText, warning] = await _parseFetchResponseBody(response);\n const result = getResponseData(bodyText, {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n });\n\n if (warning) {\n return mergeWarning(result, warning);\n }\n\n return result;\n}\n\nfunction getResponseData(\n bodyText: string | undefined,\n {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n }: {\n captureDetails: boolean;\n networkCaptureBodies: boolean;\n responseBodySize: number | undefined;\n headers: Record;\n textEncoder: TextEncoderInternal;\n },\n): ReplayNetworkRequestOrResponse | undefined {\n try {\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize response body', error);\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchResponseBody(response: Response): Promise<[string | undefined, NetworkMetaWarning?]> {\n const res = _tryCloneResponse(response);\n\n if (!res) {\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n try {\n const text = await _tryGetResponseText(res);\n return [text];\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to get text body from response', error);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs: unknown[] = []): RequestInit['body'] | undefined {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] as RequestInit).body;\n}\n\nfunction getAllHeaders(headers: Headers, allowedHeaders: string[]): Record {\n const allHeaders: Record = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) as string;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs: unknown[], allowedHeaders: string[]): Record {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] as Request | RequestInit, allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] as Request | RequestInit, allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input: Request | RequestInit | undefined,\n allowedHeaders: string[],\n): Record {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\nfunction _tryCloneResponse(response: Response): Response | void {\n try {\n // We have to clone this, as the body can only be read once\n return response.clone();\n } catch (error) {\n // this can throw if the response was already consumed before\n DEBUG_BUILD && logger.warn('[Replay] Failed to clone response body', error);\n }\n}\n\n/**\n * Get the response body of a fetch request, or timeout after 500ms.\n * Fetch can return a streaming body, that may not resolve (or not for a long time).\n * If that happens, we rather abort after a short time than keep waiting for this.\n */\nfunction _tryGetResponseText(response: Response): Promise {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error('Timeout while trying to read response body')), 500);\n\n _getResponseText(response)\n .then(\n txt => resolve(txt),\n reason => reject(reason),\n )\n .finally(() => clearTimeout(timeout));\n });\n\n return _getResponseText(response);\n}\n\nasync function _getResponseText(response: Response): Promise {\n // Force this to be a promise, just to be safe\n // eslint-disable-next-line no-return-await\n return await response.text();\n}\n","import type { Breadcrumb, TextEncoderInternal, XhrBreadcrumbData } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n XhrHint,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureXhrBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & { replay: ReplayContainer },\n): Promise {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture xhr breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichXhrBreadcrumb(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { xhr, input } = hint;\n\n if (!xhr) {\n return;\n }\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : _getBodySize(xhr.response, xhr.responseType, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions,\n): ReplayNetworkRequestData | null {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input) : [undefined];\n const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [undefined];\n\n const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);\n const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request: requestWarning ? mergeWarning(request, requestWarning) : request,\n response: responseWarning ? mergeWarning(response, responseWarning) : response,\n };\n}\n\nfunction getResponseHeaders(xhr: XMLHttpRequest): Record {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record, line: string) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n\nfunction _getXhrResponseBody(xhr: XMLHttpRequest): [string | undefined, NetworkMetaWarning?] {\n // We collect errors that happen, but only log them if we can't get any response body\n const errors: unknown[] = [];\n\n try {\n return [xhr.responseText];\n } catch (e) {\n errors.push(e);\n }\n\n // Try to manually parse the response body, if responseText fails\n try {\n return _parseXhrResponse(xhr.response, xhr.responseType);\n } catch (e) {\n errors.push(e);\n }\n\n DEBUG_BUILD && logger.warn('[Replay] Failed to get xhr response body', ...errors);\n\n return [undefined];\n}\n\n/**\n * Get the string representation of the XHR response.\n * Based on MDN, these are the possible types of the response:\n * string\n * ArrayBuffer\n * Blob\n * Document\n * POJO\n *\n * Exported only for tests.\n */\nexport function _parseXhrResponse(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof Document) {\n return [body.body.outerHTML];\n }\n\n if (responseType === 'json' && body && typeof body === 'object') {\n return [JSON.stringify(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\nfunction _getBodySize(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr, textEncoder);\n } catch {\n return undefined;\n }\n}\n","import { getClient } from '@sentry/core';\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n FetchBreadcrumbData,\n TextEncoderInternal,\n XhrBreadcrumbData,\n} from '@sentry/types';\nimport { addFetchInstrumentationHandler, addXhrInstrumentationHandler, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { FetchHint, ReplayContainer, ReplayNetworkOptions, XhrHint } from '../types';\nimport { handleFetchSpanListener } from './handleFetch';\nimport { handleXhrSpanListener } from './handleXhr';\nimport { captureFetchBreadcrumbToReplay, enrichFetchBreadcrumb } from './util/fetchUtils';\nimport { captureXhrBreadcrumbToReplay, enrichXhrBreadcrumb } from './util/xhrUtils';\n\ninterface ExtendedNetworkBreadcrumbsOptions extends ReplayNetworkOptions {\n replay: ReplayContainer;\n textEncoder: TextEncoderInternal;\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nexport function handleNetworkBreadcrumbs(replay: ReplayContainer): void {\n const client = getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options: ExtendedNetworkBreadcrumbsOptions = {\n replay,\n textEncoder,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addFetchInstrumentationHandler(handleFetchSpanListener(replay));\n addXhrInstrumentationHandler(handleXhrSpanListener(replay));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nexport function beforeAddNetworkBreadcrumb(\n options: ExtendedNetworkBreadcrumbsOptions,\n breadcrumb: Breadcrumb,\n hint?: BreadcrumbHint,\n): void {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n DEBUG_BUILD && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: XhrBreadcrumbData } {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: FetchBreadcrumbData } {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint?: BreadcrumbHint): hint is XhrHint {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint?: BreadcrumbHint): hint is FetchHint {\n return hint && hint.response;\n}\n","import type { HandlerDataFetch } from '@sentry/types';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleFetch(handlerData: HandlerDataFetch): null | ReplayPerformanceEntry {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response ? (response as Response).status : undefined,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addFetchInstrumentationHandler(listener)`.\n */\nexport function handleFetchSpanListener(replay: ReplayContainer): (handlerData: HandlerDataFetch) => void {\n return (handlerData: HandlerDataFetch) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { HandlerDataXhr } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleXhr(handlerData: HandlerDataXhr): ReplayPerformanceEntry | null {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addXhrInstrumentationHandler(listener)`.\n */\nexport function handleXhrSpanListener(replay: ReplayContainer): (handlerData: HandlerDataXhr) => void {\n return (handlerData: HandlerDataXhr) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { Breadcrumb, Scope } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport { CONSOLE_ARG_MAX_SIZE } from '../constants';\nimport type { ReplayContainer } from '../types';\nimport type { ReplayFrame } from '../types/replayFrame';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\nlet _LAST_BREADCRUMB: null | Breadcrumb = null;\n\ntype BreadcrumbWithCategory = Required>;\n\nfunction isBreadcrumbWithCategory(breadcrumb: Breadcrumb): breadcrumb is BreadcrumbWithCategory {\n return !!breadcrumb.category;\n}\n\nexport const handleScopeListener: (replay: ReplayContainer) => (scope: Scope) => void =\n (replay: ReplayContainer) =>\n (scope: Scope): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nexport function handleScope(scope: Scope): Breadcrumb | null {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n !isBreadcrumbWithCategory(newBreadcrumb) ||\n ['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (newBreadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(newBreadcrumb);\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/** exported for tests only */\nexport function normalizeConsoleBreadcrumb(\n breadcrumb: Omit & BreadcrumbWithCategory,\n): ReplayFrame {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n // We use the pretty printed JSON string here as a base\n return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n","import type { BaseClient } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport { addEventProcessor, getClient } from '@sentry/core';\nimport type { Client, DynamicSamplingContext } from '@sentry/types';\nimport { addClickKeypressInstrumentationHandler, addHistoryInstrumentationHandler } from '@sentry/utils';\n\nimport { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';\nimport { handleBeforeSendEvent } from '../coreHandlers/handleBeforeSendEvent';\nimport { handleDomListener } from '../coreHandlers/handleDom';\nimport { handleGlobalEventListener } from '../coreHandlers/handleGlobalEvent';\nimport { handleHistorySpanListener } from '../coreHandlers/handleHistory';\nimport { handleNetworkBreadcrumbs } from '../coreHandlers/handleNetworkBreadcrumbs';\nimport { handleScopeListener } from '../coreHandlers/handleScope';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Add global listeners that cannot be removed.\n */\nexport function addGlobalListeners(replay: ReplayContainer): void {\n // Listeners from core SDK //\n const scope = getCurrentScope();\n const client = getClient();\n\n scope.addScopeListener(handleScopeListener(replay));\n addClickKeypressInstrumentationHandler(handleDomListener(replay));\n addHistoryInstrumentationHandler(handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n const eventProcessor = handleGlobalEventListener(replay, !hasHooks(client));\n if (client && client.addEventProcessor) {\n client.addEventProcessor(eventProcessor);\n } else {\n addEventProcessor(eventProcessor);\n }\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('beforeSendEvent', handleBeforeSendEvent(replay));\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc: DynamicSamplingContext) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n // Ensure to check that the session is still active - it could have expired in the meanwhile\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (isSessionActive) {\n dsc.replay_id = replayId;\n }\n }\n });\n\n client.on('startTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We may be missing the initial startTransaction due to timing issues,\n // so we capture it on finish again.\n client.on('finishTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We want to flush replay\n client.on('beforeSendFeedback', (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options && options.includeReplay && replay.isEnabled() && replayId) {\n // This should never reject\n if (feedbackEvent.contexts && feedbackEvent.contexts.feedback) {\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n }\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client: Client | undefined): client is BaseClient {\n return !!(client && client.on);\n}\n","import type { HandlerDataHistory } from '@sentry/types';\n\nimport type { HistoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from '../util/createPerformanceSpans';\n\nfunction handleHistory(handlerData: HandlerDataHistory): ReplayPerformanceEntry {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addHistoryInstrumentationHandler(listener)`.\n */\nexport function handleHistorySpanListener(replay: ReplayContainer): (handlerData: HandlerDataHistory) => void {\n return (handlerData: HandlerDataHistory) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n","import type { Event, EventHint } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isFeedbackEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';\nimport { isRrwebError } from '../util/isRrwebError';\nimport { handleAfterSendEvent } from './handleAfterSendEvent';\nimport { addFeedbackBreadcrumb } from './util/addFeedbackBreadcrumb';\nimport { shouldSampleForBufferEvent } from './util/shouldSampleForBufferEvent';\n\n/**\n * Returns a listener to be added to `addEventProcessor(listener)`.\n */\nexport function handleGlobalEventListener(\n replay: ReplayContainer,\n includeAfterSendEventHandling = false,\n): (event: Event, hint: EventHint) => Event | null {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return Object.assign(\n (event: Event, hint: EventHint) => {\n // Do nothing if replay has been disabled\n if (!replay.isEnabled()) {\n return event;\n }\n\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors, transactions, and feedbacks, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) {\n return event;\n }\n\n // Ensure we do not add replay_id if the session is expired\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (!isSessionActive) {\n return event;\n }\n\n if (isFeedbackEvent(event)) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.flush();\n event.contexts.feedback.replay_id = replay.getSessionId();\n // Add a replay breadcrumb for this piece of feedback\n addFeedbackBreadcrumb(replay, event);\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n DEBUG_BUILD && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n },\n { id: 'Replay' },\n );\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { FeedbackEvent } from '@sentry/types';\n\nimport type { ReplayBreadcrumbFrameEvent, ReplayContainer } from '../../types';\n\n/**\n * Add a feedback breadcrumb event to replay.\n */\nexport function addFeedbackBreadcrumb(replay: ReplayContainer, event: FeedbackEvent): void {\n replay.triggerUserActivity();\n replay.addUpdate(() => {\n if (!event.timestamp) {\n // Ignore events that don't have timestamps (this shouldn't happen, more of a typing issue)\n // Return true here so that we don't flush\n return true;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: event.timestamp * 1000,\n data: {\n tag: 'breadcrumb',\n payload: {\n timestamp: event.timestamp,\n type: 'default',\n category: 'sentry.feedback',\n data: {\n feedbackId: event.event_id,\n },\n },\n },\n } as ReplayBreadcrumbFrameEvent);\n\n return false;\n });\n}\n","import type { Event, EventHint } from '@sentry/types';\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nexport function isRrwebError(event: Event, hint: EventHint): boolean {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-expect-error this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n return false;\n}\n","import type { Event } from '@sentry/types';\n\nimport { UNABLE_TO_SEND_REPLAY } from '../../constants';\nimport type { ReplayContainer } from '../../types';\nimport { isSampled } from '../../util/isSampled';\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `hanldleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nexport function shouldSampleForBufferEvent(replay: ReplayContainer, event: Event): boolean {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n EventProcessor,\n FeedbackEvent,\n Integration,\n IntegrationClass,\n MetricBucketItem,\n MetricsAggregator,\n Outcome,\n ParameterizedString,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n StartSpanOptions,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n SentryError,\n SyncPromise,\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isParameterizedString,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport { getClient } from './exports';\nimport { getIsolationScope } from './hub';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport { createMetricEnvelope } from './metrics/envelope';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /**\n * A reference to a metrics aggregator\n *\n * @experimental Note this is alpha API. It may experience breaking changes in the future.\n */\n public metricsAggregator?: MetricsAggregator;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n protected _eventProcessors: EventProcessor[];\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(\n this._captureEvent(event, hint, capturedSpanScope || scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n if (this.metricsAggregator) {\n this.metricsAggregator.flush();\n }\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n if (this.metricsAggregator) {\n this.metricsAggregator.close();\n }\n return result;\n });\n }\n\n /** Get all installed event processors. */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * This is an internal function to setup all integrations that should run on the client.\n * @deprecated Use `client.init()` instead.\n */\n public setupIntegrations(forceInitialize?: boolean): void {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._setupIntegrations();\n }\n }\n\n /** @inheritdoc */\n public init(): void {\n if (this._isEnabled()) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this.getIntegrationByName(integrationId);\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n public getIntegrationByName(integrationName: string): T | undefined {\n return this._integrations[integrationName] as T | undefined;\n }\n\n /**\n * Returns the client's instance of the given integration class, it any.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, eventOrCount?: Event | number): void {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /**\n * @inheritDoc\n */\n public captureAggregateMetrics(metricBucketItems: Array): void {\n DEBUG_BUILD && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);\n const metricsEnvelope = createMetricEnvelope(\n metricBucketItems,\n this._dsn,\n this._options._metadata,\n this._options.tunnel,\n );\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(metricsEnvelope);\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n public on(hook: 'startTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'startPageLoadSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'startPageLoadSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: 'startNavigationSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n protected _setupIntegrations(): void {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n\n // TODO v8: We don't need this flag anymore\n this._integrationsInitialized = true;\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope = getIsolationScope(),\n ): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n const propagationContext = {\n ...isolationScope.getPropagationContext(),\n ...(scope ? scope.getPropagationContext() : undefined),\n };\n\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n DEBUG_BUILD && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/**\n * Add an event processor to the current client.\n * This event processor will run for all events processed by this client.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n const client = getClient();\n\n if (!client || !client.addEventProcessor) {\n return;\n }\n\n client.addEventProcessor(callback);\n}\n","import type { ErrorEvent, Event } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { isErrorEvent } from '../util/eventUtils';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\ntype BeforeSendEventCallback = (event: Event) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleBeforeSendEvent(replay: ReplayContainer): BeforeSendEventCallback {\n return (event: Event) => {\n if (!replay.isEnabled() || !isErrorEvent(event)) {\n return;\n }\n\n handleHydrationError(replay, event);\n };\n}\n\nfunction handleHydrationError(replay: ReplayContainer, event: ErrorEvent): void {\n const exceptionValue = event.exception && event.exception.values && event.exception.values[0].value;\n if (typeof exceptionValue !== 'string') {\n return;\n }\n\n if (\n // Only matches errors in production builds of react-dom\n // Example https://reactjs.org/docs/error-decoder.html?invariant=423\n exceptionValue.match(/reactjs\\.org\\/docs\\/error-decoder\\.html\\?invariant=(418|419|422|423|425)/) ||\n // Development builds of react-dom\n // Error 1: Hydration failed because the initial UI does not match what was rendered on the server.\n // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match.\n exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)\n ) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.hydrate-error',\n });\n addBreadcrumbEvent(replay, breadcrumb);\n }\n}\n","import { WINDOW } from '../constants';\nimport type { AddEventResult, MemoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from './createPerformanceSpans';\n\ntype ReplayMemoryEntry = ReplayPerformanceEntry & { data: { memory: MemoryInfo } };\n\ninterface MemoryInfo {\n jsHeapSizeLimit: number;\n totalJSHeapSize: number;\n usedJSHeapSize: number;\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nexport async function addMemoryEntry(replay: ReplayContainer): Promise> {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry: MemoryInfo): ReplayMemoryEntry {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { logger } from '@sentry/utils';\n\nimport { updateClickDetectorForRecordingEvent } from '../coreHandlers/handleClick';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { saveSession } from '../session/saveSession';\nimport type { RecordingEvent, ReplayContainer, ReplayOptionFrameEvent } from '../types';\nimport { addEventSync } from './addEvent';\nimport { logInfo } from './log';\n\ntype RecordingEmitCallback = (event: RecordingEvent, isCheckout?: boolean) => void;\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nexport function getHandleRecordingEmit(replay: ReplayContainer): RecordingEmitCallback {\n let hadFirstEvent = false;\n\n return (event: RecordingEvent, _isCheckout?: boolean) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n if (replay.clickDetector) {\n updateClickDetectorForRecordingEvent(replay.clickDetector, event);\n }\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // If the event is not added (e.g. due to being paused, disabled, or out of the max replay duration),\n // Skip all further steps\n if (!addEventSync(replay, event, isCheckout)) {\n // Return true to skip scheduling a debounced flush\n return true;\n }\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time.\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n addSettingsEvent(replay, isCheckout);\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n logInfo(\n `[Replay] Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`,\n replay.getOptions()._experiments.traceInternals,\n );\n\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n if (replay.recordingMode === 'session') {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void replay.flush();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nexport function createOptionsEvent(replay: ReplayContainer): ReplayOptionFrameEvent {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n shouldRecordCanvas: replay.isRecordingCanvas(),\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay: ReplayContainer, isCheckout?: boolean): void {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return;\n }\n\n addEventSync(replay, createOptionsEvent(replay), false);\n}\n","import type { DsnComponents, ReplayEnvelope, ReplayEvent, ReplayRecordingData } from '@sentry/types';\nimport { createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader } from '@sentry/utils';\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nexport function createReplayEnvelope(\n replayEvent: ReplayEvent,\n recordingData: ReplayRecordingData,\n dsn: DsnComponents,\n tunnel?: string,\n): ReplayEnvelope {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\n/**\n * Prepare the recording data ready to be sent.\n */\nexport function prepareRecordingData({\n recordingData,\n headers,\n}: {\n recordingData: ReplayRecordingData;\n headers: Record;\n}): ReplayRecordingData {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n","import type { IntegrationIndex, Scope } from '@sentry/core';\nimport { getIsolationScope } from '@sentry/core';\nimport { prepareEvent } from '@sentry/core';\nimport type { Client, EventHint, ReplayEvent } from '@sentry/types';\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nexport async function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}: {\n client: Client & { _integrations?: IntegrationIndex };\n scope: Scope;\n replayId: string;\n event: ReplayEvent;\n}): Promise {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n\n const eventHint: EventHint = { event_id, integrations };\n\n if (client.emit) {\n client.emit('preprocessEvent', event, eventHint);\n }\n\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n eventHint,\n scope,\n client,\n getIsolationScope(),\n )) as ReplayEvent | null;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n","import { getClient, getCurrentScope } from '@sentry/core';\nimport type { ReplayEvent, TransportMakeRequestResponse } from '@sentry/types';\nimport type { RateLimits } from '@sentry/utils';\nimport { isRateLimited, updateRateLimits } from '@sentry/utils';\n\nimport { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { createReplayEnvelope } from './createReplayEnvelope';\nimport { logInfo } from './log';\nimport { prepareRecordingData } from './prepareRecordingData';\nimport { prepareReplayEvent } from './prepareReplayEvent';\n\n/**\n * Send replay attachment using `fetch()`\n */\nexport async function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}: SendReplayData): Promise {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const client = getClient();\n const scope = getCurrentScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent: ReplayEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n logInfo('An event processor returned `null`, will not send event.');\n return;\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete replayEvent.sdkProcessingMetadata;\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response: void | TransportMakeRequestResponse;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n const rateLimits = updateRateLimits({}, response);\n if (isRateLimited(rateLimits, 'replay')) {\n throw new RateLimitError(rateLimits);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nexport class TransportStatusCodeError extends Error {\n public constructor(statusCode: number) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * This error indicates that we hit a rate limit API error.\n */\nexport class RateLimitError extends Error {\n public rateLimits: RateLimits;\n\n public constructor(rateLimits: RateLimits) {\n super('Rate limit hit');\n this.rateLimits = rateLimits;\n }\n}\n","import { captureException, setContext } from '@sentry/core';\n\nimport { RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SendReplayData } from '../types';\nimport { RateLimitError, TransportStatusCodeError, sendReplayRequest } from './sendReplayRequest';\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nexport async function sendReplay(\n replayData: SendReplayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n): Promise {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (DEBUG_BUILD && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n","export const THROTTLED = '__THROTTLED';\nexport const SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle any>(\n fn: T,\n maxCount: number,\n durationSeconds: number,\n): (...rest: Parameters) => ReturnType | typeof THROTTLED | typeof SKIPPED {\n const counter = new Map();\n\n const _cleanup = (now: number): void => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = (): number => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest: Parameters): ReturnType | typeof THROTTLED | typeof SKIPPED => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n","/* eslint-disable max-lines */ // TODO: We might want to split this file up\nimport { EventType, record } from '@sentry-internal/rrweb';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n captureException,\n getClient,\n getCurrentScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { ReplayRecordingMode, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport {\n BUFFER_CHECKOUT_TIME,\n SESSION_IDLE_EXPIRE_DURATION,\n SESSION_IDLE_PAUSE_DURATION,\n SLOW_CLICK_SCROLL_TIMEOUT,\n SLOW_CLICK_THRESHOLD,\n WINDOW,\n} from './constants';\nimport { ClickDetector } from './coreHandlers/handleClick';\nimport { handleKeyboardEvent } from './coreHandlers/handleKeyboardEvent';\nimport { setupPerformanceObserver } from './coreHandlers/performanceObserver';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventBuffer } from './eventBuffer';\nimport { clearSession } from './session/clearSession';\nimport { loadOrCreateSession } from './session/loadOrCreateSession';\nimport { saveSession } from './session/saveSession';\nimport { shouldRefreshSession } from './session/shouldRefreshSession';\n\nimport type {\n AddEventResult,\n AddUpdateCallback,\n AllPerformanceEntry,\n AllPerformanceEntryData,\n EventBuffer,\n InternalEventContext,\n PopEventContext,\n RecordingEvent,\n RecordingOptions,\n ReplayBreadcrumbFrame,\n ReplayCanvasIntegrationOptions,\n ReplayContainer as ReplayContainerInterface,\n ReplayPerformanceEntry,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n Session,\n SlowClickConfig,\n Timeouts,\n} from './types';\nimport { ReplayEventTypeCustom } from './types';\nimport { addEvent, addEventSync } from './util/addEvent';\nimport { addGlobalListeners } from './util/addGlobalListeners';\nimport { addMemoryEntry } from './util/addMemoryEntry';\nimport { createBreadcrumb } from './util/createBreadcrumb';\nimport { createPerformanceEntries } from './util/createPerformanceEntries';\nimport { createPerformanceSpans } from './util/createPerformanceSpans';\nimport { debounce } from './util/debounce';\nimport { getHandleRecordingEmit } from './util/handleRecordingEmit';\nimport { isExpired } from './util/isExpired';\nimport { isSessionExpired } from './util/isSessionExpired';\nimport { logInfo, logInfoNextTick } from './util/log';\nimport { sendReplay } from './util/sendReplay';\nimport type { SKIPPED } from './util/throttle';\nimport { THROTTLED, throttle } from './util/throttle';\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nexport class ReplayContainer implements ReplayContainerInterface {\n public eventBuffer: EventBuffer | null;\n\n public performanceEntries: AllPerformanceEntry[];\n\n public replayPerformanceEntries: ReplayPerformanceEntry[];\n\n public session: Session | undefined;\n\n public clickDetector: ClickDetector | undefined;\n\n /**\n * Recording can happen in one of three modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n public recordingMode: ReplayRecordingMode;\n\n /**\n * The current or last active transcation.\n * This is only available when performance is enabled.\n */\n public lastTransaction?: Transaction;\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n public readonly timeouts: Timeouts;\n\n private _throttledAddEvent: (\n event: RecordingEvent,\n isCheckout?: boolean,\n ) => typeof THROTTLED | typeof SKIPPED | Promise;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n private readonly _options: ReplayPluginOptions;\n\n private _performanceCleanupCallback?: () => void;\n\n private _debouncedFlush: ReturnType;\n private _flushLock: Promise | undefined;\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n private _lastActivity: number;\n\n /**\n * Is the integration currently active?\n */\n private _isEnabled: boolean;\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n private _isPaused: boolean;\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n private _hasInitializedCoreListeners: boolean;\n\n /**\n * Function to stop recording\n */\n private _stopRecording: ReturnType | undefined;\n\n private _context: InternalEventContext;\n\n /**\n * Internal use for canvas recording options\n */\n private _canvas: ReplayCanvasIntegrationOptions | undefined;\n\n public constructor({\n options,\n recordingOptions,\n }: {\n options: ReplayPluginOptions;\n recordingOptions: RecordingOptions;\n }) {\n this.eventBuffer = null;\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n this.recordingMode = 'session';\n this.timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n } as const;\n this._lastActivity = Date.now();\n this._isEnabled = false;\n this._isPaused = false;\n this._hasInitializedCoreListeners = false;\n this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event: RecordingEvent, isCheckout?: boolean) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig: SlowClickConfig | undefined = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n }\n\n /** Get the event context. */\n public getContext(): InternalEventContext {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n public isEnabled(): boolean {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n public isPaused(): boolean {\n return this._isPaused;\n }\n\n /**\n * Determine if canvas recording is enabled\n */\n public isRecordingCanvas(): boolean {\n return Boolean(this._canvas);\n }\n\n /** Get the replay integration options. */\n public getOptions(): ReplayPluginOptions {\n return this._options;\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n public initializeSampling(previousSessionId?: string): void {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n if (errorSampleRate <= 0 && sessionSampleRate <= 0) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n this._initializeSessionForSampling(previousSessionId);\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n this._handleException(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled === false) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n // If segmentId > 0, it means we've previously already captured this session\n // In this case, we still want to continue in `session` recording mode\n this.recordingMode = this.session.sampled === 'buffer' && this.session.segmentId === 0 ? 'buffer' : 'session';\n\n logInfoNextTick(\n `[Replay] Starting replay in ${this.recordingMode} mode`,\n this._options._experiments.traceInternals,\n );\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (this._isEnabled && this.recordingMode === 'session') {\n throw new Error('Replay recording is already in progress');\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n throw new Error('Replay buffering is in progress, call `flush()` to save the replay');\n }\n\n logInfoNextTick('[Replay] Starting replay in session mode', this._options._experiments.traceInternals);\n\n // Required as user activity is initially set in\n // constructor, so if `start()` is called after\n // session idle expiration, a replay will not be\n // created due to an idle timeout.\n this._updateUserActivity();\n\n const session = loadOrCreateSession(\n {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n },\n );\n\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n public startBuffering(): void {\n if (this._isEnabled) {\n throw new Error('Replay recording is already in progress');\n }\n\n logInfoNextTick('[Replay] Starting replay in buffer mode', this._options._experiments.traceInternals);\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: 0,\n allowBuffering: true,\n },\n );\n\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n public startRecording(): void {\n try {\n const canvasOptions = this._canvas;\n\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n ...(canvasOptions\n ? {\n recordCanvas: canvasOptions.recordCanvas,\n getCanvasManager: canvasOptions.getCanvasManager,\n sampling: canvasOptions.sampling,\n dataURLOptions: canvasOptions.dataURLOptions,\n }\n : {}),\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n public stopRecording(): boolean {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public async stop({ forceFlush = false, reason }: { forceFlush?: boolean; reason?: string } = {}): Promise {\n if (!this._isEnabled) {\n return;\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n\n try {\n logInfo(\n `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`,\n this._options._experiments.traceInternals,\n );\n\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (forceFlush) {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n public pause(): void {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n logInfo('[Replay] Pausing replay', this._options._experiments.traceInternals);\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n public resume(): void {\n if (!this._isPaused || !this._checkSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n logInfo('[Replay] Resuming replay', this._options._experiments.traceInternals);\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public async sendBufferedReplayOrFlush({ continueRecording = true }: SendBufferedReplayOptions = {}): Promise {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n logInfo('[Replay] Converting buffer to session', this._options._experiments.traceInternals);\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // To avoid race conditions where this is called multiple times, we check here again that we are still buffering\n if ((this.recordingMode as ReplayRecordingMode) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n public addUpdate(cb: AddUpdateCallback): void {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n public triggerUserActivity(): void {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._checkSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n public updateUserActivity(): void {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n public conditionalFlush(): Promise {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Flush using debounce flush\n */\n public flush(): Promise {\n return this._debouncedFlush() as Promise;\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n public flushImmediate(): Promise {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() as Promise;\n }\n\n /**\n * Cancels queued up flushes.\n */\n public cancelFlush(): void {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current sesion (=replay) ID */\n public getSessionId(): string | undefined {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n public checkAndHandleExpiredSession(): boolean | void {\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._checkSession()) {\n // Check session handles the refreshing itself\n return false;\n }\n\n return true;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n public setInitialState(): void {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n public throttledAddEvent(\n event: RecordingEvent,\n isCheckout?: boolean,\n ): typeof THROTTLED | typeof SKIPPED | Promise {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n // Return `false` if the event _was_ added, as that means we schedule a flush\n return !addEventSync(this, {\n type: ReplayEventTypeCustom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n public getCurrentRoute(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const lastTransaction = this.lastTransaction || getCurrentScope().getTransaction();\n\n const attributes = (lastTransaction && spanToJSON(lastTransaction).data) || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n if (!lastTransaction || !source || !['route', 'custom'].includes(source)) {\n return undefined;\n }\n\n return spanToJSON(lastTransaction).description;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n private _initializeRecording(): void {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n workerUrl: this._options.workerUrl,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n this._isPaused = false;\n\n this.startRecording();\n }\n\n /** A wrapper to conditionally capture exceptions. */\n private _handleException(error: unknown): void {\n DEBUG_BUILD && logger.error('[Replay]', error);\n\n if (DEBUG_BUILD && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n */\n private _initializeSessionForSampling(previousSessionId?: string): void {\n // Whenever there is _any_ error sample rate, we always allow buffering\n // Because we decide on sampling when an error occurs, we need to buffer at all times if sampling for errors\n const allowBuffering = this._options.errorSampleRate > 0;\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n previousSessionId,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering,\n },\n );\n\n this.session = session;\n }\n\n /**\n * Checks and potentially refreshes the current session.\n * Returns false if session is not recorded.\n */\n private _checkSession(): boolean {\n // If there is no session yet, we do not want to refresh anything\n // This should generally not happen, but to be safe....\n if (!this.session) {\n return false;\n }\n\n const currentSession = this.session;\n\n if (\n shouldRefreshSession(currentSession, {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n })\n ) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._refreshSession(currentSession);\n return false;\n }\n\n return true;\n }\n\n /**\n * Refresh a session with a new one.\n * This stops the current session (without forcing a flush, as that would never work since we are expired),\n * and then does a new sampling based on the refreshed session.\n */\n private async _refreshSession(session: Session): Promise {\n if (!this._isEnabled) {\n return;\n }\n await this.stop({ reason: 'refresh session' });\n this.initializeSampling(session.id);\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n private _addListeners(): void {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n this._performanceCleanupCallback = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n private _removeListeners(): void {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceCleanupCallback) {\n this._performanceCleanupCallback();\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n private _handleVisibilityChange: () => void = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n private _handleWindowBlur: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n /**\n * Handle when page is focused\n */\n private _handleWindowFocus: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n private _handleKeyboardEvent: (event: KeyboardEvent) => void = (event: KeyboardEvent) => {\n handleKeyboardEvent(this, event);\n };\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n private _doChangeToBackgroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n });\n\n if (expired) {\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n private _doChangeToForegroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n logInfo('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n private _updateUserActivity(_lastActivity: number = Date.now()): void {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n private _updateSessionActivity(_lastActivity: number = Date.now()): void {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n private _createCustomBreadcrumb(breadcrumb: ReplayBreadcrumbFrame): void {\n this.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEntries`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n private _addPerformanceEntries(): Promise> {\n const performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n return Promise.all(createPerformanceSpans(this, performanceEntries));\n }\n\n /**\n * Clear _context\n */\n private _clearContext(): void {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n private _updateInitialTimestampFromEventBuffer(): void {\n const { session, eventBuffer } = this;\n if (!session || !eventBuffer) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n private _popEventContext(): PopEventContext {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n private async _runFlush(): Promise {\n const replayId = this.getSessionId();\n\n if (!this.session || !this.eventBuffer || !replayId) {\n DEBUG_BUILD && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n // if this changed in the meanwhile, e.g. because the session was refreshed or similar, we abort here\n if (replayId !== this.getSessionId()) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n const timestamp = Date.now();\n\n // Check total duration again, to avoid sending outdated stuff\n // We leave 30s wiggle room to accomodate late flushing etc.\n // This _could_ happen when the browser is suspended during flushing, in which case we just want to stop\n if (timestamp - this._context.initialTimestamp > this._options.maxReplayDuration + 30_000) {\n throw new Error('Session is too long, not sending replay');\n }\n\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp,\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'sendReplay' });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n private _flush = async ({\n force = false,\n }: {\n /**\n * If true, flush while ignoring the `_isEnabled` state of\n * Replay integration. (By default, flush is noop if integration\n * is stopped).\n */\n force?: boolean;\n } = {}): Promise => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n // should never happen, as we would have bailed out before\n return;\n }\n\n const start = this.session.started;\n const now = Date.now();\n const duration = now - start;\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // If session is too short, or too long (allow some wiggle room over maxReplayDuration), do not send it\n // This _should_ not happen, but it may happen if flush is triggered due to a page activity change or similar\n const tooShort = duration < this._options.minReplayDuration;\n const tooLong = duration > this._options.maxReplayDuration + 5_000;\n if (tooShort || tooLong) {\n logInfo(\n `[Replay] Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\n this._options._experiments.traceInternals,\n );\n\n if (tooShort) {\n this._debouncedFlush();\n }\n return;\n }\n\n const eventBuffer = this.eventBuffer;\n if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {\n logInfo('[Replay] Flushing initial segment without checkout.', this._options._experiments.traceInternals);\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = undefined;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n DEBUG_BUILD && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };\n\n /** Save the session, if it is sticky */\n private _maybeSaveSession(): void {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n private _onMutationHandler = (mutations: unknown[]): boolean => {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'mutationLimit', forceFlush: this.recordingMode === 'session' });\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };\n}\n","type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => unknown;\ntype DebounceOptions = { maxWait?: number };\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nexport function debounce(func: CallbackFunction, wait: number, options?: DebounceOptions): DebouncedCallback {\n let callbackReturnValue: unknown;\n\n let timerId: ReturnType | undefined;\n let maxTimerId: ReturnType | undefined;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc(): unknown {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers(): void {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush(): unknown {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced(): unknown {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../../src/constants';\nimport type { ReplayContainer } from '../../src/types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nexport function clearSession(replay: ReplayContainer): void {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession(): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/**\n * The id of the profile that this span occured in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id';\n","import { getWorkerURL } from '@sentry-internal/replay-worker';\n\nimport type { EventBuffer } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferProxy } from './EventBufferProxy';\n\ninterface CreateEventBufferParams {\n useCompression: boolean;\n workerUrl?: string;\n}\n\n// Treeshakable guard to remove the code of the included compression worker\ndeclare const __SENTRY_EXCLUDE_REPLAY_WORKER__: boolean;\n\n/**\n * Create an event buffer for replays.\n */\nexport function createEventBuffer({\n useCompression,\n workerUrl: customWorkerUrl,\n}: CreateEventBufferParams): EventBuffer {\n if (\n useCompression &&\n // eslint-disable-next-line no-restricted-globals\n window.Worker\n ) {\n const worker = _loadWorker(customWorkerUrl);\n\n if (worker) {\n return worker;\n }\n }\n\n logInfo('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl?: string): EventBufferProxy | void {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n logInfo(`[Replay] Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n logInfo('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n}\n\nfunction _getWorkerUrl(): string {\n if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === 'undefined' || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {\n return getWorkerURL();\n }\n\n return '';\n}\n","import r from\"./worker\";function e(){const e=new Blob([r]);return URL.createObjectURL(e)}export{e as getWorkerURL};\n","export default `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==r||r<0)&&(r=0),(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=[\"unexpected EOF\",\"invalid block type\",\"invalid length/literal\",\"invalid distance\",\"stream finished\",\"no stream handler\",,\"no callback\",\"invalid UTF-8 data\",\"extra field too long\",\"date not in range 1980-2099\",\"filename too long\",\"stream finishing\",\"invalid zip data\"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},A=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},_=function(r,e){for(var i=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=x(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},x=function(t,n,r){return-1==t.s?Math.max(x(t.l,n,r+1),x(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,C)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B255){A(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;A(r,m,Q[et]),m+=R[et],et>3&&(A(r,m,rt>>5&8191),m+=i[et])}else A(r,m,N[rt]),m+=P[rt]}return A(r,m,N[256]),m+P[256]},U=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=U[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=C(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=A[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if(\"function\"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,a=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),s=a.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(a,n),O(a,s-8,r.d()),O(a,s-4,e),a}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),G=\"undefined\"!=typeof TextEncoder&&new TextEncoder,H=\"undefined\"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(r){for(var e=new t(n.length),i=0;i>1)),o=0,f=function(t){s[o++]=t};for(i=0;is.length){var h=new t(o+8+(a-i<<1));h.set(s),s=h}var l=n.charCodeAt(i);l<128||r?f(l):l<2048?(f(192|l>>6),f(128|63&l)):l>55295&&l<57344?(f(240|(l=65536+(1047552&l)|1023&n.charCodeAt(++i))>>18),f(128|l>>12&63),f(128|l>>6&63),f(128|63&l)):(f(224|l>>12),f(128|l>>6&63),f(128|63&l))}return b(s,0,o)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const n=this._hasEvents?\",\":\"\";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push(\"]\",!0);const t=function(t){let n=0;for(let r=0,e=t.length;r{this._deflatedData.push(t)},this.stream=new J(((t,n)=>{this.deflate.push(t,n)})),this.stream.push(\"[\")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener(\"message\",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&\"function\"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n","import type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { getBaseDomBreadcrumb } from './handleDom';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\n/** Handle keyboard events & create breadcrumbs. */\nexport function handleKeyboardEvent(replay: ReplayContainer, event: KeyboardEvent): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nexport function getKeyboardBreadcrumb(event: KeyboardEvent): Breadcrumb | null {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target as HTMLElement) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target as Node, message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target: HTMLElement): boolean {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n","import { consoleSandbox } from '@sentry/utils';\n\nimport type { DeprecatedPrivacyOptions, ReplayIntegrationPrivacyOptions } from '../types';\n\ntype GetPrivacyOptions = Required> &\n Omit;\ninterface GetPrivacyReturn {\n maskTextSelector: string;\n unmaskTextSelector: string;\n blockSelector: string;\n unblockSelector: string;\n ignoreSelector: string;\n\n blockClass?: RegExp;\n maskTextClass?: RegExp;\n}\n\nfunction getOption(\n selectors: string[],\n defaultSelectors: string[],\n deprecatedClassOption?: string | RegExp,\n deprecatedSelectorOption?: string,\n): string {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n });\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nexport function getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}: GetPrivacyOptions): GetPrivacyReturn {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options: GetPrivacyReturn = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n","import { getClient } from '@sentry/core';\nimport type { BrowserClientReplayOptions, Integration, IntegrationFn } from '@sentry/types';\nimport { consoleSandbox, dropUndefinedKeys, isBrowser } from '@sentry/utils';\n\nimport {\n DEFAULT_FLUSH_MAX_DELAY,\n DEFAULT_FLUSH_MIN_DELAY,\n MAX_REPLAY_DURATION,\n MIN_REPLAY_DURATION,\n MIN_REPLAY_DURATION_LIMIT,\n} from './constants';\nimport { ReplayContainer } from './replay';\nimport type {\n RecordingOptions,\n ReplayCanvasIntegrationOptions,\n ReplayConfiguration,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n} from './types';\nimport { getPrivacyOptions } from './util/getPrivacyOptions';\nimport { maskAttribute } from './util/maskAttribute';\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\ntype InitialReplayPluginOptions = Omit &\n Partial>;\n\nexport const replayIntegration = ((options?: ReplayConfiguration) => {\n // eslint-disable-next-line deprecation/deprecation\n return new Replay(options);\n}) satisfies IntegrationFn;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n * @deprecated Use `replayIntegration()` instead.\n */\nexport class Replay implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Replay';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n private readonly _initialOptions: InitialReplayPluginOptions;\n\n private _replay?: ReplayContainer;\n\n public constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n minReplayDuration = MIN_REPLAY_DURATION,\n maxReplayDuration = MAX_REPLAY_DURATION,\n stickySession = true,\n useCompression = true,\n workerUrl,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10_000,\n\n slowClickTimeout = 7_000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n maskAttributes = ['title', 'placeholder'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n }: ReplayConfiguration = {}) {\n // eslint-disable-next-line deprecation/deprecation\n this.name = Replay.id;\n\n const privacyOptions = getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n });\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n maskAttributeFn: (key: string, value: string, el: HTMLElement): string =>\n maskAttribute({\n maskAttributes,\n maskAllText,\n privacyOptions,\n key,\n value,\n el,\n }),\n\n ...privacyOptions,\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n errorHandler: (err: Error & { __rrweb__?: boolean }) => {\n try {\n err.__rrweb__ = true;\n } catch (error) {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n workerUrl,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n protected get _isInitialized(): boolean {\n return _initialized;\n }\n\n /** Update _isInitialized */\n protected set _isInitialized(value: boolean) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n public setupOnce(): void {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // Once upon a time, we tried to create a transaction in `setupOnce` and it would\n // potentially create a transaction before some native SDK integrations have run\n // and applied their own global event processor. An example is:\n // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n //\n // So we call `this._initialize()` in next event loop as a workaround to wait for other\n // global event processors to finish. This is no longer needed, but keeping it\n // here to avoid any future issues.\n setTimeout(() => this._initialize());\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n public startBuffering(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public stop(): Promise {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop({ forceFlush: this._replay.recordingMode === 'session' });\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public flush(options?: SendBufferedReplayOptions): Promise {\n if (!this._replay || !this._replay.isEnabled()) {\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n public getReplayId(): string | undefined {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n\n /**\n * Initializes replay.\n */\n protected _initialize(): void {\n if (!this._replay) {\n return;\n }\n\n // We have to run this in _initialize, because this runs in setTimeout\n // So when this runs all integrations have been added\n // Before this, we cannot access integrations on the client,\n // so we need to mutate the options here\n this._maybeLoadFromReplayCanvasIntegration();\n\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n private _setup(): void {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n\n /** Get canvas options from ReplayCanvas integration, if it is also added. */\n private _maybeLoadFromReplayCanvasIntegration(): void {\n // To save bundle size, we skip checking for stuff here\n // and instead just try-catch everything - as generally this should all be defined\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n try {\n const client = getClient()!;\n const canvasIntegration = client.getIntegrationByName!('ReplayCanvas') as Integration & {\n getOptions(): ReplayCanvasIntegrationOptions;\n };\n if (!canvasIntegration) {\n return;\n }\n\n this._replay!['_canvas'] = canvasIntegration.getOptions();\n } catch {\n // ignore errors here\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions: InitialReplayPluginOptions): ReplayPluginOptions {\n const client = getClient();\n const opt = client && (client.getOptions() as BrowserClientReplayOptions);\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n });\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n });\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers: string[]): string[] {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n","import type { getPrivacyOptions } from './getPrivacyOptions';\n\ninterface MaskAttributeParams {\n maskAttributes: string[];\n maskAllText: boolean;\n privacyOptions: ReturnType;\n key: string;\n value: string;\n el: HTMLElement;\n}\n\n/**\n * Masks an attribute if necessary, otherwise return attribute value as-is.\n */\nexport function maskAttribute({\n el,\n key,\n maskAttributes,\n maskAllText,\n privacyOptions,\n value,\n}: MaskAttributeParams): string {\n // We only mask attributes if `maskAllText` is true\n if (!maskAllText) {\n return value;\n }\n\n // unmaskTextSelector takes precendence\n if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) {\n return value;\n }\n\n if (\n maskAttributes.includes(key) ||\n // Need to mask `value` attribute for `` if it's a button-like\n // type\n (key === 'value' && el.tagName === 'INPUT' && ['submit', 'button'].includes(el.getAttribute('type') || ''))\n ) {\n return value.replace(/[\\S]/g, '*');\n }\n\n return value;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\nimport { serializeMetricBuckets } from './utils';\n\n/**\n * Create envelope from a metric aggregate.\n */\nexport function createMetricEnvelope(\n metricBucketItems: Array,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): StatsdEnvelope {\n const headers: StatsdEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const item = createMetricEnvelopeItem(metricBucketItems);\n return createEnvelope(headers, [item]);\n}\n\nfunction createMetricEnvelopeItem(metricBucketItems: MetricBucketItem[]): StatsdItem {\n const payload = serializeMetricBuckets(metricBucketItems);\n const metricHeaders: StatsdItem[0] = {\n type: 'statsd',\n length: payload.length,\n };\n return [metricHeaders, payload];\n}\n","import type { MeasurementUnit, MetricBucketItem, Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport type { MetricType } from './types';\n\n/**\n * Generate bucket key from metric properties.\n */\nexport function getBucketKey(\n metricType: MetricType,\n name: string,\n unit: MeasurementUnit,\n tags: Record,\n): string {\n const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));\n return `${metricType}${name}${unit}${stringifiedTags}`;\n}\n\n/* eslint-disable no-bitwise */\n/**\n * Simple hash function for strings.\n */\nexport function simpleHash(s: string): number {\n let rv = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n rv = (rv << 5) - rv + c;\n rv &= rv;\n }\n return rv >>> 0;\n}\n/* eslint-enable no-bitwise */\n\n/**\n * Serialize metrics buckets into a string based on statsd format.\n *\n * Example of format:\n * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677\n * Segments:\n * name: metric.name\n * unit: second\n * value: [1, 1.2]\n * type of metric: d (distribution)\n * tags: { a: value, b: anothervalue }\n * timestamp: 12345677\n */\nexport function serializeMetricBuckets(metricBucketItems: MetricBucketItem[]): string {\n let out = '';\n for (const item of metricBucketItems) {\n const tagEntries = Object.entries(item.tags);\n const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';\n out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\\n`;\n }\n return out;\n}\n\n/** Sanitizes units */\nexport function sanitizeUnit(unit: string): string {\n return unit.replace(/[^\\w]+/gi, '_');\n}\n\n/** Sanitizes metric keys */\nexport function sanitizeMetricKey(key: string): string {\n return key.replace(/[^\\w\\-.]+/gi, '_');\n}\n\nfunction sanitizeTagKey(key: string): string {\n return key.replace(/[^\\w\\-./]+/gi, '');\n}\n\nconst tagValueReplacements: [string, string][] = [\n ['\\n', '\\\\n'],\n ['\\r', '\\\\r'],\n ['\\t', '\\\\t'],\n ['\\\\', '\\\\\\\\'],\n ['|', '\\\\u{7c}'],\n [',', '\\\\u{2c}'],\n];\n\nfunction getCharOrReplacement(input: string): string {\n for (const [search, replacement] of tagValueReplacements) {\n if (input === search) {\n return replacement;\n }\n }\n\n return input;\n}\n\nfunction sanitizeTagValue(value: string): string {\n return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), '');\n}\n\n/**\n * Sanitizes tags.\n */\nexport function sanitizeTags(unsanitizedTags: Record): Record {\n const tags: Record = {};\n for (const key in unsanitizedTags) {\n if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {\n const sanitizedKey = sanitizeTagKey(key);\n tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));\n }\n }\n return tags;\n}\n","import type { Scope } from '@sentry/core';\nimport { applySdkMetadata } from '@sentry/core';\nimport { BaseClient } from '@sentry/core';\nimport type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n ParameterizedString,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(options, 'browser', ['browser'], sdkSource);\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n}\n","import type { Options } from '@sentry/types';\nimport { SDK_VERSION } from '../version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: Options, name: string, names = [name], source = 'npm'): void {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n SentryError,\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n DEBUG_BUILD && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/**\n * Deduplication filter.\n * @deprecated Use `dedupeIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Dedupe = convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n>;\n\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport { functionToStringIntegration, inboundFiltersIntegration } from '@sentry/core';\nimport {\n captureSession,\n getClient,\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n startSession,\n} from '@sentry/core';\nimport type { Integration, Options, UserFeedback } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n logger,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs';\nimport { dedupeIntegration } from './integrations/dedupe';\nimport { globalHandlersIntegration } from './integrations/globalhandlers';\nimport { httpContextIntegration } from './integrations/httpcontext';\nimport { linkedErrorsIntegration } from './integrations/linkederrors';\nimport { browserApiErrorsIntegration } from './integrations/trycatch';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\n/** @deprecated Use `getDefaultIntegrations(options)` instead. */\nexport const defaultIntegrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n];\n\n/** Get the default integrations for the browser SDK. */\nexport function getDefaultIntegrations(_options: Options): Integration[] {\n // We return a copy of the defaultIntegrations here to avoid mutating this\n return [\n // eslint-disable-next-line deprecation/deprecation\n ...defaultIntegrations,\n ];\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\ntype NewReportDialogOptions = ReportDialogOptions & { eventId: string }; // eslint-disable-line\n\ninterface ShowReportDialogFunction {\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\n (options: NewReportDialogOptions): void;\n\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n *\n * @deprecated Please always pass an `options` argument with `eventId`. The `hub` argument will not be used in the next version of the SDK.\n */\n // eslint-disable-next-line deprecation/deprecation\n (options?: ReportDialogOptions, hub?: Hub): void;\n}\n\nexport const showReportDialog: ShowReportDialogFunction = (\n // eslint-disable-next-line deprecation/deprecation\n options: ReportDialogOptions = {},\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub = getCurrentHub(),\n) => {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n // eslint-disable-next-line deprecation/deprecation\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event: MessageEvent): void => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n};\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import {\n captureException,\n captureMessage,\n convertIntegrationFnToClass,\n defineIntegration,\n getClient,\n withScope,\n} from '@sentry/core';\nimport type { CaptureContext, Client, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport {\n CONSOLE_LEVELS,\n GLOBAL_OBJ,\n addConsoleInstrumentationHandler,\n addExceptionMechanism,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\ninterface CaptureConsoleOptions {\n levels?: string[];\n}\n\nconst INTEGRATION_NAME = 'CaptureConsole';\n\nconst _captureConsoleIntegration = ((options: CaptureConsoleOptions = {}) => {\n const levels = options.levels || CONSOLE_LEVELS;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.includes(level)) {\n return;\n }\n\n consoleHandler(args, level);\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);\n\n/**\n * Send Console API calls as Sentry Events.\n * @deprecated Use `captureConsoleIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const CaptureConsole = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n captureConsoleIntegration,\n) as IntegrationClass void }> & {\n new (options?: { levels?: string[] }): Integration;\n};\n\nfunction consoleHandler(args: unknown[], level: string): void {\n const captureContext: CaptureContext = {\n level: severityLevelFromString(level),\n extra: {\n arguments: args,\n },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'console';\n\n addExceptionMechanism(event, {\n handled: false,\n type: 'console',\n });\n\n return event;\n });\n\n if (level === 'assert' && args[0] === false) {\n const message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n captureMessage(message, captureContext);\n return;\n }\n\n const error = args.find(arg => arg instanceof Error);\n if (level === 'error' && error) {\n captureException(error, captureContext);\n return;\n }\n\n const message = safeJoin(args, ' ');\n captureMessage(message, captureContext);\n });\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["isNodeEnv","__SENTRY_BROWSER_BUNDLE__","Object","prototype","toString","call","process","_typeof","require","_regeneratorRuntime","module","exports","__esModule","Op","hasOwn","hasOwnProperty","defineProperty","obj","key","desc","value","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","fn","arg","type","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","result","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","undefined","done","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","methodName","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","runtime","regeneratorRuntime","accidentalStrictMode","globalThis","Function","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","n","getter","d","a","definition","o","get","g","e","window","hmd","children","set","prop","r","flarum","core","compat","DEBUG_BUILD","__SENTRY_DEBUG__","isGlobalObj","Math","GLOBAL_OBJ","global","getGlobalObject","getGlobalSingleton","creator","gbl","__SENTRY__","CONSOLE_LEVELS","originalConsoleMethods","consoleSandbox","callback","console","wrappedFuncs","wrappedLevels","level","originalConsoleMethod","enabled","logger","enable","disable","isEnabled","_len","arguments","args","Array","_key","_GLOBAL_OBJ$console","apply","PREFIX","concat","_extends","assign","bind","target","source","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isParameterizedString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","base","_e","isVueViewModel","__isVue","_isVue","WINDOW","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","options","nextStr","currentElem","out","height","len","keyAttrs","isArray","maxStringLength","_htmlElementAsString","separator","parentNode","join","_oO","el","classes","attr","tagName","HTMLElement","dataset","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","keyAttrPair","split","allowedAttrs","truncate","str","max","safeJoin","input","delimiter","output","String","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","fill","replacementFactory","original","wrapped","markFunctionWrapped","addNonEnumerableProperty","o_O","log","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","message","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","isPojo","memoVal","returnValue","_i","_Object$keys","item","uuid4","crypto","msCrypto","getRandomByte","random","randomUUID","replace","getRandomValues","typedArray","Uint8Array","_","c","getFirstException","event","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","States","resolvedSyncPromise","SyncPromise","rejectedSyncPromise","reason","executor","__init","__init2","__init3","__init4","_state","PENDING","_handlers","_resolve","_reject","_proto","onfulfilled","onrejected","_this","_executeHandlers","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","_value","_this6","cachedHandlers","handler","getGlobalEventProcessors","addGlobalEventProcessor","notifyEventProcessors","processors","hint","index","processor","final","ONE_SECOND_IN_MS","dateTimestampInSeconds","Date","now","timestampInSeconds","performance","approxStartingTimeOrigin","timeOrigin","createUnixTimestampInSecondsFunc","DEFAULT_ENVIRONMENT","threshold","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","abnormal_mechanism","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","defaultFunctionName","getFunctionName","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","document","isSyntheticEvent","objName","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","toJSON","numAdded","visitable","visitKey","visitValue","TRACE_FLAG_SAMPLED","spanToTraceContext","span","_span$spanContext","spanContext","span_id","spanId","trace_id","traceId","_spanToJSON","spanToJSON","op","parent_span_id","tags","origin","getSpanJSON","spanIsSpanClass","debugIdStackParserCache","WeakMap","captureContextKeys","captureEvent","getCurrentHub","addBreadcrumb","breadcrumb","getClient","getRootSpan","transaction","getDynamicSamplingContextFromClient","client","scope","getOptions","public_key","getDsn","publicKey","user_segment","getUser","segment","dsc","emit","getDynamicSamplingContextFromSpan","getScope","txn","v7FrozenDsc","_frozenDynamicSamplingContext","_txn$metadata","metadata","maybeSampleRate","sampleRate","sample_rate","jsonSpan","description","sampled","traceFlags","spanIsSampled","applyScopeDataToEvent","fingerprint","breadcrumbs","sdkProcessingMetadata","extra","contexts","transactionName","cleanedExtra","cleanedTags","cleanedUser","cleanedContexts","applyDataToEvent","trace","rootSpan","dynamicSamplingContext","applySpanToEvent","maybeArray","applyFingerprintToEvent","mergedBreadcrumbs","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","eventProcessors","attachments","propagationContext","mergeAndOverwriteScopeData","mergeVal","globalScope","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","_propagationContext","generatePropagationContext","clone","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","_client","setClient","addScopeListener","addEventProcessor","setUser","_notifyScopeListeners","getRequestSession","setRequestSession","requestSession","setTags","setTag","_extends2","setExtras","extras","setExtra","_extends3","setFingerprint","setLevel","setTransactionName","setContext","setSpan","getSpan","getTransaction","setSession","getSession","update","captureContext","scopeToMerge","scopeData","getScopeData","scopeContext","clear","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","additionalEventProcessors","setSDKProcessingMetadata","newData","setPropagationContext","getPropagationContext","captureException","warn","syntheticException","originalException","captureMessage","substring","SDK_VERSION","API_VERSION","parseFloat","Hub","isolationScope","_version","assignedScope","assignedIsolationScope","_stack","bindClient","_isolationScope","isOlderThan","version","top","getStackTop","setupIntegrations","pushScope","getStack","popScope","withScope","maybePromiseResult","res","getIsolationScope","_lastEventId","lastEventId","_this$getStackTop","_ref","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","configureScope","_this$getStackTop2","run","oldHub","makeMain","getIntegration","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2","_ref2$environment","navigator","startingTime","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","sentry","getMainCarrier","extensions","hub","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","installedIntegrations","afterSetupIntegrations","integrations","_step","_iterator","_createForOfIteratorHelperLoose","afterAllSetup","setupIntegration","integrationIndex","indexOf","setupOnce","setup","on","preprocessEvent","processEvent","convertIntegrationFnToClass","originalFunctionToString","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","INTEGRATION_NAME","inboundFiltersIntegration","_hint","clientOptions","mergedOptions","internalOptions","allowUrls","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","_isSentryError","lastException","possibleMessages","_getPossibleEventMessages","_isIgnoredError","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","InboundFilters","frames","stacktrace","frame","filename","_getLastValidUrl","oO","SETUP_CLIENTS","functionToStringIntegration","originalFunction","FunctionToString","ignoreOnError","shouldIgnoreOnError","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","ex","setTimeout","rest","hintIsScopeOrFunction","hintIsScopeContext","parseEventHintOrCaptureContext","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","browserApiErrorsIntegration","_options","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","TryCatch","originalCallback","function","originalSend","xhr","wrapOptions","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","handlers","instrumented","addHandler","maybeInstrument","instrumentFn","triggerHandlers","typeHandlers","_oldOnErrorHandler","instrumentError","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","instrumentUnhandledRejection","onunhandledrejection","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","getNonErrorObjectExceptionValue","__serialized__","eventFromPlainObject","synthetic","__sentry_template_string__","__sentry_template_values__","logentry","params","maxLength","sort","includedKeys","serialized","extractExceptionKeysForMessage","captureType","getObjectClassName","globalHandlersIntegration","stackTraceLimit","_getOptions","groups","match","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","_installGlobalOnErrorHandler","globalHandlerLog","_getOptions2","e2","_getUnhandledRejectionError","_installGlobalOnUnhandledRejectionHandler","GlobalHandlers","ev","ev0","ev0s","ev0sf","colno","parseInt","lineno","location","href","getLocationHref","in_app","instrumentConsole","debounceTimerID","lastCapturedEventType","lastCapturedEventTargetId","DEBOUNCE_DURATION","instrumentDOM","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","globalListener","getEventTarget","eventType","isContentEditable","shouldSkipDOMEvent","_sentryId","isSimilarToLastCapturedEvent","clearTimeout","SENTRY_XHR_DATA_KEY","instrumentXHR","xhrproto","originalOpen","startTimestamp","toUpperCase","parseUrl","request_headers","__sentry_own_request__","onreadystatechangeHandler","xhrInfo","readyState","status_code","endTimestamp","onreadystatechange","readyStateArgs","_len3","setRequestHeaderArgs","_key3","header","sentryXhrData","_len4","_key4","body","isNativeFetch","instrumentFetch","EdgeRuntime","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","resource","lastHref","instrumentHistory","isChromePackagedApp","chromeVar","chrome","app","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","from","historyReplacementFunction","originalHistoryFunction","validSeverityLevels","query","fragment","host","path","protocol","search","hash","relative","MAX_ALLOWED_STRING_LENGTH","breadcrumbsIntegration","dom","category","_getConsoleBreadcrumbHandler","addClickKeypressInstrumentationHandler","componentName","serializeAttribute","element","_isEvent","getComponentName","_getDomBreadcrumbHandler","addXhrInstrumentationHandler","_getXhrBreadcrumbHandler","addFetchInstrumentationHandler","_getFetchBreadcrumbHandler","addHistoryInstrumentationHandler","parsedLoc","parsedFrom","parsedTo","_getHistoryBreadcrumbHandler","_getSentryBreadcrumbHandler","Breadcrumbs","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","parser","maxValueLimit","limit","exceptions","maxValueLength","aggregateExceptionsFromError","prevExceptions","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","childError","is_exception_group","exception_id","parentId","parent_id","linkedErrorsIntegration","LinkedErrors","httpContextIntegration","request","referrer","headers","Referer","HttpContext","asyncGeneratorStep","gen","_next","_throw","_asyncToGenerator","_defineProperties","props","descriptor","prim","toPrimitive","_createClass","Constructor","protoProps","staticProps","_setPrototypeOf","p","_inheritsLoose","subClass","superClass","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","Wrapper","_optionalChain","ops","lastAccessLHS","browserPerformanceTimeOrigin","makeLogger","getCurrentScope","prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","dist","_options$maxValueLeng","applyClientOptions","integrationNames","sdk","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","filenameDebugIdMap","reduce","acc","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","getFinalScope","clientEventProcessors","getEventProcessors","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","b","spans","normalizeEvent","removeTrailingSlash","dsnToString","dsn","withPassword","pass","port","projectId","DEFAULT_RETRY_AFTER","updateRateLimits","limits","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","trim","_limit$split","retryAfter","categories","namespaces","headerDelay","delay","_step2","_iterator2","all","headerDate","parse","parseRetryAfterHeader","isBrowser","getNavigationEntry","__WEB_VITALS_POLYFILL__","getEntriesByType","navigation","navigationEntry","entryType","startTime","getNavigationEntryFromPerformanceTiming","getActivationStart","navEntry","activationStart","onHidden","cb","once","onHiddenOrPageHide","visibilityState","removeEventListener","firstHiddenTime","observe","opts","PerformanceObserver","supportedEntryTypes","po","list","getEntries","buffered","reportedMetricIDs","onLCP","onReport","navigationType","report","visibilityWatcher","prerendering","Infinity","timeStamp","metric","rating","delta","entries","floor","handleEntries","lastEntry","reportAllChanges","prevValue","forceReport","bindReporter","stopListening","takeRecords","disconnect","capture","_previousLcp","instrumentLcp","getCleanupCallback","NodeType$1","REPLAY_SESSION_KEY","REPLAY_EVENT_NAME","UNABLE_TO_SEND_REPLAY","RETRY_BASE_INTERVAL","RETRY_MAX_COUNT","NETWORK_BODY_MAX_SIZE","CONSOLE_ARG_MAX_SIZE","REPLAY_MAX_EVENT_BUFFER_SIZE","MAX_REPLAY_DURATION","_optionalChain$5","_value2","isShadowRoot","_2","shadowRoot","isNativeShadowDom","stringifyStylesheet","s","rules","cssRules","cssText","stringifyRule","rule","importStringified","regex","isCSSImportRule","styleSheet","statement","layerName","supportsText","media","mediaText","escapeImportStatement","isCSSStyleRule","selectorText","NodeType","Mirror","idNodeMap","nodeMetaMap","getId","lhs","_3","getMeta","_4","_5","getNode","getIds","removeNodeFromMap","childNodes","childNode","hasNode","node","meta","oldNode","shouldMaskInput","maskInputOptions","maskInputValue","isMasked","maskInputFn","text","repeat","ORIGINAL_ATTRIBUTE_NAME","getInputType","hasAttribute","getInputValue","canvasService","canvasCtx","_id","tagNameRegex","RegExp","IGNORED_NODE","genId","URL_IN_CSS_REF","URL_PROTOCOL_MATCH","URL_WWW_MATCH","DATA_URI","absoluteToStylesheet","quote1","path1","quote2","path2","path3","filePath","maybeQuote","parts","part","SRCSET_NOT_SPACES","SRCSET_COMMAS_OR_SPACES","absoluteToDoc","attributeValue","isSVGElement","ownerSVGElement","getHref","transformAttribute","maskAttributeFn","pos","collectCharacters","regEx","chars","exec","descriptorsStr","inParens","getAbsoluteSrcsetString","ignoreAttribute","distanceToMatch","matchPredicate","distance","nodeType","ELEMENT_NODE","createMatchPredicate","selector","matches","eIndex","classList","elementClassMatchesRegex","needMaskingText","maskTextClass","maskTextSelector","unmaskTextClass","unmaskTextSelector","maskAllText","parentElement","autocomplete","maskDistance","unmaskDistance","lowerIfExists","maybeAttr","serializeNodeWithId","mirror","blockClass","blockSelector","unblockSelector","_options$skipChild","skipChild","_options$inlineStyles","inlineStylesheet","_options$maskInputOpt3","maskTextFn","slimDOMOptions","_options$dataURLOptio3","dataURLOptions","_options$inlineImages","inlineImages","_options$recordCanvas","recordCanvas","onSerialize","onIframeLoad","_options$iframeLoadTi","iframeLoadTimeout","onStylesheetLoad","_options$stylesheetLo","stylesheetLoadTimeout","_options$keepIframeSr","keepIframeSrcFn","_options$newlyAddedEl3","newlyAddedElement","_options$preserveWhit","preserveWhiteSpace","_serializedNode","_options$maskInputOpt","_options$dataURLOptio","_options$newlyAddedEl","rootId","docId","getRootId","DOCUMENT_NODE","compatMode","Document","DOCUMENT_TYPE_NODE","DocumentType","publicId","systemId","isCustomElement","_options$maskInputOpt2","_options$dataURLOptio2","_options$newlyAddedEl2","needBlock","contains","_isBlockedElement","HTMLFormElement","processedTagName","getValidTagName","attributes","stylesheet","styleSheets","find","rel","_cssText","sheet","innerText","textContent","checked","forceMask","selected","__context","canvas","ctx","getContext","x","width","y","getImageData","originalGetImageData","Uint32Array","min","buffer","pixel","is2DCanvasBlank","rr_dataURL","toDataURL","quality","canvasDataURL","blankCanvas","image","oldValue","crossOrigin","recordInlineImage","naturalWidth","naturalHeight","drawImage","currentSrc","removeAttribute","rr_mediaState","paused","rr_mediaCurrentTime","currentTime","scrollLeft","rr_scrollLeft","scrollTop","rr_scrollTop","_n$getBoundingClientR","getBoundingClientRect","rr_width","rr_height","src","contentDocument","rr_src","customElements","isSVG","isCustom","serializeElementNode","TEXT_NODE","parentTagName","isStyle","isScript","isTextarea","nextSibling","previousSibling","_6","_7","_8","textarea","Text","serializeTextNode","CDATA_SECTION_NODE","CDATA","COMMENT_NODE","Comment","serializeNode","sn","comment","script","as","endsWith","headFavicon","headMetaDescKeywords","headMetaSocial","headMetaRobots","headMetaHttpEquiv","headMetaAuthorship","headMetaVerification","slimDOMExcluded","serializedNode","recordChild","isShadowHost","headWhitespace","bypassOptions","_Array$from","serializedChildNode","isElement$1","_i2","_Array$from2","isShadow","iframeEl","win","fired","blankUrl","timer","onceIframeLoaded","iframeDoc","serializedIframeNode","link","styleSheetLoadTimeout","styleSheetLoaded","onceStylesheetLoaded","serializedLinkNode","_optionalChain$4","_value3","passive","DEPARTED_MIRROR_ACCESS_WARNING","_mirror","throttle$1","wait","timeout","previous","leading","remaining","getImplementation","clearTimeout$1","trailing","setTimeout$1","hookSetter","isRevoked","patch","replacement","defineProperties","__rrweb_original__","receiver","nowTimestamp","getWindowScroll","left","scrollingElement","pageXOffset","documentElement","pageYOffset","_9","_10","_11","_12","_13","_14","getWindowHeight","innerHeight","clientHeight","getWindowWidth","innerWidth","clientWidth","closestElementOfNode","isBlocked","checkAncestors","blockedPredicate","isUnblocked","blockDistance","unblockDistance","isIgnored","isAncestorRemoved","legacy_isTouchEvent","changedTouches","isSerializedIframe","nodeName","isSerializedStylesheet","hasShadowRoot","_18","getTime","StyleSheetMirror","styleIDMap","idStyleMap","_proto2","newId","getStyle","generateId","getShadowHost","shadowHost","_19","getRootNode","_20","_21","Node","DOCUMENT_FRAGMENT_NODE","inDom","ownerDocument","rootShadowHost","getRootShadowHost","shadowHostInDom","cachedImplementations","cached","impl","EventType","EventType2","IncrementalSource","IncrementalSource2","MouseInteractions","MouseInteractions2","PointerTypes","PointerTypes2","_optionalChain$3","_value4","_len5","_key5","isNodeInLinkedList","errorHandler","DoubleLinkedList","tail","_proto3","position","current","addNode","__ln","removeNode","moveKey","MutationBuffer","frozen","locked","texts","attributeMap","removes","mapRemoves","movedMap","addedSet","Set","movedSet","droppedSet","processMutations","mutations","processMutation","adds","addedIds","addList","getNextId","ns","nextId","pushAdd","currentN","iframeManager","addIframe","stylesheetManager","trackLinkElement","shadowDomManager","addShadowRoot","iframe","childSn","attachIframe","observeAttachShadow","attachLinkElement","shift","isParentRemoved","_step3","_iterator3","isAncestorInSet","candidate","tailNode","_node","unhandledNode","payload","attribute","style","diffAsStr","styleDiff","unchangedAsStr","_unchangedStyles","mutationCb","m","attributeName","isInputMasked","setAttribute","unattachedDoc","implementation","createHTMLDocument","old","_i3","_Array$from3","pname","newValue","getPropertyValue","newPriority","getPropertyPriority","_i4","_Array$from4","addedNodes","genAdds","removedNodes","nodeId","isSerialized","deepDelete","processedNodeManager","inOtherBuffer","targetId","childN","_proto4","freeze","canvasManager","unfreeze","isFrozen","lock","unlock","addsSet","_isParentRemoved","size","_isAncestorInSet","registerErrorHandler","unregisterErrorHandler","callbackWrapper","_optionalChain$2","_value6","_len6","_key6","mutationBuffers","composedPath","initMutationObserver","rootEl","mutationBuffer","mutationObserverCtor","MutationObserver","__rrMutationObserver","angularZoneSymbol","Zone","__symbol__","observer","onMutation","attributeOldValue","characterData","characterDataOldValue","childList","subtree","initScrollObserver","_ref7","scrollCb","sampling","defaultView","scrollLeftTop","scroll","INPUT_TAGS","lastInputValueMap","initInputObserver","_ref10","inputCb","ignoreClass","ignoreSelector","userTriggeredOnInput","eventHandler","userTriggered","isTrusted","isChecked","cbWithDedup","querySelectorAll","v","lastInputValue","currentWindow","h","propertyDescriptor","HTMLInputElement","hookProperties","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","getNestedCSSRulePositions","childRule","hasNestedCSSRule","parentRule","CSSGroupingRule","CSSMediaRule","CSSSupportsRule","CSSConditionRule","unshift","parentStyleSheet","recurse","getIdAndStyleId","styleMirror","styleId","ownerNode","initAdoptedStyleSheetObserver","_ref15","hostId","patchTarget","ShadowRoot","originalPropertyDescriptor","sheets","_this7","_15","_16","adoptStyleSheets","initObservers","_hooks","_ref9","viewportResizeCb","lastH","lastW","_step4","mutationObserver","mousemoveHandler","_ref4","mousemoveCb","mousemove","timeBaseline","callbackThreshold","mousemoveCallback","positions","wrappedCb","totalOffset","timeOffset","updatePosition","_ref5","clientX","clientY","DragEvent","Drag","MouseEvent","MouseMove","TouchMove","initMoveObserver","mouseInteractionHandler","_ref6","mouseInteractionCb","mouseInteraction","disableMap","currentPointerType","Number","eventKey","pointerType","thisEventKey","Mouse","Touch","Pen","MouseDown","MouseUp","Click","getHandler","PointerEvent","TouchStart","TouchEnd","initMouseInteractionObserver","scrollHandler","viewportResizeHandler","inputHandler","mediaInteractionHandler","_ref18","mediaInteractionCb","volume","muted","playbackRate","initMediaInteractionObserver","styleSheetObserver","_ref11","_ref12","styleSheetRuleCb","CSSStyleSheet","insertRule","thisArg","argumentsList","_getIdAndStyleId","replaceSync","deleteRule","_getIdAndStyleId2","_getIdAndStyleId3","_getIdAndStyleId4","supportedNestedCSSRuleTypes","canMonkeyPatchNestedCSSRule","unmodifiedFunctions","_ref13","typeKey","_getIdAndStyleId5","_getIdAndStyleId6","_ref14","initStyleSheetObserver","adoptedStyleSheetObserver","styleDeclarationObserver","_ref16","_ref17","styleDeclarationCb","ignoreCSSAttributes","setProperty","CSSStyleDeclaration","priority","_getIdAndStyleId7","_17","removeProperty","_getIdAndStyleId8","remove","initStyleDeclarationObserver","fontObserver","collectFonts","_ref19","fontCb","fontMap","originalFontFace","FontFace","family","descriptors","fontFace","fontSource","restoreHandler","fonts","initFontObserver","selectionObserver","param","selectionCb","collapsed","updateSelection","selection","getSelection","isCollapsed","ranges","count","rangeCount","range","getRangeAt","startContainer","startOffset","endContainer","endOffset","start","end","initSelectionObserver","customElementObserver","_ref20","customElementCb","initCustomElementObserver","pluginHandlers","_iterator4","plugins","plugin","CrossOriginIframeMirror","generateIdFn","iframeIdToRemoteIdMap","iframeRemoteIdToIdMap","_proto5","remoteId","idToRemoteMap","remoteToIdMap","idToRemoteIdMap","getIdToRemoteIdMap","remoteIdToIdMap","getRemoteIdToIdMap","_this8","getRemoteId","getRemoteIds","ids","_this9","_optionalChain$1","_value7","_len7","_key7","wrappedEmit","_takeFullSnapshot","IframeManagerNoop","crossOriginIframeMirror","crossOriginIframeRootIdMap","_proto6","addLoadListener","IframeManager","iframes","crossOriginIframeMap","recordCrossOriginIframes","crossOriginIframeStyleMirror","handleMessage","_proto7","loadListener","isAttachIframe","adoptedStyleSheets","crossOriginMessageEvent","transformedEvent","transformCrossOriginEvent","isCheckout","_this10","FullSnapshot","replaceIdOnNode","patchRootIdOnNode","IncrementalSnapshot","Mutation","Meta","Load","DomContentLoaded","Plugin","Custom","replaceIds","ViewportResize","MediaInteraction","MouseInteraction","Scroll","CanvasMutation","Input","StyleSheetRule","StyleDeclaration","replaceStyleIds","Font","Selection","AdoptedStyleSheet","styles","iframeMirror","_step5","_iterator5","_this11","child","_this12","ShadowDomManagerNoop","_proto8","ShadowDomManager","shadowDoms","restoreHandlers","_proto9","patchAttachShadow","_this13","iframeElement","manager","option","CanvasManagerNoop","_proto10","snapshot","StylesheetManager","trackedLinkElements","adoptedStyleSheetCb","_proto11","linkEl","trackStylesheetInLinkElement","_step6","adoptedStyleSheetData","styleIds","_iterator6","CSSRule","ProcessedNodeManager","nodeMap","loop","periodicallyClear","_proto12","_this14","onRequestAnimationFrame","thisBuffer","buffers","destroy","checkoutEveryNms","checkoutEveryNth","_options$blockClass","_options$blockSelecto","_options$unblockSelec","_options$ignoreClass","_options$ignoreSelect","_options$maskAllText","_options$maskTextClas","_options$unmaskTextCl","_options$maskTextSele","_options$unmaskTextSe","_options$inlineStyles2","maskAllInputs","_maskInputOptions","_slimDOMOptions","_options$maxCanvasSiz","maxCanvasSize","packFn","_options$sampling","_options$dataURLOptio4","mousemoveWait","_options$recordCanvas2","_options$recordCrossO","_options$recordAfter","recordAfter","_options$userTriggere","_options$collectFonts","_options$inlineImages2","_options$keepIframeSr2","_options$ignoreCSSAtt","getCanvasManager","inEmittingFrame","parent","passEmitsToParent","lastFullSnapshotEvent","color","date","month","number","tel","time","week","select","radio","checkbox","NodeList","DOMTokenList","polyfill","incrementalSnapshotCount","eventProcessor","_step7","_iterator7","buf","postMessage","exceedCount","exceedTime","takeFullSnapshot","_step8","wrappedMutationEmit","wrappedScrollEmit","wrappedCanvasMutationEmit","__RRWEB_EXCLUDE_IFRAME__","_iterator8","getMirror","nodeMirror","getCanvasManagerFn","_getCanvasManager","__RRWEB_EXCLUDE_SHADOW_DOM__","_ref3","_ref3$mirror","_ref3$blockClass","_ref3$blockSelector","_ref3$unblockSelector","_ref3$maskAllText","_ref3$maskTextClass","_ref3$unmaskTextClass","_ref3$maskTextSelecto","_ref3$unmaskTextSelec","_ref3$inlineStyleshee","_ref3$inlineImages","_ref3$recordCanvas","_ref3$maskAllInputs","_ref3$slimDOM","slimDOM","_ref3$keepIframeSrcFn","initialOffset","canvasMutationCb","CustomElement","ReplayEventTypeIncrementalSnapshot","timestampToMs","timestampToS","addBreadcrumbEvent","replay","triggerUserActivity","checkAndHandleExpiredSession","addUpdate","throttledAddEvent","tag","INTERACTIVE_SELECTOR","getClosestInteractive","closest","getClickTargetNode","getTargetNode","isEventWithTarget","ClickDetector","slowClickConfig","_addBreadcrumbEvent","_lastMutation","_lastScroll","_clicks","_timeout","_threshold","_scollTimeout","scrollTimeout","_replay","_ignoreSelector","_proto13","addListeners","_this15","cleanupWindowOpen","nowInSeconds","originalWindowOpen","_len8","_key8","_teardown","removeListeners","_checkClickTimeout","handleClick","SLOW_CLICK_TAGS","ignoreElement","isClickBreadcrumb","newClick","clickBreadcrumb","clickCount","click","_scheduleCheckClicks","registerMutation","registerScroll","registerClick","_handleMultiClick","_getClicks","_checkClicks","_this16","timedOutClicks","mutationAfter","scrollAfter","_i5","_timedOutClicks","_generateBreadcrumbs","hadScroll","hadMutation","isSlowClick","timeAfterClickMs","endReason","route","getCurrentRoute","_this17","createBreadcrumb","ATTRIBUTES_TO_RECORD","getAttributesToRecord","normalizedKey","getBaseDomBreadcrumb","isElement","ENTRY_TYPES","initiatorType","responseEnd","decodedBodySize","encodedBodySize","responseStatus","transferSize","getAbsoluteTime","paint","domComplete","domContentLoadedEventStart","domContentLoadedEventEnd","domInteractive","loadEventStart","loadEventEnd","redirectCount","createPerformanceEntry","setupPerformanceObserver","addPerformanceEntry","performanceEntries","onEntries","_ref21","stopOnCallback","clearCallbacks","durationThreshold","instrumentPerformanceObserver","addPerformanceInstrumentationHandler","previousValue","addMetricObserver","_ref22","replayPerformanceEntries","getLargestContentfulPaint","clearCallback","logInfo","shouldAddBreadcrumb","addLogBreadcrumb","logInfoNextTick","EventBufferSizeExceededError","_Error","EventBufferArray","events","_totalSize","hasCheckout","_proto14","addEvent","_addEvent2","_callee","eventSize","_context2","_x","_this18","eventsRet","getEarliestTimestamp","WorkerHandler","worker","_worker","_proto15","ensureReady","_this19","_ensureReadyPromise","_ref23","success","terminate","_this20","_getAndIncrementId","_ref24","EventBufferCompressionWorker","_earliestTimestamp","_proto16","_sendEventToWorker","_finishRequest","_finishRequest2","_callee2","_context3","EventBufferProxy","_fallback","_compression","_used","_ensureWorkerIsLoadedPromise","_ensureWorkerIsLoaded","_proto17","_finish","_callee3","_context4","ensureWorkerIsLoaded","_ensureWorkerIsLoaded2","_callee4","_context5","t0","_switchToCompressionWorker","_switchToCompressionWorker2","_callee5","_this$_fallback","addEventPromises","_iterator9","_step9","_context6","hasEvents","hasSessionStorage","sessionStorage","isSampled","lastActivity","segmentId","previousSessionId","saveSession","setItem","createSession","_ref26","_temp","sessionSampleRate","allowBuffering","_ref26$stickySession","stickySession","getSessionSampleType","isExpired","initialTime","expiry","targetTime","isSessionExpired","_ref28","maxReplayDuration","sessionIdleExpire","_ref28$targetTime","shouldRefreshSession","_ref29","loadOrCreateSession","_ref30","sessionOptions","traceInternals","existingSession","sessionStringFromStorage","getItem","sessionObj","fetchSession","addEventSync","shouldAddEvent","_addEvent","_x2","_x3","_x4","_addEvent3","_callee11","replayOptions","eventAfterPossibleCallback","_context12","eventBuffer","recordingMode","maybeApplyCallback","beforeAddRecordingEvent","recordDroppedEvent","isPaused","timestampInMs","timeouts","sessionIdlePause","initialTimestamp","_experiments","isCustomEvent","isTransactionEvent","isFeedbackEvent","handleAfterSendEvent","enforceStatusCode","transport","getTransport","send","__sentry__baseTransport__","isBaseTransportSend","sendResponse","replayContext","traceIds","handleTransactionEvent","errorIds","replayId","beforeErrorSampling","sendBufferedReplayOrFlush","handleErrorEvent","createPerformanceSpans","_ref31","addNetworkBreadcrumb","hubOrClient","isHub","tunnel","checkDsn","checkTunnel","isSentryRequestUrl","shouldFilterRequest","getBodySize","textEncoder","encode","URLSearchParams","FormData","formDataStr","_serializeFormData","Blob","ArrayBuffer","byteLength","parseContentLengthHeader","getBodyString","mergeWarning","warning","_meta","warnings","newMeta","existingWarnings","makeNetworkReplayBreadcrumb","buildSkippedNetworkRequestOrResponse","bodySize","buildNetworkRequestOrResponse","_normalizeNetworkBody","first","last","exceedsSizeLimit","isProbablyJson","truncatedBody","e3","normalizeNetworkBody","normalizedBody","getAllowedHeaders","allowedHeaders","filteredHeaders","formData","urlMatches","urls","fullUrl","baseURI","fixedUrl","URL","getFullUrl","_captureFetchBreadcrumbToReplay","_callee12","_context13","_prepareFetchData","_x8","_x9","_x10","_prepareFetchData2","_callee13","_hint$startTimestamp2","_hint$endTimestamp2","_breadcrumb$data2","_breadcrumb$data2$sta","requestBodySize","responseBodySize","captureDetails","_context14","request_body_size","response_body_size","networkDetailAllowUrls","networkDetailDenyUrls","_getRequestInfo","_getResponseInfo","_ref32","networkCaptureBodies","networkRequestHeaders","getHeadersFromOptions","_getBodyString","_getFetchRequestArgBody","bodyStr","_x11","_x12","_x13","_x14","_getResponseInfo2","_callee14","_ref33","networkResponseHeaders","_yield$_parseFetchRes","bodyText","_context15","getAllHeaders","_parseFetchResponseBody","getResponseData","_ref34","_x15","_parseFetchResponseBody2","_callee15","_context16","_tryCloneResponse","_tryGetResponseText","allHeaders","_x16","_getResponseText2","_getResponseText","txt","_callee16","_context17","_captureXhrBreadcrumbToReplay","_callee17","_context18","_prepareXhrData","_hint$startTimestamp","_hint$endTimestamp","_breadcrumb$data","_breadcrumb$data$stat","getAllResponseHeaders","_line$split","getResponseHeaders","_ref35","requestBody","requestWarning","_ref36","responseText","responseType","outerHTML","_parseXhrResponse","_getXhrResponseBody","responseBody","responseWarning","handleNetworkBreadcrumbs","TextEncoder","_replay$getOptions2","_isXhrBreadcrumb","_isXhrHint","reqSize","resSize","getResponseHeader","_getBodySize","enrichXhrBreadcrumb","_x17","_x18","_x19","captureXhrBreadcrumbToReplay","_isFetchBreadcrumb","_isFetchHint","enrichFetchBreadcrumb","_x5","_x6","_x7","captureFetchBreadcrumbToReplay","beforeAddNetworkBreadcrumb","handleFetch","handleFetchSpanListener","handleXhr","handleXhrSpanListener","_LAST_BREADCRUMB","addGlobalListeners","newBreadcrumb","isTruncated","normalizedArgs","normalizedArg","normalizeConsoleBreadcrumb","handleScope","handleScopeListener","_getDomTarget","isClick","getDomTarget","handleDom","clickDetector","altKey","metaKey","ctrlKey","shiftKey","handleDomListener","handleHistory","handleHistorySpanListener","includeAfterSendEventHandling","afterSendHandler","isReplayEvent","flush","feedback","replay_id","getSessionId","feedbackId","addFeedbackBreadcrumb","__rrweb__","isRrwebError","captureExceptions","isErrorEventSampled","errorSampleRate","shouldSampleForBufferEvent","handleGlobalEventListener","hasHooks","exceptionValue","handleHydrationError","handleBeforeSendEvent","lastTransaction","feedbackEvent","includeReplay","addMemoryEntry","_x20","_addMemoryEntry","_callee18","_context19","memoryEntry","memory","jsHeapSizeLimit","totalJSHeapSize","usedJSHeapSize","getHandleRecordingEmit","hadFirstEvent","_isCheckout","isIncrementalEvent","isIncrementalMouseInteraction","_event$data","updateClickDetectorForRecordingEvent","setInitialState","shouldRecordCanvas","isRecordingCanvas","useCompressionOption","useCompression","blockAllMedia","networkDetailHasUrls","networkRequestHasHeaders","networkResponseHasHeaders","createOptionsEvent","addSettingsEvent","earliestEvent","createReplayEnvelope","replayEvent","recordingData","sdkInfo","sent_at","createEventEnvelopeHeaders","metadataOrEvent","_metadataOrEvent$sdk","getSdkMetadataForEnvelopeHeader","items","prepareRecordingData","_ref37","payloadWithSequence","replayHeaders","sequence","prepareReplayEvent","_x21","_prepareReplayEvent","_callee19","_ref38","eventHint","preparedEvent","_ref48","_context20","_integrations","platform","getSdkMetadata","sendReplayRequest","_x22","_sendReplayRequest","_callee20","_ref39","segment_id","eventContext","preparedRecordingData","baseEvent","envelope","rateLimits","_context21","replay_start_timestamp","error_ids","trace_ids","replay_type","cause","TransportStatusCodeError","isRateLimited","dataCategory","disabledUntil","RateLimitError","_Error2","_Error3","_this21","sendReplay","_x23","_x24","_sendReplay","_callee22","replayData","retryConfig","_context23","interval","_retryCount","_callee21","_context22","THROTTLED","ReplayContainer","_ref40","_this22","recordingOptions","__init5","__init6","_lastActivity","_isEnabled","_isPaused","_hasInitializedCoreListeners","_context","initialUrl","_recordingOptions","_debouncedFlush","callbackReturnValue","timerId","maxTimerId","maxWait","invokeFunc","cancelTimers","debounced","cancel","debounce","_flush","flushMinDelay","flushMaxDelay","_throttledAddEvent","maxCount","durationSeconds","counter","isThrottled","_cleanup","wasThrottled","throttle","_this$getOptions","slowClickTimeout","slowClickIgnoreSelectors","_proto18","_canvas","initializeSampling","_this$_options","_initializeSessionForSampling","_initializeRecording","_handleException","_updateUserActivity","startBuffering","startRecording","canvasOptions","_stopRecording","_onMutationHandler","stopRecording","_stop","_callee6","_temp2","_ref41","_ref41$forceFlush","forceFlush","_context7","_removeListeners","force","removeItem","deleteSession","_x25","pause","resume","_checkSession","_sendBufferedReplayOrFlush","_callee7","_temp3","_ref42$continueRecord","continueRecording","activityTime","hasStoppedRecording","_context8","flushImmediate","_updateSessionActivity","_maybeSaveSession","_x26","cbResult","updateUserActivity","conditionalFlush","cancelFlush","urlPath","pathname","_clearContext","_this23","_ref25","customWorkerUrl","workerUrl","Worker","__SENTRY_EXCLUDE_REPLAY_WORKER__","createObjectURL","_loadWorker","createEventBuffer","_addListeners","_refreshSession","_refreshSession2","_callee8","_context9","_x27","_handleVisibilityChange","_handleWindowBlur","_handleWindowFocus","_handleKeyboardEvent","_performanceCleanupCallback","_this24","_doChangeToForegroundTasks","_doChangeToBackgroundTasks","_this25","_this26","_this27","isInputElement","hasModifierKey","isCharacterKey","getKeyboardBreadcrumb","handleKeyboardEvent","_createCustomBreadcrumb","_this28","_addPerformanceEntries","_updateInitialTimestampFromEventBuffer","_popEventContext","_runFlush","_runFlush2","_callee9","_context10","_this29","_ref43","_callee10","_temp4","_ref44$force","tooShort","tooLong","_context11","minReplayDuration","_flushLock","_x28","_this30","mutationLimit","overMutationLimit","mutationBreadcrumbLimit","getOption","selectors","defaultSelectors","deprecatedClassOption","deprecatedSelectorOption","deprecatedSelectors","allSelectors","MEDIA_SELECTORS","DEFAULT_NETWORK_HEADERS","_initialized","Replay$1","_temp5","_ref47","_ref47$flushMinDelay","_ref47$flushMaxDelay","_ref47$minReplayDurat","_ref47$maxReplayDurat","_ref47$stickySession","_ref47$useCompression","_ref47$_experiments","_ref47$maskAllText","_ref47$maskAllInputs","_ref47$blockAllMedia","_ref47$mutationBreadc","_ref47$mutationLimit","_ref47$slowClickTimeo","_ref47$slowClickIgnor","_ref47$networkDetailA","_ref47$networkDetailD","_ref47$networkCapture","_ref47$networkRequest","_ref47$networkRespons","_ref47$mask","mask","_ref47$maskAttributes","maskAttributes","_ref47$unmask","unmask","_ref47$block","block","_ref47$unblock","unblock","_ref47$ignore","ignore","maskFn","privacyOptions","_ref45","getPrivacyOptions","password","_ref46","maskAttribute","_initialOptions","_getMergedNetworkHeaders","_isInitialized","__initStatic","_proto19","_this31","_setup","_initialize","getReplayId","_maybeLoadFromReplayCanvasIntegration","finalOptions","initialOptions","opt","replaysSessionSampleRate","replaysOnErrorSampleRate","loadReplayOptionsFromClient","canvasIntegration","getIntegrationByName","DSN_REGEX","dsnFromComponents","components","makeDsn","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","component","isValidProtocol","validateDsn","createEnvelope","forEachEnvelopeItem","envelopeItem","encodeUTF8","serializeEnvelope","envHeaders","append","itemHeaders","stringifiedPayload","totalLength","merged","offset","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","statsd","envelopeItemTypeToDataCategory","SentryError","logLevel","ReferenceError","_assertThisInitialized","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","_metadata","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","encodeURIComponent","_encodedAuth","createMetricEnvelope","metricBucketItems","tagEntries","maybeTags","unit","metricType","serializeMetricBuckets","createMetricEnvelopeItem","ALREADY_SEEN_ERROR","BaseClient","_integrationsInitialized","_numProcessing","_outcomes","_dsn","_transport","transportOptions","_process","eventFromException","_captureEvent","eventMessage","promisedEvent","eventFromMessage","capturedSpanScope","sendSession","metricsAggregator","_isClientDoneProcessing","clientFinished","transportFlushed","close","forceInitialize","_setupIntegrations","getIntegrationById","integrationId","integrationName","addIntegration","isAlreadyInstalled","sendEvent","newItem","env","packages","enhanceEventWithSdkInfo","envelopeHeaders","createEventEnvelope","promise","_sendEnvelope","createSessionEnvelope","eventOrCount","sendClientReports","captureAggregateMetrics","metricsEnvelope","hook","_updateSessionFromEvent","crashed","errored","sessionNonTerminal","ticked","clearInterval","_prepareEvent","parentSpanId","_processEvent","finalEvent","sentryError","isTransaction","beforeSendLabel","capturedSpanIsolationScope","__sentry__","beforeSend","beforeSendTransaction","spanCountBefore","spanCountBeforeProcessing","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","spanCount","droppedSpanCount","transactionInfo","transaction_info","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","names","applySdkMetadata","SENTRY_SDK_SOURCE","_flushOutcomes","captureUserFeedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","discarded_events","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","task","$","taskProducer","drain","capturedSetTimeout","makePromiseBuffer","bufferSize","filteredEnvelopeItems","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","dedupeIntegration","previousEvent","currentEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","onClose","reportDialogClosedMessageHandler","injectionPoint","severityLevelFromString","CaptureConsole","levels","consoleHandler","Replay","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","tracesSampleRate","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file diff --git a/js/dist/forum.tracing.js b/js/dist/forum.tracing.js index 4fcfdff..582882c 100644 --- a/js/dist/forum.tracing.js +++ b/js/dist/forum.tracing.js @@ -1,2 +1,3 @@ -(()=>{var t={476:(t,e,n)=>{"use strict";function r(){return"undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&!!__SENTRY_BROWSER_BUNDLE__}function i(){return"npm"}n.d(e,{S:()=>i,n:()=>r})},538:(t,e,n)=>{"use strict";n.d(e,{KV:()=>i,l$:()=>a});var r=n(476);function i(){return!(0,r.n)()&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}function a(t,e){return t.require(e)}t=n.hmd(t)},910:(t,e,n)=>{"use strict";n.d(e,{Z1:()=>p,ph:()=>f,yW:()=>u});var r=n(538),i=n(899);t=n.hmd(t);var a=(0,i.Rf)(),o={nowSeconds:function(){return Date.now()/1e3}},s=(0,r.KV)()?function(){try{return(0,r.l$)(t,"perf_hooks").performance}catch(t){return}}():function(){var t=a.performance;if(t&&t.now)return{now:function(){return t.now()},timeOrigin:Date.now()-t.now()}}(),c=void 0===s?o:{nowSeconds:function(){return(s.timeOrigin+s.now())/1e3}},u=o.nowSeconds.bind(o),f=c.nowSeconds.bind(c),p=function(){var t=a.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i{"use strict";function r(t){return t&&t.Math==Math?t:void 0}n.d(e,{Rf:()=>a,YO:()=>o,n2:()=>i});var i="object"==typeof globalThis&&r(globalThis)||"object"==typeof window&&r(window)||"object"==typeof self&&r(self)||"object"==typeof n.g&&r(n.g)||function(){return this}()||{};function a(){return i}function o(t,e,n){var r=n||i,a=r.__SENTRY__=r.__SENTRY__||{};return a[t]||(a[t]=e())}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var a=e[r]={id:r,loaded:!1,exports:{}};return t[r](a,a.exports,n),a.loaded=!0,a.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.hmd=t=>((t=Object.create(t)).children||(t.children=[]),Object.defineProperty(t,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+t.id)}}),t),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=Object.prototype.toString;function a(t){switch(i.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return v(t,Error)}}function o(t,e){return i.call(t)==="[object "+e+"]"}function s(t){return o(t,"ErrorEvent")}function c(t){return o(t,"DOMError")}function u(t){return o(t,"String")}function f(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function p(t){return o(t,"Object")}function d(t){return"undefined"!=typeof Event&&v(t,Event)}function l(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function h(t){return"number"==typeof t&&t!=t}function v(t,e){try{return t instanceof e}catch(t){return!1}}function m(t,e){return void 0===e&&(e=0),"string"!=typeof t||0===e||t.length<=e?t:t.slice(0,e)+"..."}function _(t,e){if(!Array.isArray(t))return"";for(var n=[],r=0;r=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(t){return null}}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&o+3*i.length+n.length>=c);)i.push(n),o+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function R(t,e){var n,r,i,a,o,s=t,c=[];if(!s||!s.tagName)return"";c.push(s.tagName.toLowerCase());var f=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(f&&f.length)f.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&c.push("#"+s.id),(n=s.className)&&u(n))for(r=n.split(/\s+/),o=0;o"}}function N(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function M(t,e){void 0===e&&(e=40);var n=Object.keys(P(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return m(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:m(i,e)}return""}function U(t){return q(t,new Map)}function q(t,e){if(p(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,a=Object.keys(t);i=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function F(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n>t/4).toString(16)}))}function X(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function J(t){var e=t.message,n=t.event_id;if(e)return e;var r=X(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function V(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],a=i[0]=i[0]||{};a.value||(a.value=e||""),a.type||(a.type=n||"Error")}function G(t,e){var n=X(t);if(n){var r=n.mechanism;if(n.mechanism=E({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=E({},r&&r.data,e.data);n.mechanism.data=i}}}function K(t){if(t&&t.__sentry_captured__)return!0;try{j(t,"__sentry_captured__",!0)}catch(t){}return!1}var Z,Q=n(910),tt=["debug","info","warn","error","log","assert","trace"];Z={enable:function(){},disable:function(){}},tt.forEach((function(t){Z[t]=function(){}}));var et,nt="production";function rt(t){return new at((function(e){e(t)}))}function it(t){return new at((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(et||(et={}));var at=function(){var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this);try{t(this._resolve,this._reject)}catch(t){this._reject(t)}}return t.__init=function(){this._state=et.PENDING},t.__init2=function(){this._handlers=[]},t.then=function(t,n){var r=this;return new e((function(e,i){r._handlers.push([!1,function(n){if(t)try{e(t(n))}catch(t){i(t)}else e(n)},function(t){if(n)try{e(n(t))}catch(t){i(t)}else i(t)}]),r._executeHandlers()}))},t.catch=function(t){return this.then((function(t){return t}),t)},t.finally=function(t){var n=this;return new e((function(e,r){var i,a;return n.then((function(e){a=!1,i=e,t&&t()}),(function(e){a=!0,i=e,t&&t()})).then((function(){a?r(i):e(i)}))}))},t.__init3=function(){var t=this;this._resolve=function(e){t._setResult(et.RESOLVED,e)}},t.__init4=function(){var t=this;this._reject=function(e){t._setResult(et.REJECTED,e)}},t.__init5=function(){var t=this;this._setResult=function(e,n){t._state===et.PENDING&&(l(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},t.__init6=function(){var t=this;this._executeHandlers=function(){if(t._state!==et.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===et.RESOLVED&&e[1](t._value),t._state===et.REJECTED&&e[2](t._value),e[0]=!0)}))}}},e}();function ot(t,e){if(void 0===e&&(e={}),e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||(0,Q.ph)(),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:$()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=""+e.did),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{var n=t.timestamp-t.started;t.duration=n>=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}var st=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={}}t.clone=function(e){var n=new t;return e&&(n._breadcrumbs=[].concat(e._breadcrumbs),n._tags=E({},e._tags),n._extra=E({},e._extra),n._contexts=E({},e._contexts),n._user=e._user,n._level=e._level,n._span=e._span,n._session=e._session,n._transactionName=e._transactionName,n._fingerprint=e._fingerprint,n._eventProcessors=[].concat(e._eventProcessors),n._requestSession=e._requestSession,n._attachments=[].concat(e._attachments),n._sdkProcessingMetadata=E({},e._sdkProcessingMetadata)),n};var e=t.prototype;return e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{},this._session&&ot(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=E({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=E({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=E({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=E({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this.getSpan();return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;if("function"==typeof e){var n=e(this);return n instanceof t?n:this}return e instanceof t?(this._tags=E({},this._tags,e._tags),this._extra=E({},this._extra,e._extra),this._contexts=E({},this._contexts,e._contexts),e._user&&Object.keys(e._user).length&&(this._user=e._user),e._level&&(this._level=e._level),e._fingerprint&&(this._fingerprint=e._fingerprint),e._requestSession&&(this._requestSession=e._requestSession)):p(e)&&(this._tags=E({},this._tags,e.tags),this._extra=E({},this._extra,e.extra),this._contexts=E({},this._contexts,e.contexts),e.user&&(this._user=e.user),e.level&&(this._level=e.level),e.fingerprint&&(this._fingerprint=e.fingerprint),e.requestSession&&(this._requestSession=e.requestSession)),this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=E({timestamp:(0,Q.yW)()},t);return this._breadcrumbs=[].concat(this._breadcrumbs,[r]).slice(-n),this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this._attachments},e.clearAttachments=function(){return this._attachments=[],this},e.applyToEvent=function(t,e){if(void 0===e&&(e={}),this._extra&&Object.keys(this._extra).length&&(t.extra=E({},this._extra,t.extra)),this._tags&&Object.keys(this._tags).length&&(t.tags=E({},this._tags,t.tags)),this._user&&Object.keys(this._user).length&&(t.user=E({},this._user,t.user)),this._contexts&&Object.keys(this._contexts).length&&(t.contexts=E({},this._contexts,t.contexts)),this._level&&(t.level=this._level),this._transactionName&&(t.transaction=this._transactionName),this._span){t.contexts=E({trace:this._span.getTraceContext()},t.contexts);var n=this._span.transaction;if(n){t.sdkProcessingMetadata=E({dynamicSamplingContext:n.getDynamicSamplingContext()},t.sdkProcessingMetadata);var r=n.name;r&&(t.tags=E({transaction:r},t.tags))}}return this._applyFingerprint(t),t.breadcrumbs=[].concat(t.breadcrumbs||[],this._breadcrumbs),t.breadcrumbs=t.breadcrumbs.length>0?t.breadcrumbs:void 0,t.sdkProcessingMetadata=E({},t.sdkProcessingMetadata,this._sdkProcessingMetadata),this._notifyEventProcessors([].concat(ct(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=E({},this._sdkProcessingMetadata,t),this},e._notifyEventProcessors=function(t,e,n,r){var i=this;return void 0===r&&(r=0),new at((function(a,o){var s=t[r];if(null===e||"function"!=typeof s)a(e);else{var c=s(E({},e),n);l(c)?c.then((function(e){return i._notifyEventProcessors(t,e,n,r+1).then(a)})).then(null,o):i._notifyEventProcessors(t,c,n,r+1).then(a).then(null,o)}}))},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},e._applyFingerprint=function(t){var e;t.fingerprint=t.fingerprint?(e=t.fingerprint,Array.isArray(e)?e:[e]):[],this._fingerprint&&(t.fingerprint=t.fingerprint.concat(this._fingerprint)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint},t}();function ct(){return(0,w.YO)("globalEventProcessors",(function(){return[]}))}function ut(t){ct().push(t)}var ft=4,pt=function(){function t(t,e,n){void 0===e&&(e=new st),void 0===n&&(n=ft),this._version=n,this._stack=[{scope:e}],t&&this.bindClient(t)}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;i0}function bt(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return r;if(D(t))return t}catch(e){return t}var i=function(){var r,i=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var a=i.map((function(t){return bt(t,e)}));return t.apply(this,a)}catch(t){throw gt++,setTimeout((function(){gt--})),r=function(n){var r;n.addEventProcessor((function(t){return e.mechanism&&(V(t,void 0,void 0),G(t,e.mechanism)),t.extra=E({},t.extra,{arguments:i}),t})),r=t,ht().captureException(r,{captureContext:undefined})},ht().withScope(r),t}};try{for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(i[a]=t[a])}catch(t){}A(i,t),j(t,"__sentry_wrapped__",i);try{Object.getOwnPropertyDescriptor(i,"name").configurable&&Object.defineProperty(i,"name",{get:function(){return t.name}})}catch(t){}return i}var St=["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"],Tt=function(){e.__initStatic=function(){this.id="TryCatch"};var t=e.prototype;function e(t){e.prototype.__init.call(this),this._options=E({XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){this._options.setTimeout&&C(_t,"setTimeout",Et),this._options.setInterval&&C(_t,"setInterval",Et),this._options.requestAnimationFrame&&C(_t,"requestAnimationFrame",xt),this._options.XMLHttpRequest&&"XMLHttpRequest"in _t&&C(XMLHttpRequest.prototype,"send",wt);var t=this._options.eventTarget;t&&(Array.isArray(t)?t:St).forEach(kt)},e}();function Et(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n2?n[2]:void 0;if(i){var a=jt,o=String(i);jt=o,Ut("history",{from:a,to:o})}return t.apply(this,n)}}}();break;case"error":Wt=At.onerror,At.onerror=function(t,e,n,r,i){return Ut("error",{column:r,error:i,line:n,msg:t,url:e}),!(!Wt||Wt.__SENTRY_LOADER__)&&Wt.apply(this,arguments)},At.onerror.__SENTRY_INSTRUMENTED__=!0;break;case"unhandledrejection":$t=At.onunhandledrejection,At.onunhandledrejection=function(t){return Ut("unhandledrejection",t),!($t&&!$t.__SENTRY_LOADER__)||$t.apply(this,arguments)},At.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0;break;default:return}}function Mt(t,e){Pt[t]=Pt[t]||[],Pt[t].push(e),Nt(t)}function Ut(t,e){if(t&&Pt[t])for(var n,r=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Ct(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ct(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Pt[t]||[]);!(n=r()).done;){var i=n.value;try{i(e)}catch(t){}}}function qt(t,e){return!!t&&"object"==typeof t&&!!t[e]}function Ht(t){return"string"==typeof t?t:t?qt(t,"url")?t.url:t.toString?t.toString():"":""}var Bt,Ft,zt=1e3;function Yt(t,e){return void 0===e&&(e=!1),function(n){if(n&&Ft!==n&&!function(t){if("keypress"!==t.type)return!1;try{var e=t.target;if(!e||!e.tagName)return!0;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||e.isContentEditable)return!1}catch(t){}return!0}(n)){var r="keypress"===n.type?"input":n.type;(void 0===Bt||function(t,e){if(!t)return!0;if(t.type!==e.type)return!0;try{if(t.target!==e.target)return!0}catch(t){}return!1}(Ft,n))&&(t({event:n,name:r,global:e}),Ft=n),clearTimeout(Bt),Bt=At.setTimeout((function(){Bt=void 0}),zt)}}}var Wt=null,$t=null;function Xt(t,e,n){void 0===e&&(e=100),void 0===n&&(n=1/0);try{return Vt("",t,e,n)}catch(t){return{ERROR:"**non-serializable** ("+t+")"}}}function Jt(t,e,n){void 0===e&&(e=3),void 0===n&&(n=102400);var r,i=Xt(t,e);return r=i,function(t){return~-encodeURI(t).split(/%..|./).length}(JSON.stringify(r))>n?Jt(t,e-1,n):i}function Vt(t,e,r,i,a){var o,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===a&&(o="function"==typeof WeakSet,s=o?new WeakSet:[],a=[function(t){if(o)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){m[y]="[MaxProperties ~]";break}var b=g[y];m[y]=Vt(y,b,l-1,i,a),_++}return f(e),m}function Gt(t,e){var n=Zt(t,e),r={type:e&&e.name,value:te(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Kt(t,e){return{exception:{values:[Gt(t,e)]}}}function Zt(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(Qt.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var Qt=/Minified React error #\d+;/i;function te(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function ee(t,e,n,r,i){var u;if(s(e)&&e.error)return Kt(t,e.error);if(c(e)||o(e,"DOMException")){var f=e;if("stack"in e)u=Kt(t,e);else{var l=f.name||(c(f)?"DOMError":"DOMException"),h=f.message?l+": "+f.message:l;V(u=ne(t,h,n,r),h)}return"code"in f&&(u.tags=E({},u.tags,{"DOMException.code":""+f.code})),u}return a(e)?Kt(t,e):p(e)||d(e)?(u=function(t,e,n,r){var i=ht().getClient(),a=i&&i.getOptions().normalizeDepth,o={exception:{values:[{type:d(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:"Non-Error "+(r?"promise rejection":"exception")+" captured with keys: "+M(e)}]},extra:{__serialized__:Jt(e,a)}};if(n){var s=Zt(t,n);s.length&&(o.exception.values[0].stacktrace={frames:s})}return o}(t,e,n,i),G(u,{synthetic:!0}),u):(V(u=ne(t,e,n,r),""+e,void 0),G(u,{synthetic:!0}),u)}function ne(t,e,n,r){var i={message:e};if(r&&n){var a=Zt(t,n);a.length&&(i.exception={values:[{value:e,stacktrace:{frames:a}}]})}return i}var re=function(){e.__initStatic=function(){this.id="GlobalHandlers"};var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),this._options=E({onerror:!0,onunhandledrejection:!0},t)}return t.__init=function(){this.name=e.id},t.__init2=function(){this._installFunc={onerror:ie,onunhandledrejection:ae}},t.setupOnce=function(){Error.stackTraceLimit=50;var t=this._options;for(var e in t){var n=this._installFunc[e];n&&t[e]&&(n(),this._installFunc[e]=void 0)}},e}();function ie(){Mt("error",(function(t){var e=ce(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(re)){var a=t.msg,o=t.url,c=t.line,f=t.column,p=t.error;if(!(yt()||p&&p.__sentry_own_request__)){var d=void 0===p&&u(a)?function(t,e,n,r){var i=s(t)?t.message:t,a="Error",o=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return o&&(a=o[1],i=o[2]),oe({exception:{values:[{type:a,value:i}]}},e,n,r)}(a,o,c,f):oe(ee(r,p||a,void 0,i,!1),o,c,f);d.level="error",se(n,p,d,"onerror")}}}))}function ae(){Mt("unhandledrejection",(function(t){var e=ce(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(re)){var a=t;try{"reason"in t?a=t.reason:"detail"in t&&"reason"in t.detail&&(a=t.detail.reason)}catch(t){}if(yt()||a&&a.__sentry_own_request__)return!0;var o=f(a)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(a)}]}}:ee(r,a,void 0,i,!0);o.level="error",se(n,a,o,"onunhandledrejection")}}))}function oe(t,e,n,r){var i=t.exception=t.exception||{},a=i.values=i.values||[],o=a[0]=a[0]||{},s=o.stacktrace=o.stacktrace||{},c=s.frames=s.frames||[],f=isNaN(parseInt(r,10))?void 0:r,p=isNaN(parseInt(n,10))?void 0:n,d=u(e)&&e.length>0?e:function(){try{return k.document.location.href}catch(t){return""}}();return 0===c.length&&c.push({colno:f,filename:d,function:"?",in_app:!0,lineno:p}),t}function se(t,e,n,r){G(n,{handled:!1,type:r}),t.captureEvent(n,{originalException:e})}function ce(){var t=ht(),e=t.getClient(),n=e&&e.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1};return[t,n.stackParser,n.attachStacktrace]}re.__initStatic();var ue=["fatal","error","warning","log","info","debug"];function fe(t){return"warn"===t?"warning":ue.includes(t)?t:"log"}function pe(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var de="Breadcrumbs",le=function(){e.__initStatic=function(){this.id=de};var t=e.prototype;function e(t){e.prototype.__init.call(this),this.options=E({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){var t;this.options.console&&Mt("console",he),this.options.dom&&Mt("dom",(t=this.options.dom,function(e){var n,r="object"==typeof t?t.serializeAttribute:void 0,i="object"==typeof t&&"number"==typeof t.maxStringLength?t.maxStringLength:void 0;i&&i>1024&&(i=1024),"string"==typeof r&&(r=[r]);try{var a=e.event;n=function(t){return t&&!!t.target}(a)?I(a.target,{keyAttrs:r,maxStringLength:i}):I(a,{keyAttrs:r,maxStringLength:i})}catch(t){n=""}0!==n.length&&ht().addBreadcrumb({category:"ui."+e.name,message:n},{event:e.event,name:e.name,global:e.global})})),this.options.xhr&&Mt("xhr",ve),this.options.fetch&&Mt("fetch",me),this.options.history&&Mt("history",_e)},t.addSentryBreadcrumb=function(t){this.options.sentry&&ht().addBreadcrumb({category:"sentry."+("transaction"===t.type?"transaction":"event"),event_id:t.event_id,level:t.level,message:J(t)},{event:t})},e}();function he(t){for(var e=0;e=e)return i;var a=Gt(t,n[r]);return ye(t,e,n[r],r,[a].concat(i))}ge.__initStatic();var be=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="HttpContext"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(){ut((function(e){if(ht().getIntegration(t)){if(!_t.navigator&&!_t.location&&!_t.document)return e;var n=e.request&&e.request.url||_t.location&&_t.location.href,r=(_t.document||{}).referrer,i=(_t.navigator||{}).userAgent,a=E({},e.request&&e.request.headers,r&&{Referer:r},i&&{"User-Agent":i}),o=E({},e.request,n&&{url:n},{headers:a});return E({},e,{request:o})}return e}))},t}();function Se(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Te(t,e){return Te=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},Te(t,e)}function Ee(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Te(t,e)}be.__initStatic();var xe=function(){var t=e.prototype;function e(t){void 0===t&&(t=1e3),e.prototype.__init.call(this),this._maxlen=t}return t.__init=function(){this.spans=[]},t.add=function(t){this.spans.length>this._maxlen?t.spanRecorder=void 0:this.spans.push(t)},e}();function we(t){return we="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},we(t)}function ke(t,e){for(var n=0;n"),t.prototype.finish.call(this,e);var r=this._hub.getClient();if(r&&r.emit&&r.emit("finishTransaction",this),!0===this.sampled){var i=this.spanRecorder?this.spanRecorder.spans.filter((function(t){return t!==n&&t.endTimestamp})):[];this._trimEnd&&i.length>0&&(this.endTimestamp=i.reduce((function(t,e){return t.endTimestamp&&e.endTimestamp?t.endTimestamp>e.endTimestamp?t:e:t})).endTimestamp);var a=this.metadata,o=E({contexts:E({},this._contexts,{trace:this.getTraceContext()}),spans:i,start_timestamp:this.startTimestamp,tags:this.tags,timestamp:this.endTimestamp,transaction:this.name,type:"transaction",sdkProcessingMetadata:E({},a,{dynamicSamplingContext:this.getDynamicSamplingContext()})},a.source&&{transaction_info:{source:a.source}});return Object.keys(this._measurements).length>0&&(o.measurements=this._measurements),this._hub.captureEvent(o)}r&&r.recordDroppedEvent("sample_rate","transaction")}},r.toContext=function(){return U(E({},t.prototype.toContext.call(this),{name:this.name,trimEnd:this._trimEnd}))},r.updateWithContext=function(e){return t.prototype.updateWithContext.call(this,e),this.name=e.name||"",this._trimEnd=e.trimEnd,this},r.getDynamicSamplingContext=function(){if(this._frozenDynamicSamplingContext)return this._frozenDynamicSamplingContext;var t=this._hub||ht(),e=t&&t.getClient();if(!e)return{};var n=e.getOptions()||{},r=n.environment,i=n.release,a=(e.getDsn()||{}).publicKey,o=this.metadata.sampleRate,s=void 0!==o?o.toString():void 0,c=(t.getScope().getUser()||{}).segment,u=this.metadata.source,f=u&&"url"!==u?this.name:void 0,p=U({environment:r||nt,release:i,transaction:f,user_segment:c,public_key:a,trace_id:this.traceId,sample_rate:s});return e.emit&&e.emit("createDsc",p),p},r.setHub=function(t){this._hub=t},e=i,(n=[{key:"name",get:function(){return this._name},set:function(t){this.setName(t)}}])&&ke(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),i}(function(){var t=e.prototype;function e(t){if(e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this),e.prototype.__init7.call(this),!t)return this;t.traceId&&(this.traceId=t.traceId),t.spanId&&(this.spanId=t.spanId),t.parentSpanId&&(this.parentSpanId=t.parentSpanId),"sampled"in t&&(this.sampled=t.sampled),t.op&&(this.op=t.op),t.description&&(this.description=t.description),t.data&&(this.data=t.data),t.tags&&(this.tags=t.tags),t.status&&(this.status=t.status),t.startTimestamp&&(this.startTimestamp=t.startTimestamp),t.endTimestamp&&(this.endTimestamp=t.endTimestamp),t.instrumenter&&(this.instrumenter=t.instrumenter)}return t.__init2=function(){this.traceId=$()},t.__init3=function(){this.spanId=$().substring(16)},t.__init4=function(){this.startTimestamp=(0,Q.ph)()},t.__init5=function(){this.tags={}},t.__init6=function(){this.data={}},t.__init7=function(){this.instrumenter="sentry"},t.startChild=function(t){var n=new e(E({},t,{parentSpanId:this.spanId,sampled:this.sampled,traceId:this.traceId}));return n.spanRecorder=this.spanRecorder,n.spanRecorder&&n.spanRecorder.add(n),n.transaction=this.transaction,n},t.setTag=function(t,e){var n;return this.tags=E({},this.tags,((n={})[t]=e,n)),this},t.setData=function(t,e){var n;return this.data=E({},this.data,((n={})[t]=e,n)),this},t.setStatus=function(t){return this.status=t,this},t.setHttpStatus=function(t){this.setTag("http.status_code",String(t));var e=function(t){if(t<400&&t>=100)return"ok";if(t>=400&&t<500)switch(t){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(t>=500&&t<600)switch(t){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"}(t);return"unknown_error"!==e&&this.setStatus(e),this},t.isSuccess=function(){return"ok"===this.status},t.finish=function(t){this.endTimestamp="number"==typeof t?t:(0,Q.ph)()},t.toTraceparent=function(){var t="";return void 0!==this.sampled&&(t=this.sampled?"-1":"-0"),this.traceId+"-"+this.spanId+t},t.toContext=function(){return U({data:this.data,description:this.description,endTimestamp:this.endTimestamp,op:this.op,parentSpanId:this.parentSpanId,sampled:this.sampled,spanId:this.spanId,startTimestamp:this.startTimestamp,status:this.status,tags:this.tags,traceId:this.traceId})},t.updateWithContext=function(t){return this.data=t.data||{},this.description=t.description,this.endTimestamp=t.endTimestamp,this.op=t.op,this.parentSpanId=t.parentSpanId,this.sampled=t.sampled,this.spanId=t.spanId||this.spanId,this.startTimestamp=t.startTimestamp||this.startTimestamp,this.status=t.status,this.tags=t.tags||{},this.traceId=t.traceId||this.traceId,this},t.getTraceContext=function(){return U({data:Object.keys(this.data).length>0?this.data:void 0,description:this.description,op:this.op,parent_span_id:this.parentSpanId,span_id:this.spanId,status:this.status,tags:Object.keys(this.tags).length>0?this.tags:void 0,trace_id:this.traceId})},t.toJSON=function(){return U({data:Object.keys(this.data).length>0?this.data:void 0,description:this.description,op:this.op,parent_span_id:this.parentSpanId,span_id:this.spanId,start_timestamp:this.startTimestamp,status:this.status,tags:Object.keys(this.tags).length>0?this.tags:void 0,timestamp:this.endTimestamp,trace_id:this.traceId})},e}());function Ie(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._beforeFinishCallbacks);!(r=i()).done;)(0,r.value)(this,e);this.spanRecorder.spans=this.spanRecorder.spans.filter((function(t){return t.spanId===n.spanId||(t.endTimestamp||(t.endTimestamp=e,t.setStatus("cancelled")),t.startTimestamp=3?(this.setStatus("deadline_exceeded"),this._finishReason=Ce[0],this.finish()):this._pingHeartbeat()}},e._pingHeartbeat=function(){var t=this;setTimeout((function(){t._beat()}),this._heartbeatInterval)},n}(Oe);function De(t){var e=ht().getClient(),n=t||e&&e.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}function Pe(t){return(t||ht()).getScope().getTransaction()}var Le=!1;function Ne(){var t=Pe();t&&t.setStatus("internal_error")}function Me(){var t=this.getScope().getSpan();return t?{"sentry-trace":t.toTraceparent()}:{}}function Ue(t,e,n){return De(e)?void 0!==t.sampled?(t.setMetadata({sampleRate:Number(t.sampled)}),t):("function"==typeof e.tracesSampler?(i=e.tracesSampler(n),t.setMetadata({sampleRate:Number(i)})):void 0!==n.parentSampled?i=n.parentSampled:void 0!==e.tracesSampleRate?(i=e.tracesSampleRate,t.setMetadata({sampleRate:Number(i)})):(i=1,t.setMetadata({sampleRate:i})),h(r=i)||"number"!=typeof r&&"boolean"!=typeof r||r<0||r>1||!i?(t.sampled=!1,t):(t.sampled=Math.random()We?t:o}),"")}(Object.entries(t).reduce((function(t,e){var n=e[0],r=e[1];return r&&(t[""+ze+n]=r),t}),{}))}function Xe(t){return t.split(",").map((function(t){return t.split("=").map((function(t){return decodeURIComponent(t.trim())}))})).reduce((function(t,e){var n=e[0],r=e[1];return t[n]=r,t}),{})}var Je=w.n2,Ve=function(t,e,n){var r,i;return function(a){e.value>=0&&(a||n)&&((i=e.value-(r||0))||void 0===r)&&(r=e.value,e.delta=i,t(e))}},Ge=function(){return Je.__WEB_VITALS_POLYFILL__?Je.performance&&(performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]||function(){var t=Je.performance.timing,e=Je.performance.navigation.type,n={entryType:"navigation",startTime:0,type:2==e?"back_forward":1===e?"reload":"navigate"};for(var r in t)"navigationStart"!==r&&"toJSON"!==r&&(n[r]=Math.max(t[r]-t.navigationStart,0));return n}()):Je.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},Ke=function(){var t=Ge();return t&&t.activationStart||0},Ze=function(t,e){var n=Ge(),r="navigate";return n&&(r=Je.document.prerendering||Ke()>0?"prerender":n.type.replace(/_/g,"-")),{name:t,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-"+Date.now()+"-"+(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},Qe=function(t,e,n){try{if(PerformanceObserver.supportedEntryTypes.includes(t)){var r=new PerformanceObserver((function(t){e(t.getEntries())}));return r.observe(Object.assign({type:t,buffered:!0},n||{})),r}}catch(t){}},tn=function(t,e){var n=function n(r){"pagehide"!==r.type&&"hidden"!==Je.document.visibilityState||(t(r),e&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},en=-1,nn=function(){return en<0&&(en="hidden"!==Je.document.visibilityState||Je.document.prerendering?1/0:0,tn((function(t){var e=t.timeStamp;en=e}),!0)),{get firstHiddenTime(){return en}}},rn={},an=["startTimestamp"];function on(t){return"number"==typeof t&&isFinite(t)}function sn(t,e){var n=e.startTimestamp,r=function(t,e){if(null==t)return{};var n,r,i={},a=Object.keys(t);for(r=0;r=0||(i[n]=t[n]);return i}(e,an);return n&&t.startTimestamp>n&&(t.startTimestamp=n),t.startChild(E({startTimestamp:n},r))}function cn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return un(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?un(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function un(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nn.value&&(n.value=r,n.entries=i,e&&e())}}))},o=Qe("layout-shift",a);if(o){e=Ve(t,n);var s=function(){a(o.takeRecords()),e(!0)};return tn(s),s}}((function(t){var e=t.entries.pop();e&&(vn.cls={value:t.value,unit:""},ln=e)})),u=function(t){var e,n=nn(),r=Ze("LCP"),i=function(t){var i=t[t.length-1];if(i){var a=Math.max(i.startTime-Ke(),0);a0&&a.setData("http.response_content_length",s)}else t.error&&a.setStatus("internal_error");a.finish(),delete r[i]}}else{var c=ht().getScope(),u=c&&c.getSpan(),f=u&&u.transaction;if(u&&f){var p=t.fetchData,d=p.method,l=p.url,h=u.startChild({data:{url:l,type:"fetch","http.method":d},description:d+" "+l,op:"http.client"});t.fetchData.__span=h.spanId,r[h.spanId]=h;var m=t.args[0];t.args[1]=t.args[1]||{};var _=t.args[1];n(t.fetchData.url)&&(_.headers=function(t,e,n,r){var i=$e(e),a=n.toTraceparent(),o="undefined"!=typeof Request&&v(t,Request)?t.headers:r.headers;if(o){if("undefined"!=typeof Headers&&v(o,Headers)){var s=new Headers(o);return s.append("sentry-trace",a),i&&s.append(Fe,i),s}if(Array.isArray(o)){var c=[].concat(o,[["sentry-trace",a]]);return i&&c.push([Fe,i]),c}var u="baggage"in o?o.baggage:void 0,f=[];return Array.isArray(u)?f.push.apply(f,u):u&&f.push(u),i&&f.push(i),E({},o,{"sentry-trace":a,baggage:f.length>0?f.join(","):void 0})}return{"sentry-trace":a,baggage:i}}(m,f.getDynamicSamplingContext(),h,_))}}}(t,s,c,u)})),r&&Mt("xhr",(function(t){!function(t,e,n,r){var i=t.xhr,a=i&&i[Dt];if(!(!De()||i&&i.__sentry_own_request__)&&i&&a&&e(a.url))if(t.endTimestamp){var o=i.__sentry_xhr_span_id__;if(!o)return;var s=r[o];s&&(s.setHttpStatus(a.status_code),s.finish(),delete r[o])}else{var c=ht().getScope(),u=c&&c.getSpan(),f=u&&u.transaction;if(u&&f){var p=u.startChild({data:E({},a.data,{type:"xhr","http.method":a.method,url:a.url}),description:a.method+" "+a.url,op:"http.client"});if(i.__sentry_xhr_span_id__=p.spanId,r[i.__sentry_xhr_span_id__]=p,i.setRequestHeader&&n(a.url))try{i.setRequestHeader("sentry-trace",p.toTraceparent());var d=$e(f.getDynamicSamplingContext());d&&i.setRequestHeader(Fe,d)}catch(t){}}}}(t,s,c,u)}))}({traceFetch:c,traceXHR:u,tracePropagationTargets:f,shouldCreateSpanForRequest:p})},t._createRouteTransaction=function(t){var e=this;if(this._getCurrentHub){var n=this.options,r=n.beforeNavigate,i=n.idleTimeout,a=n.finalTimeout,o=n.heartbeatInterval,s="pageload"===t.op,c=s?Tn("sentry-trace"):null,f=s?Tn("baggage"):null,p=c?function(t){var e,n=t.match(Be);if(t&&n)return"1"===n[3]?e=!0:"0"===n[3]&&(e=!1),{traceId:n[1],parentSampled:e,parentSpanId:n[2]}}(c):void 0,d=f?function(t){if(u(t)||Array.isArray(t)){var e={};if(Array.isArray(t))e=t.reduce((function(t,e){return E({},t,Xe(e))}),{});else{if(!t)return;e=Xe(t)}var n=Object.entries(e).reduce((function(t,e){var n=e[0],r=e[1];return n.match(Ye)&&(t[n.slice(ze.length)]=r),t}),{});return Object.keys(n).length>0?n:void 0}}(f):void 0,l=E({},t,p,{metadata:E({},t.metadata,{dynamicSamplingContext:p&&!d?{}:d}),trimEnd:!0}),h="function"==typeof r?r(l):l,v=void 0===h?E({},l,{sampled:!1}):h;v.metadata=v.name!==l.name?E({},v.metadata,{source:"custom"}):v.metadata,this._latestRouteName=v.name,this._latestRouteSource=v.metadata&&v.metadata.source,v.sampled;var m=He(this._getCurrentHub(),v,i,a,!0,{location:Je.location},o);return m.registerBeforeFinishCallback((function(t){e._collectWebVitals(),function(t){var e=pn();if(e&&Je.performance.getEntries&&Q.Z1){var n,r,i=fn(Q.Z1),a=e.getEntries();if(a.slice(hn).forEach((function(e){var a=fn(e.startTime),o=fn(e.duration);if(!("navigation"===t.op&&i+a=t.startTimestamp)){var n=vn[e].value,r=i+fn(n),a=Math.abs(1e3*(r-t.startTimestamp));vn[e].value=a}}));var o=vn["mark.fid"];o&&vn.fid&&(sn(t,{description:"first input delay",endTimestamp:o.value+fn(vn.fid.value),op:"ui.action",startTimestamp:o.value}),delete vn["mark.fid"]),"fcp"in vn||delete vn.cls,Object.keys(vn).forEach((function(e){t.setMeasurement(e,vn[e].value,vn[e].unit)})),function(t){dn&&(dn.element&&t.setTag("lcp.element",I(dn.element)),dn.id&&t.setTag("lcp.id",dn.id),dn.url&&t.setTag("lcp.url",dn.url.trim().slice(0,200)),t.setTag("lcp.size",dn.size)),ln&&ln.sources&&ln.sources.forEach((function(e,n){return t.setTag("cls.source."+(n+1),I(e.node))}))}(t)}dn=void 0,ln=void 0,vn={}}}(t)})),m}},t._registerInteractionListener=function(){var t,e=this,n=function(){var n=e.options,r=n.idleTimeout,i=n.finalTimeout,a=n.heartbeatInterval,o=Pe();if(!(o&&o.op&&["navigation","pageload"].includes(o.op))&&(t&&(t.setFinishReason("interactionInterrupted"),t.finish(),t=void 0),e._getCurrentHub&&e._latestRouteName)){var s=e._getCurrentHub(),c=Je.location,u={name:e._latestRouteName,op:"ui.action.click",trimEnd:!0,metadata:{source:e._latestRouteSource||"url"}};t=He(s,u,r,i,!0,{location:c},a)}};["click"].forEach((function(t){addEventListener(t,n,{once:!1,capture:!0})}))},e}();function Tn(t){var e,n=(e="meta[name="+t+"]",k.document&&k.document.querySelector?k.document.querySelector(e):null);return n?n.getAttribute("content"):null}var En="7.56.0",xn=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function wn(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,a=t.port,o=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(a?":"+a:"")+"/"+(r?r+"/":r)+o}function kn(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function On(t){var e="string"==typeof t?function(t){var e=xn.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],a=n[2],o=void 0===a?"":a,s=n[3],c=n[4],u=void 0===c?"":c,f="",p=n[5],d=p.split("/");if(d.length>1&&(f=d.slice(0,-1).join("/"),p=d.pop()),p){var l=p.match(/^\d+/);l&&(p=l[0])}return kn({host:s,pass:o,path:f,projectId:p,port:u,protocol:r,publicKey:i})}console.error("Invalid Sentry Dsn: "+t)}(t):kn(t);if(e)return e}function In(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Rn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Rn(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Rn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Vn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},t._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._dsn},t._prepareEvent=function(t,e,n){var r=this.getOptions(),i=Object.keys(this._integrations);return!e.integrations&&i.length>0&&(e.integrations=i),function(t,e,n,r){var i=t.normalizeDepth,a=void 0===i?3:i,o=t.normalizeMaxBreadth,s=void 0===o?1e3:o,c=E({},e,{event_id:e.event_id||n.event_id||$(),timestamp:e.timestamp||(0,Q.yW)()}),u=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,a=e.maxValueLength,o=void 0===a?250:a;"environment"in t||(t.environment="environment"in e?n:nt),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=m(t.message,o));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=m(s.value,o));var c=t.request;c&&c.url&&(c.url=m(c.url,o))}(c,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(c,u),void 0===e.type&&function(t,e){var n,r=w.n2._sentryDebugIds;if(r){var i=Xn.get(e);i?n=i:(n=new Map,Xn.set(e,n));var a=Object.keys(r).reduce((function(t,i){var a,o=n.get(i);o?a=o:(a=e(i),n.set(i,a));for(var s=a.length-1;s>=0;s--){var c=a[s];if(c.filename){t[c.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=a[t.filename])}))}))}catch(t){}}}(c,t.stackParser);var f=r;n.captureContext&&(f=st.clone(f).update(n.captureContext));var p=rt(c);if(f){if(f.getAttachments){var d=[].concat(n.attachments||[],f.getAttachments());d.length&&(n.attachments=d)}p=f.applyToEvent(c,n)}return p.then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof a&&a>0?function(t,e,n){if(!t)return null;var r=E({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return E({},t,t.data&&{data:Xt(t.data,e,n)})}))},t.user&&{user:Xt(t.user,e,n)},t.contexts&&{contexts:Xt(t.contexts,e,n)},t.extra&&{extra:Xt(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=Xt(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){return t.data&&(t.data=Xt(t.data,e,n)),t}))),r}(t,a,s):t}))}(r,t,e,n)},t._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){}))},t._processEvent=function(t,e,n){var r=this,i=this.getOptions(),a=i.sampleRate;if(!this._isEnabled())return it(new Bn("SDK not enabled, will not capture event.","log"));var o=Zn(t),s=Kn(t),c=t.type||"error",u="before send for type `"+c+"`";if(s&&"number"==typeof a&&Math.random()>a)return this.recordDroppedEvent("sample_rate","error",t),it(new Bn("Discarding event because it's not included in the random sample (sampling rate = "+a+")","log"));var f="replay_event"===c?"replay":c;return this._prepareEvent(t,e,n).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",f,t),new Bn("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var a=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;return Kn(e)&&r?r(e,n):Zn(e)&&i?i(e,n):e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(l(t))return t.then((function(t){if(!p(t)&&null!==t)throw new Bn(n);return t}),(function(t){throw new Bn(e+" rejected with "+t)}));if(!p(t)&&null!==t)throw new Bn(n);return t}(a,u)})).then((function(i){if(null===i)throw r.recordDroppedEvent("before_send",f,t),new Bn(u+" returned `null`, will not send event.","log");var a=n&&n.getSession();!o&&a&&r._updateSessionFromEvent(a,i);var s=i.transaction_info;return o&&s&&i.transaction!==t.transaction&&(i.transaction_info=E({},s,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof Bn)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new Bn("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},t._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},t._sendEnvelope=function(t){if(this._transport&&this._dsn)return this.emit("beforeEnvelope",t),this._transport.send(t).then(null,(function(t){}))},t._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},e}();function Kn(t){return void 0===t.type}function Zn(t){return"transaction"===t.type}var Qn=n(476),tr=function(t){function e(e){var n,r=_t.SENTRY_SDK_SOURCE||(0,Qn.S)();return e._metadata=e._metadata||{},e._metadata.sdk=e._metadata.sdk||{name:"sentry.javascript.browser",packages:[{name:r+":@sentry/browser",version:En}],version:En},n=t.call(this,e)||this,e.sendClientReports&&_t.document&&_t.document.addEventListener("visibilitychange",(function(){"hidden"===_t.document.visibilityState&&n._flushOutcomes()})),n}Ee(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=ee(t,e,n&&n.syntheticException||void 0,r);return G(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),rt(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var a=ne(t,e,r&&r.syntheticException||void 0,i);return a.level=n,r&&r.event_id&&(a.event_id=r.event_id),rt(a)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.sendEvent=function(e,n){var r=this.getIntegrationById(de);r&&r.addSentryBreadcrumb&&r.addSentryBreadcrumb(e),t.prototype.sendEvent.call(this,e,n)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,a=E({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:wn(i)}),o=function(t){return[{type:"user_report"},t]}(t);return Cn(a,[o])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,Cn((n=this._options.tunnel&&wn(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:(0,Q.yW)(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(Gn);function er(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return nr(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?nr(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function nr(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){rt(t).then((function(){--i||(clearTimeout(a),n(!0))}),r)}))}))}}}(t.bufferSize||ir));var r={};function i(i){var a=[];if(jn(i,(function(e,n){var i,o,s,c=Nn(n);if(i=r,o=c,void 0===s&&(s=Date.now()),function(t,e){return t[e]||t.all||0}(i,o)>s){var u=or(e,n);t.recordDroppedEvent("ratelimit_backoff",c,u)}else a.push(e)})),0===a.length)return rt();var o=Cn(i[0],a),s=function(e){jn(o,(function(n,r){var i=or(n,r);t.recordDroppedEvent(e,Nn(r),i)}))};return n.add((function(){return e({body:Dn(o,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var a=E({},t),o=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(o)for(var c,u=er(o.trim().split(","));!(c=u()).done;){var f=c.value.split(":",2),p=f[0],d=f[1],l=parseInt(p,10),h=1e3*(isNaN(l)?60:l);if(d)for(var v,m=er(d.split(";"));!(v=m()).done;)a[v.value]=n+h;else a.all=n+h}else s?a.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?rr:r-e}(s,n):429===r&&(a.all=n+6e4);return a}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof Bn)return s("queue_overflow"),rt();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function or(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var sr=void 0;function cr(t,e){void 0===e&&(e=function(){if(sr)return sr;if(It(_t.fetch))return sr=_t.fetch.bind(_t);var t=_t.document,e=_t.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return sr=e.bind(_t)}());var n=0,r=0;return ar(t,(function(i){var a=i.body.length;n+=a,r++;var o=E({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,o).then((function(t){return n-=a,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return sr=void 0,n-=a,r--,it(t)}}))}var ur="?";function fr(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var pr=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dr=/\((\S*)(?::(\d+))(?::(\d+))\)/,lr=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,hr=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vr=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,mr=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=z.test(o)?o.replace(z,"$1"):o;if(!s.match(/\S*Error: /)){for(var c,u=B(r);!(c=u()).done;){var f=(0,c.value)(s);if(f){n.push(f);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=t.slice(0,50),n=e[e.length-1].function;n&&/sentryWrapped/.test(n)&&e.pop(),e.reverse();var r=e[e.length-1].function;return r&&/captureMessage|captureException/.test(r)&&e.pop(),e.map((function(t){return E({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=pr.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=dr.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=_r(e[1]||ur,e[2]),i=r[0];return fr(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=lr.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=hr.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||ur,a=_r(i,r);return i=a[0],fr(r=a[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=vr.exec(t);return e?fr(e[2],e[1]||ur,+e[3],e[4]?+e[4]:void 0):void 0}]]),_r=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:ur,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},gr=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="Dedupe"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(e,n){var r=function(e){if(e.type)return e;var r=n().getIntegration(t);if(r){try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!br(t,e)&&!!yr(t,e))))}(t,e)||!!function(t,e){var n=Sr(e),r=Sr(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!br(t,e)&&!!yr(t,e)))}(t,e))}(e,r._previousEvent))return null}catch(t){return r._previousEvent=e}return r._previousEvent=e}return e};r.id=this.name,e(r)},t}();function yr(t,e){var n=Tr(t),r=Tr(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i{var t={648:(t,e,n)=>{var r=n(288).default;function i(){"use strict";t.exports=i=function(){return e},t.exports.__esModule=!0,t.exports.default=t.exports;var e={},n=Object.prototype,a=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",u=s.asyncIterator||"@@asyncIterator",d=s.toStringTag||"@@toStringTag";function f(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,n){return t[e]=n}}function p(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,a=Object.create(i.prototype),s=new O(r||[]);return o(a,"_invoke",{value:E(t,n,s)}),a}function l(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=p;var h={};function v(){}function g(){}function m(){}var _={};f(_,c,(function(){return this}));var y=Object.getPrototypeOf,b=y&&y(y(C([])));b&&b!==n&&a.call(b,c)&&(_=b);var S=m.prototype=v.prototype=Object.create(_);function x(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function T(t,e){function n(i,o,s,c){var u=l(t[i],t,o);if("throw"!==u.type){var d=u.arg,f=d.value;return f&&"object"==r(f)&&a.call(f,"__await")?e.resolve(f.__await).then((function(t){n("next",t,s,c)}),(function(t){n("throw",t,s,c)})):e.resolve(f).then((function(t){d.value=t,s(d)}),(function(t){return n("throw",t,s,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,r){function a(){return new e((function(e,i){n(t,r,e,i)}))}return i=i?i.then(a,a):a()}})}function E(t,e,n){var r="suspendedStart";return function(i,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw a;return{value:void 0,done:!0}}for(n.method=i,n.arg=a;;){var o=n.delegate;if(o){var s=w(o,n);if(s){if(s===h)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var c=l(t,e,n);if("normal"===c.type){if(r=n.done?"completed":"suspendedYield",c.arg===h)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r="completed",n.method="throw",n.arg=c.arg)}}}function w(t,e){var n=e.method,r=t.iterator[n];if(void 0===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=void 0,w(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),h;var i=l(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var a=i.arg;return a?a.done?(e[t.resultName]=a.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function k(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function I(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(k,this),this.reset(!0)}function C(t){if(t){var e=t[c];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n=0;--r){var i=this.tryEntries[r],o=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=a.call(i,"catchLoc"),c=a.call(i,"finallyLoc");if(s&&c){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&a.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),I(n),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;I(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:C(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),h}},e}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},288:t=>{function e(n){return t.exports=e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.__esModule=!0,t.exports.default=t.exports,e(n)}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports},357:(t,e,n)=>{var r=n(648)();t.exports=r;try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var a=e[r]={exports:{}};return t[r](a,a.exports,n),a.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=!1;function a(t){return t&&t.Math==Math?t:void 0}var o="object"==typeof globalThis&&a(globalThis)||"object"==typeof window&&a(window)||"object"==typeof self&&a(self)||"object"==typeof n.g&&a(n.g)||function(){return this}()||{};function s(){return o}function c(t,e,n){var r=n||o,i=r.__SENTRY__=r.__SENTRY__||{};return i[t]||(i[t]=e())}var u=["debug","info","warn","error","log","assert","trace"],d={};function f(t){if(!("console"in o))return t();var e=o.console,n={},r=Object.keys(d);r.forEach((function(t){var r=d[t];n[t]=e[t],e[t]=r}));try{return t()}finally{r.forEach((function(t){e[t]=n[t]}))}}var p,l,h=(p=!1,l={enable:function(){p=!0},disable:function(){p=!1},isEnabled:function(){return p}},i?u.forEach((function(t){l[t]=function(){for(var e=arguments.length,n=new Array(e),r=0;r";try{for(var n,r=t,i=[],a=0,o=0,s=Array.isArray(e)?e:e.keyAttrs,c=!Array.isArray(e)&&e.maxStringLength||R;r&&a++<5&&!("html"===(n=P(r,s))||a>1&&o+3*i.length+n.length>=c);)i.push(n),o+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function P(t,e){var n,r,i,a,o,s=t,c=[];if(!s||!s.tagName)return"";if(A.HTMLElement&&s instanceof HTMLElement&&s.dataset&&s.dataset.sentryComponent)return s.dataset.sentryComponent;c.push(s.tagName.toLowerCase());var u=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(u&&u.length)u.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&c.push("#"+s.id),(n=s.className)&&S(n))for(r=n.split(/\s+/),o=0;o"}}function J(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function z(t){return $(t,new Map)}function $(t,e){if(function(t){if(!E(t))return!1;try{var e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,a=Object.keys(t);i>t/4).toString(16)}))}function V(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function W(t){var e=t.message,n=t.event_id;if(e)return e;var r=V(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function X(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],a=i[0]=i[0]||{};a.value||(a.value=e||""),a.type||(a.type=n||"Error")}function K(t,e){var n=V(t);if(n){var r=n.mechanism;if(n.mechanism=v({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=v({},r&&r.data,e.data);n.mechanism.data=i}}}function Q(t){if(t&&t.__sentry_captured__)return!0;try{q(t,"__sentry_captured__",!0)}catch(t){}return!1}var Z,tt=!1;function et(t){return new rt((function(e){e(t)}))}function nt(t){return new rt((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(Z||(Z={}));var rt=function(){function t(e){t.prototype.__init.call(this),t.prototype.__init2.call(this),t.prototype.__init3.call(this),t.prototype.__init4.call(this),this._state=Z.PENDING,this._handlers=[];try{e(this._resolve,this._reject)}catch(t){this._reject(t)}}var e=t.prototype;return e.then=function(e,n){var r=this;return new t((function(t,i){r._handlers.push([!1,function(n){if(e)try{t(e(n))}catch(t){i(t)}else t(n)},function(e){if(n)try{t(n(e))}catch(t){i(t)}else i(e)}]),r._executeHandlers()}))},e.catch=function(t){return this.then((function(t){return t}),t)},e.finally=function(e){var n=this;return new t((function(t,r){var i,a;return n.then((function(t){a=!1,i=t,e&&e()}),(function(t){a=!0,i=t,e&&e()})).then((function(){a?r(i):t(i)}))}))},e.__init=function(){var t=this;this._resolve=function(e){t._setResult(Z.RESOLVED,e)}},e.__init2=function(){var t=this;this._reject=function(e){t._setResult(Z.REJECTED,e)}},e.__init3=function(){var t=this;this._setResult=function(e,n){t._state===Z.PENDING&&(k(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},e.__init4=function(){var t=this;this._executeHandlers=function(){if(t._state!==Z.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===Z.RESOLVED&&e[1](t._value),t._state===Z.REJECTED&&e[2](t._value),e[0]=!0)}))}}},t}();function it(){return c("globalEventProcessors",(function(){return[]}))}function at(t){it().push(t)}function ot(t,e,n,r){return void 0===r&&(r=0),new rt((function(i,a){var o=t[r];if(null===e||"function"!=typeof o)i(e);else{var s=o(v({},e),n);tt&&o.id&&null===s&&h.log('Event processor "'+o.id+'" dropped event'),k(s)?s.then((function(e){return ot(t,e,n,r+1).then(i)})).then(null,a):ot(t,s,n,r+1).then(i).then(null,a)}}))}var st=1e3;function ct(){return Date.now()/st}var ut=function(){var t=o.performance;if(!t||!t.now)return ct;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/st}}(),dt=function(){var t=o.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,a=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function lt(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return ht(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ht(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function ht(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nn?bt(t,e-1,n):i}function St(t,e,r,i,a){var o,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===a&&(o="function"==typeof WeakSet,s=o?new WeakSet:[],a=[function(t){if(o)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){h[m]="[MaxProperties ~]";break}var _=g[m];h[m]=St(m,_,p-1,i,a),v++}return d(e),h}var xt="baggage",Tt="sentry-",Et=/^sentry-/,wt=8192;function kt(t){if(t)return function(t){if(0!==Object.keys(t).length)return Object.entries(t).reduce((function(t,e,n){var r=e[0],a=e[1],o=encodeURIComponent(r)+"="+encodeURIComponent(a),s=0===n?o:t+","+o;return s.length>wt?(i&&h.warn("Not adding key: "+r+" with val: "+a+" to baggage header due to exceeding baggage size limits."),t):s}),"")}(Object.entries(t).reduce((function(t,e){var n=e[0],r=e[1];return r&&(t[""+Tt+n]=r),t}),{}))}function It(t){return t.split(",").map((function(t){return t.split("=").map((function(t){return decodeURIComponent(t.trim())}))})).reduce((function(t,e){var n=e[0],r=e[1];return t[n]=r,t}),{})}var Ot=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function Ct(t,e){var n=function(t){if(t){var e,n=t.match(Ot);if(n)return"1"===n[3]?e=!0:"0"===n[3]&&(e=!1),{traceId:n[1],parentSampled:e,parentSpanId:n[2]}}}(t),r=function(t){if(S(t)||Array.isArray(t)){var e={};if(Array.isArray(t))e=t.reduce((function(t,e){for(var n=It(e),r=0,i=Object.keys(n);r0?n:void 0}}(e),i=n||{},a=i.traceId,o=i.parentSpanId,s=i.parentSampled;return n?{traceId:a||G(),parentSpanId:o||G().substring(16),spanId:G().substring(16),sampled:s,dsc:r||{}}:{traceId:a||G(),spanId:G().substring(16)}}function At(t,e,n){void 0===t&&(t=G()),void 0===e&&(e=G().substring(16));var r="";return void 0!==n&&(r=n?"-1":"-0"),t+"-"+e+r}var Rt=1;function jt(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=Mt(t);return z({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function Pt(t){var e=t.spanContext();return At(e.traceId,e.spanId,Lt(t))}function Nt(t){return"number"==typeof t?Dt(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?Dt(t.getTime()):ut()}function Dt(t){return t>9999999999?t/1e3:t}function Mt(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function Lt(t){var e=t.spanContext().traceFlags;return Boolean(e&Rt)}var Ut=new WeakMap;var qt=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function Ft(t,e){return ie().captureEvent(t,e)}function Ht(t,e){ie().addBreadcrumb(t,e)}function Bt(){return ie().getClient()}function Yt(){return ie().getScope()}function Jt(t){return t.transaction}function zt(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,a=(n&&n.getUser()||{}).segment,o=z({environment:r.environment||ft,release:r.release,user_segment:a,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",o),o}function $t(t){var e=Bt();if(!e)return{};var n=zt(Mt(t).trace_id||"",e,Yt()),r=Jt(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var a=r.metadata,o=a.sampleRate,s=a.source;null!=o&&(n.sample_rate=""+o);var c=Mt(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(Lt(r)),e.emit&&e.emit("createDsc",n),n}function Gt(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,a=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,a=e.contexts,o=e.level,s=e.transactionName,c=z(n);c&&Object.keys(c).length&&(t.extra=v({},c,t.extra));var u=z(r);u&&Object.keys(u).length&&(t.tags=v({},u,t.tags));var d=z(i);d&&Object.keys(d).length&&(t.user=v({},d,t.user));var f=z(a);f&&Object.keys(f).length&&(t.contexts=v({},f,t.contexts)),o&&(t.level=o),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=v({trace:jt(e)},t.contexts);var n=Jt(e);if(n){t.sdkProcessingMetadata=v({dynamicSamplingContext:$t(e)},t.sdkProcessingMetadata);var r=Mt(n).description;r&&(t.tags=v({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=v({},t.sdkProcessingMetadata,e)}(t,a)}function Vt(t,e){var n=e.extra,r=e.tags,i=e.user,a=e.contexts,o=e.level,s=e.sdkProcessingMetadata,c=e.breadcrumbs,u=e.fingerprint,d=e.eventProcessors,f=e.attachments,p=e.propagationContext,l=e.transactionName,h=e.span;Wt(t,"extra",n),Wt(t,"tags",r),Wt(t,"user",i),Wt(t,"contexts",a),Wt(t,"sdkProcessingMetadata",s),o&&(t.level=o),l&&(t.transactionName=l),h&&(t.span=h),c.length&&(t.breadcrumbs=[].concat(t.breadcrumbs,c)),u.length&&(t.fingerprint=[].concat(t.fingerprint,u)),d.length&&(t.eventProcessors=[].concat(t.eventProcessors,d)),f.length&&(t.attachments=[].concat(t.attachments,f)),t.propagationContext=v({},t.propagationContext,p)}function Wt(t,e,n){if(n&&Object.keys(n).length)for(var r in t[e]=v({},t[e]),n)Object.prototype.hasOwnProperty.call(n,r)&&(t[e][r]=n[r])}var Xt,Kt=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=Qt()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=v({},this._tags),e._extra=v({},this._extra),e._contexts=v({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=v({},this._sdkProcessingMetadata),e._propagationContext=v({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&pt(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=v({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=v({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=v({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=v({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=v({},this._tags,r.tags),this._extra=v({},this._extra,r.extra),this._contexts=v({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(E(n)){var i=e;this._tags=v({},this._tags,i.tags),this._extra=v({},this._extra,i.extra),this._contexts=v({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=Qt(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=v({timestamp:ct()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),Gt(t,this.getScopeData()),ot([].concat(n,it(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=v({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:G();if(!this._client)return h.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,v({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:G();if(!this._client)return h.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,v({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:G();return this._client?(this._client.captureEvent(t,v({},e,{event_id:n}),this),n):(h.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function Qt(){return{traceId:G(),spanId:G().substring(16)}}var Zt="7.119.1",te=parseFloat(Zt),ee=function(){function t(t,e,n,r){var i,a;void 0===r&&(r=te),this._version=r,e?i=e:(i=new Kt).setClient(t),n?a=n:(a=new Kt).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=a}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(n=r()).done;){var i=n.value;i&&i.afterAllSetup&&i.afterAllSetup(t)}}function fe(t,e,n){if(n[e.name])tt&&h.log("Integration skipped because it was already installed: "+e.name);else{if(n[e.name]=e,-1===ue.indexOf(e.name)&&(e.setupOnce(at,ie),ue.push(e.name)),e.setup&&"function"==typeof e.setup&&e.setup(t),t.on&&"function"==typeof e.preprocessEvent){var r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(function(e,n){return r(e,n,t)}))}if(t.addEventProcessor&&"function"==typeof e.processEvent){var i=e.processEvent.bind(e),a=Object.assign((function(e,n){return i(e,n,t)}),{id:e.name});t.addEventProcessor(a)}tt&&h.log("Integration installed: "+e.name)}}function pe(t,e){return Object.assign((function(){return e.apply(void 0,arguments)}),{id:t})}var le,he=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/],ve=[/^.*\/healthcheck$/,/^.*\/healthy$/,/^.*\/live$/,/^.*\/ready$/,/^.*\/heartbeat$/,/^.*\/health$/,/^.*\/healthz$/],ge="InboundFilters",me=function(t){return void 0===t&&(t={}),{name:ge,setupOnce:function(){},processEvent:function(e,n,r){var i=r.getOptions(),a=function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),{allowUrls:[].concat(t.allowUrls||[],e.allowUrls||[]),denyUrls:[].concat(t.denyUrls||[],e.denyUrls||[]),ignoreErrors:[].concat(t.ignoreErrors||[],e.ignoreErrors||[],t.disableErrorDefaults?[]:he),ignoreTransactions:[].concat(t.ignoreTransactions||[],e.ignoreTransactions||[],t.disableTransactionDefaults?[]:ve),ignoreInternal:void 0===t.ignoreInternal||t.ignoreInternal}}(t,i);return function(t,e){return e.ignoreInternal&&function(t){try{return"SentryError"===t.exception.values[0].type}catch(t){}return!1}(t)?(tt&&h.warn("Event dropped due to being internal Sentry Error.\nEvent: "+W(t)),!0):function(t,e){return!(t.type||!e||!e.length)&&function(t){var e,n=[];t.message&&n.push(t.message);try{e=t.exception.values[t.exception.values.length-1]}catch(t){}return e&&e.value&&(n.push(e.value),e.type&&n.push(e.type+": "+e.value)),tt&&0===n.length&&h.error("Could not extract message for event "+W(t)),n}(t).some((function(t){return L(t,e)}))}(t,e.ignoreErrors)?(tt&&h.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: "+W(t)),!0):function(t,e){if("transaction"!==t.type||!e||!e.length)return!1;var n=t.transaction;return!!n&&L(n,e)}(t,e.ignoreTransactions)?(tt&&h.warn("Event dropped due to being matched by `ignoreTransactions` option.\nEvent: "+W(t)),!0):function(t,e){if(!e||!e.length)return!1;var n=ye(t);return!!n&&L(n,e)}(t,e.denyUrls)?(tt&&h.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: "+W(t)+".\nUrl: "+ye(t)),!0):!function(t,e){if(!e||!e.length)return!0;var n=ye(t);return!n||L(n,e)}(t,e.allowUrls)&&(tt&&h.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: "+W(t)+".\nUrl: "+ye(t)),!0)}(e,a)?null:e}}},_e=pe(ge,me);function ye(t){try{var e;try{e=t.exception.values[0].stacktrace.frames}catch(t){}return e?function(t){void 0===t&&(t=[]);for(var e=t.length-1;e>=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(e){return tt&&h.error("Cannot extract url for event "+W(t)),null}}var be="FunctionToString",Se=new WeakMap,xe=function(){return{name:be,setupOnce:function(){le=Function.prototype.toString;try{Function.prototype.toString=function(){for(var t=H(this),e=Se.has(Bt())&&void 0!==t?t:this,n=arguments.length,r=new Array(n),i=0;i0}function Ie(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return"function"==typeof r?r:t;if(H(t))return t}catch(e){return t}var i=function(){var r=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var i=r.map((function(t){return Ie(t,e)}));return t.apply(this,i)}catch(t){throw we++,setTimeout((function(){we--})),function(){for(var t=ie(),e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=a()).done;){var o=r.value;try{o(e)}catch(e){i&&h.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+_t(o)+"\nError:",e)}}}var Be=null;function Ye(t){var e="error";qe(e,t),Fe(e,Je)}function Je(){Be=o.onerror,o.onerror=function(t,e,n,r,i){return He("error",{column:r,error:i,line:n,msg:t,url:e}),!(!Be||Be.__SENTRY_LOADER__)&&Be.apply(this,arguments)},o.onerror.__SENTRY_INSTRUMENTED__=!0}var ze=null;function $e(t){var e="unhandledrejection";qe(e,t),Fe(e,Ge)}function Ge(){ze=o.onunhandledrejection,o.onunhandledrejection=function(t){return He("unhandledrejection",t),!(ze&&!ze.__SENTRY_LOADER__)||ze.apply(this,arguments)},o.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function Ve(t,e){var n=Xe(t,e),r={type:e&&e.name,value:Qe(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function We(t,e){return{exception:{values:[Ve(t,e)]}}}function Xe(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(Ke.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var Ke=/Minified React error #\d+;/i;function Qe(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function Ze(t,e,n,r,i){var a;if(y(e)&&e.error)return We(t,e.error);if(b(e)||_(e,"DOMException")){var o=e;if("stack"in e)a=We(t,e);else{var s=o.name||(b(o)?"DOMError":"DOMException"),c=o.message?s+": "+o.message:s;X(a=tn(t,c,n,r),c)}return"code"in o&&(a.tags=v({},a.tags,{"DOMException.code":""+o.code})),a}return m(e)?We(t,e):E(e)||w(e)?(a=function(t,e,n,r){var i=Bt(),a=i&&i.getOptions().normalizeDepth,o={exception:{values:[{type:w(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:en(e,{isUnhandledRejection:r})}]},extra:{__serialized__:bt(e,a)}};if(n){var s=Xe(t,n);s.length&&(o.exception.values[0].stacktrace={frames:s})}return o}(t,e,n,i),K(a,{synthetic:!0}),a):(X(a=tn(t,e,n,r),""+e,void 0),K(a,{synthetic:!0}),a)}function tn(t,e,n,r){var i={};if(r&&n){var a=Xe(t,n);a.length&&(i.exception={values:[{value:e,stacktrace:{frames:a}}]})}if(x(e)){var o=e.__sentry_template_string__,s=e.__sentry_template_values__;return i.logentry={message:o,params:s},i}return i.message=e,i}function en(t,e){var n=e.isUnhandledRejection,r=function(t,e){void 0===e&&(e=40);var n=Object.keys(B(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return D(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:D(i,e)}return""}(t),i=n?"promise rejection":"exception";return y(t)?"Event `ErrorEvent` captured as "+i+" with message `"+t.message+"`":w(t)?"Event `"+function(t){try{var e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch(t){}}(t)+"` (type="+t.type+") captured as "+i:"Object captured as "+i+" with keys: "+r}var nn="GlobalHandlers",rn=function(t){void 0===t&&(t={});var e=v({onerror:!0,onunhandledrejection:!0},t);return{name:nn,setupOnce:function(){Error.stackTraceLimit=50},setup:function(t){e.onerror&&(function(t){Ye((function(e){var n=cn(),r=n.stackParser,i=n.attachStacktrace;if(Bt()===t&&!ke()){var a=e.msg,o=e.url,s=e.line,c=e.column,u=e.error,d=void 0===u&&S(a)?function(t,e,n,r){var i=y(t)?t.message:t,a="Error",o=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return o&&(a=o[1],i=o[2]),on({exception:{values:[{type:a,value:i}]}},e,n,r)}(a,o,s,c):on(Ze(r,u||a,void 0,i,!1),o,s,c);d.level="error",Ft(d,{originalException:u,mechanism:{handled:!1,type:"onerror"}})}}))}(t),sn("onerror")),e.onunhandledrejection&&(function(t){$e((function(e){var n=cn(),r=n.stackParser,i=n.attachStacktrace;if(Bt()===t&&!ke()){var a=function(t){if(T(t))return t;var e=t;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch(t){}return t}(e),o=T(a)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(a)}]}}:Ze(r,a,void 0,i,!0);o.level="error",Ft(o,{originalException:a,mechanism:{handled:!1,type:"onunhandledrejection"}})}}))}(t),sn("onunhandledrejection"))}}},an=pe(nn,rn);function on(t,e,n,r){var i=t.exception=t.exception||{},a=i.values=i.values||[],o=a[0]=a[0]||{},s=o.stacktrace=o.stacktrace||{},c=s.frames=s.frames||[],u=isNaN(parseInt(r,10))?void 0:r,d=isNaN(parseInt(n,10))?void 0:n,f=S(e)&&e.length>0?e:function(){try{return A.document.location.href}catch(t){return""}}();return 0===c.length&&c.push({colno:u,filename:f,function:"?",in_app:!0,lineno:d}),t}function sn(t){}function cn(){var t=Bt();return t&&t.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1}}function un(){"console"in o&&u.forEach((function(t){t in o.console&&U(o.console,t,(function(e){return d[t]=e,function(){for(var e=arguments.length,n=new Array(e),r=0;r2?n[2]:void 0;if(i){var a=In,o=String(i);In=o,He("history",{from:a,to:o})}return t.apply(this,n)}}}var jn=["fatal","error","warning","log","info","debug"];function Pn(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var Nn=1024,Dn="Breadcrumbs",Mn=function(t){void 0===t&&(t={});var e=v({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t);return{name:Dn,setupOnce:function(){},setup:function(t){var n;e.console&&(n=function(t){return function(e){if(Bt()===t){var n={category:"console",data:{arguments:e.args,logger:"console"},level:(r=e.level,"warn"===r?"warning":jn.includes(r)?r:"log"),message:M(e.args," ")};if("assert"===e.level){if(!1!==e.args[0])return;n.message="Assertion failed: "+(M(e.args.slice(1)," ")||"console.assert"),n.data.arguments=e.args.slice(1)}Ht(n,{input:e.args,level:e.level})}var r}}(t),qe("console",n),Fe("console",un)),e.dom&&function(t){qe("dom",t),Fe("dom",vn)}(function(t,e){return function(n){if(Bt()===t){var r,i,a="object"==typeof e?e.serializeAttribute:void 0,o="object"==typeof e&&"number"==typeof e.maxStringLength?e.maxStringLength:void 0;o&&o>Nn&&(o=Nn),"string"==typeof a&&(a=[a]);try{var s=n.event,c=function(t){return!!t&&!!t.target}(s)?s.target:s;r=j(c,{keyAttrs:a,maxStringLength:o}),i=N(c)}catch(t){r=""}if(0!==r.length){var u={category:"ui."+n.name,message:r};i&&(u.data={"ui.component_name":i}),Ht(u,{event:n.event,name:n.name,global:n.global})}}}}(t,e.dom)),e.xhr&&yn(function(t){return function(e){if(Bt()===t){var n=e.startTimestamp,r=e.endTimestamp,i=e.xhr[_n];if(n&&r&&i){var a=i.method,o=i.url,s=i.status_code,c=i.body;Ht({category:"xhr",data:{method:a,url:o,status_code:s},type:"http"},{xhr:e.xhr,input:c,startTimestamp:n,endTimestamp:r})}}}}(t)),e.fetch&&Tn(function(t){return function(e){if(Bt()===t){var n=e.startTimestamp,r=e.endTimestamp;if(r&&(!e.fetchData.url.match(/sentry_key/)||"POST"!==e.fetchData.method))if(e.error)Ht({category:"fetch",data:e.fetchData,level:"error",type:"http"},{data:e.error,input:e.args,startTimestamp:n,endTimestamp:r});else{var i=e.response;Ht({category:"fetch",data:v({},e.fetchData,{status_code:i&&i.status}),type:"http"},{input:e.args,response:i,startTimestamp:n,endTimestamp:r})}}}}(t)),e.history&&An(function(t){return function(e){if(Bt()===t){var n=e.from,r=e.to,i=Pn(Ee.location.href),a=n?Pn(n):void 0,o=Pn(r);a&&a.path||(a=i),i.protocol===o.protocol&&i.host===o.host&&(r=o.relative),i.protocol===a.protocol&&i.host===a.host&&(n=a.relative),Ht({category:"navigation",data:{from:n,to:r}})}}}(t)),e.sentry&&t.on&&t.on("beforeSendEvent",function(t){return function(e){Bt()===t&&Ht({category:"sentry."+("transaction"===e.type?"transaction":"event"),event_id:e.event_id,level:e.level,message:W(e)},{event:e})}}(t))}}},Ln=pe(Dn,Mn);function Un(t,e,n,r,i,a,o){if(void 0===n&&(n=250),a.exception&&a.exception.values&&o&&O(o.originalException,Error)){var s,c,u=a.exception.values.length>0?a.exception.values[a.exception.values.length-1]:void 0;u&&(a.exception.values=(s=qn(t,e,i,o.originalException,r,a.exception.values,u,0),c=n,s.map((function(t){return t.value&&(t.value=D(t.value,c)),t}))))}}function qn(t,e,n,r,i,a,o,s){if(a.length>=n+1)return a;var c=[].concat(a);if(O(r[i],Error)){Fn(o,s);var u=t(e,r[i]),d=c.length;Hn(u,i,d,s),c=qn(t,e,n,r[i],i,[u].concat(c),u,d)}return Array.isArray(r.errors)&&r.errors.forEach((function(r,a){if(O(r,Error)){Fn(o,s);var u=t(e,r),d=c.length;Hn(u,"errors["+a+"]",d,s),c=qn(t,e,n,r,i,[u].concat(c),u,d)}})),c}function Fn(t,e){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=v({},t.mechanism,"AggregateError"===t.type&&{is_exception_group:!0},{exception_id:e})}function Hn(t,e,n,r){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=v({},t.mechanism,{type:"chained",source:e,exception_id:n,parent_id:r})}var Bn,Yn="LinkedErrors",Jn=function(t){void 0===t&&(t={});var e=t.limit||5,n=t.key||"cause";return{name:Yn,setupOnce:function(){},preprocessEvent:function(t,r,i){var a=i.getOptions();Un(Ve,a.stackParser,a.maxValueLength,n,e,t,r)}}},zn=pe(Yn,Jn),$n="HttpContext",Gn=function(){return{name:$n,setupOnce:function(){},preprocessEvent:function(t){if(Ee.navigator||Ee.location||Ee.document){var e=t.request&&t.request.url||Ee.location&&Ee.location.href,n=(Ee.document||{}).referrer,r=(Ee.navigator||{}).userAgent,i=v({},t.request&&t.request.headers,n&&{Referer:n},r&&{"User-Agent":r}),a=v({},t.request,e&&{url:e},{headers:i});t.request=a}}}},Vn=pe($n,Gn);function Wn(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Xn(t,e){return Xn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},Xn(t,e)}function Kn(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Xn(t,e)}function Qn(t){return Qn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qn(t)}function Zn(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(n=i()).done;){var a=n.value[1],o=a[0],s=a[1];r[o]||(r[o]=[]),r[o].push(z(s))}return r}}var rr,ir="sentry.source",ar="sentry.sample_rate",or="sentry.op",sr="sentry.origin";function cr(t,e){t.setTag("http.status_code",String(e)),t.setData("http.response.status_code",e);var n=function(t){if(t<400&&t>=100)return"ok";if(t>=400&&t<500)switch(t){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(t>=500&&t<600)switch(t){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"}(e);"unknown_error"!==n&&t.setStatus(n)}!function(t){t.Ok="ok",t.DeadlineExceeded="deadline_exceeded",t.Unauthenticated="unauthenticated",t.PermissionDenied="permission_denied",t.NotFound="not_found",t.ResourceExhausted="resource_exhausted",t.InvalidArgument="invalid_argument",t.Unimplemented="unimplemented",t.Unavailable="unavailable",t.InternalError="internal_error",t.UnknownError="unknown_error",t.Cancelled="cancelled",t.AlreadyExists="already_exists",t.FailedPrecondition="failed_precondition",t.Aborted="aborted",t.OutOfRange="out_of_range",t.DataLoss="data_loss"}(rr||(rr={}));var ur=function(){function t(t){void 0===t&&(t=1e3),this._maxlen=t,this.spans=[]}return t.prototype.add=function(t){this.spans.length>this._maxlen?t.spanRecorder=void 0:this.spans.push(t)},t}(),dr=function(){function t(t){var e;void 0===t&&(t={}),this._traceId=t.traceId||G(),this._spanId=t.spanId||G().substring(16),this._startTime=t.startTimestamp||ut(),this.tags=t.tags?v({},t.tags):{},this.data=t.data?v({},t.data):{},this.instrumenter=t.instrumenter||"sentry",this._attributes={},this.setAttributes(v(((e={})[sr]=t.origin||"manual",e[or]=t.op,e),t.attributes)),this._name=t.name||t.description,t.parentSpanId&&(this._parentSpanId=t.parentSpanId),"sampled"in t&&(this._sampled=t.sampled),t.status&&(this._status=t.status),t.endTimestamp&&(this._endTime=t.endTimestamp),void 0!==t.exclusiveTime&&(this._exclusiveTime=t.exclusiveTime),this._measurements=t.measurements?v({},t.measurements):{}}var e=t.prototype;return e.spanContext=function(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:this._sampled?Rt:0}},e.startChild=function(e){var n=new t(v({},e,{parentSpanId:this._spanId,sampled:this._sampled,traceId:this._traceId}));n.spanRecorder=this.spanRecorder,n.spanRecorder&&n.spanRecorder.add(n);var r=Jt(this);if(n.transaction=r,tt&&r){var i="[Tracing] Starting '"+(e&&e.op||"< unknown op >")+"' span on transaction '"+(Mt(n).description||"< unknown name >")+"' ("+r.spanContext().spanId+").";h.log(i),this._logMessage=i}return n},e.setTag=function(t,e){var n;return this.tags=v({},this.tags,((n={})[t]=e,n)),this},e.setData=function(t,e){var n;return this.data=v({},this.data,((n={})[t]=e,n)),this},e.setAttribute=function(t,e){void 0===e?delete this._attributes[t]:this._attributes[t]=e},e.setAttributes=function(t){var e=this;Object.keys(t).forEach((function(n){return e.setAttribute(n,t[n])}))},e.setStatus=function(t){return this._status=t,this},e.setHttpStatus=function(t){return cr(this,t),this},e.setName=function(t){this.updateName(t)},e.updateName=function(t){return this._name=t,this},e.isSuccess=function(){return"ok"===this._status},e.finish=function(t){return this.end(t)},e.end=function(t){if(!this._endTime){var e=Jt(this);if(tt&&e&&e.spanContext().spanId!==this._spanId){var n=this._logMessage;n&&h.log(n.replace("Starting","Finishing"))}this._endTime=Nt(t)}},e.toTraceparent=function(){return Pt(this)},e.toContext=function(){return z({data:this._getData(),description:this._name,endTimestamp:this._endTime,op:this.op,parentSpanId:this._parentSpanId,sampled:this._sampled,spanId:this._spanId,startTimestamp:this._startTime,status:this._status,tags:this.tags,traceId:this._traceId})},e.updateWithContext=function(t){return this.data=t.data||{},this._name=t.name||t.description,this._endTime=t.endTimestamp,this.op=t.op,this._parentSpanId=t.parentSpanId,this._sampled=t.sampled,this._spanId=t.spanId||this._spanId,this._startTime=t.startTimestamp||this._startTime,this._status=t.status,this.tags=t.tags||{},this._traceId=t.traceId||this._traceId,this},e.getTraceContext=function(){return jt(this)},e.getSpanJSON=function(){return z({data:this._getData(),description:this._name,op:this._attributes[or],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:this._status,tags:Object.keys(this.tags).length>0?this.tags:void 0,timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[sr],_metrics_summary:nr(this),profile_id:this._attributes.profile_id,exclusive_time:this._exclusiveTime,measurements:Object.keys(this._measurements).length>0?this._measurements:void 0})},e.isRecording=function(){return!this._endTime&&!!this._sampled},e.toJSON=function(){return this.getSpanJSON()},e._getData=function(){var t=this.data,e=this._attributes,n=Object.keys(t).length>0,r=Object.keys(e).length>0;if(n||r)return n&&r?v({},t,e):n?t:e},tr(t,[{key:"name",get:function(){return this._name||""},set:function(t){this.updateName(t)}},{key:"description",get:function(){return this._name},set:function(t){this._name=t}},{key:"traceId",get:function(){return this._traceId},set:function(t){this._traceId=t}},{key:"spanId",get:function(){return this._spanId},set:function(t){this._spanId=t}},{key:"parentSpanId",get:function(){return this._parentSpanId},set:function(t){this._parentSpanId=t}},{key:"sampled",get:function(){return this._sampled},set:function(t){this._sampled=t}},{key:"attributes",get:function(){return this._attributes},set:function(t){this._attributes=t}},{key:"startTimestamp",get:function(){return this._startTime},set:function(t){this._startTime=t}},{key:"endTimestamp",get:function(){return this._endTime},set:function(t){this._endTime=t}},{key:"status",get:function(){return this._status},set:function(t){this._status=t}},{key:"op",get:function(){return this._attributes[or]},set:function(t){this.setAttribute(or,t)}},{key:"origin",get:function(){return this._attributes[sr]},set:function(t){this.setAttribute(sr,t)}}]),t}();function fr(t){var e=Bt(),n=t||e&&e.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}function pr(t){if(fr()){var e=function(t){if(t.startTime){var e=v({},t);return e.startTimestamp=Nt(t.startTime),delete e.startTime,e}return t}(t),n=ie(),r=t.scope?t.scope.getSpan():Yt().getSpan();if(!t.onlyIfParent||r){var i=(t.scope||Yt()).clone();return function(t,e){var n=e.parentSpan,r=e.spanContext,i=e.forceTransaction,a=e.scope;if(fr()){var o,s=ae();if(n&&!i)o=n.startChild(r);else if(n){var c=$t(n),u=n.spanContext(),d=u.traceId,f=u.spanId,p=Lt(n);o=t.startTransaction(v({traceId:d,parentSpanId:f,parentSampled:p},r,{metadata:v({dynamicSamplingContext:c},r.metadata)}))}else{var l=v({},s.getPropagationContext(),a.getPropagationContext()),h=l.traceId,g=l.dsc,m=l.parentSpanId,_=l.sampled;o=t.startTransaction(v({traceId:h,parentSpanId:m,parentSampled:_},r,{metadata:v({dynamicSamplingContext:g},r.metadata)}))}return a.setSpan(o),function(t,e,n){t&&(q(t,hr,n),q(t,lr,e))}(o,a,s),o}}(n,{parentSpan:r,spanContext:e,forceTransaction:t.forceTransaction,scope:i})}}}var lr="_sentryScope",hr="_sentryIsolationScope",vr=function(t){function e(e,n){var r;(r=t.call(this,e)||this)._contexts={},r._hub=n||ie(),r._name=e.name||"",r._metadata=v({},e.metadata),r._trimEnd=e.trimEnd,r.transaction=Wn(r);var i=r._metadata.dynamicSamplingContext;return i&&(r._frozenDynamicSamplingContext=v({},i)),r}Kn(e,t);var n=e.prototype;return n.setName=function(t,e){void 0===e&&(e="custom"),this._name=t,this.setAttribute(ir,e)},n.updateName=function(t){return this._name=t,this},n.initSpanRecorder=function(t){void 0===t&&(t=1e3),this.spanRecorder||(this.spanRecorder=new ur(t)),this.spanRecorder.add(this)},n.setContext=function(t,e){null===e?delete this._contexts[t]:this._contexts[t]=e},n.setMeasurement=function(t,e,n){void 0===n&&(n=""),this._measurements[t]={value:e,unit:n}},n.setMetadata=function(t){this._metadata=v({},this._metadata,t)},n.end=function(t){var e=Nt(t),n=this._finishTransaction(e);if(n)return this._hub.captureEvent(n)},n.toContext=function(){return z(v({},t.prototype.toContext.call(this),{name:this._name,trimEnd:this._trimEnd}))},n.updateWithContext=function(e){return t.prototype.updateWithContext.call(this,e),this._name=e.name||"",this._trimEnd=e.trimEnd,this},n.getDynamicSamplingContext=function(){return $t(this)},n.setHub=function(t){this._hub=t},n.getProfileId=function(){if(void 0!==this._contexts&&void 0!==this._contexts.profile)return this._contexts.profile.profile_id},n._finishTransaction=function(e){var n=this;if(void 0===this._endTime){this._name||(tt&&h.warn("Transaction has no name, falling back to ``."),this._name=""),t.prototype.end.call(this,e);var r=this._hub.getClient();if(r&&r.emit&&r.emit("finishTransaction",this),!0!==this._sampled)return tt&&h.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled."),void(r&&r.recordDroppedEvent("sample_rate","transaction"));var i=this.spanRecorder?this.spanRecorder.spans.filter((function(t){return t!==n&&Mt(t).timestamp})):[];if(this._trimEnd&&i.length>0){var a=i.map((function(t){return Mt(t).timestamp})).filter(Boolean);this._endTime=a.reduce((function(t,e){return t>e?t:e}))}var o={scope:this[lr],isolationScope:this[hr]},s=o.scope,c=o.isolationScope,u=this.metadata,d=u.source,f=v({contexts:v({},this._contexts,{trace:jt(this)}),spans:i,start_timestamp:this._startTime,tags:this.tags,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:v({},u,{capturedSpanScope:s,capturedSpanIsolationScope:c},z({dynamicSamplingContext:$t(this)})),_metrics_summary:nr(this)},d&&{transaction_info:{source:d}});return Object.keys(this._measurements).length>0&&(tt&&h.log("[Measurements] Adding measurements to transaction",JSON.stringify(this._measurements,void 0,2)),f.measurements=this._measurements),tt&&h.log("[Tracing] Finishing "+this.op+" transaction: "+this._name+"."),f}},tr(e,[{key:"name",get:function(){return this._name},set:function(t){this.setName(t)}},{key:"metadata",get:function(){return v({source:"custom",spanMetadata:{}},this._metadata,this._attributes[ir]&&{source:this._attributes[ir]},this._attributes[ar]&&{sampleRate:this._attributes[ar]})},set:function(t){this._metadata=t}}]),e}(dr);function gr(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._beforeFinishCallbacks);!(i=a()).done;)(0,i.value)(this,r);this.spanRecorder.spans=this.spanRecorder.spans.filter((function(t){if(t.spanContext().spanId===n.spanContext().spanId)return!0;Mt(t).timestamp||(t.setStatus("cancelled"),t.end(r),tt&&h.log("[Tracing] cancelling span since transaction ended early",JSON.stringify(t,void 0,2)));var e=Mt(t),i=e.start_timestamp,a=e.timestamp,o=i&&i=3?this._autoFinishAllowed&&(tt&&h.log("[Tracing] Transaction finished because of no change for 3 heart beats"),this.setStatus("deadline_exceeded"),this._finishReason=_r[0],this.end()):this._pingHeartbeat()}},n._pingHeartbeat=function(){var t=this;tt&&h.log("pinging Heartbeat -> current counter: "+this._heartbeatCounter),setTimeout((function(){t._beat()}),this._heartbeatInterval)},e}(vr);function Sr(t){return(t||ie()).getScope().getTransaction()}var xr=!1;function Tr(){var t=Sr();if(t){var e="internal_error";tt&&h.log("[Tracing] Transaction: "+e+" -> Global error occured"),t.setStatus(e)}}function Er(t,e,n){return fr(e)?void 0!==t.sampled?(t.setAttribute(ar,Number(t.sampled)),t):("function"==typeof e.tracesSampler?(r=e.tracesSampler(n),t.setAttribute(ar,Number(r))):void 0!==n.parentSampled?r=n.parentSampled:void 0!==e.tracesSampleRate?(r=e.tracesSampleRate,t.setAttribute(ar,Number(r))):(r=1,t.setAttribute(ar,r)),wr(r)?r?(t.sampled=Math.random()1)||(tt&&h.warn("[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got "+t+"."),!1)}function kr(){var t=this.getScope().getSpan();return t?{"sentry-trace":Pt(t)}:{}}function Ir(t,e){var n=this.getClient(),r=n&&n.getOptions()||{},i=r.instrumenter||"sentry",a=t.instrumenter||"sentry";i!==a&&(tt&&h.error("A transaction was started with instrumenter=`"+a+"`, but the SDK is configured with the `"+i+"` instrumenter.\nThe transaction will not be sampled. Please use the "+i+" instrumentation to start transactions."),t.sampled=!1);var o=new vr(t,this);return(o=Er(o,r,v({name:t.name,parentSampled:t.parentSampled,transactionContext:t,attributes:v({},t.data,t.attributes)},e))).isRecording()&&o.initSpanRecorder(r._experiments&&r._experiments.maxSpans),n&&n.emit&&n.emit("startTransaction",o),o}function Or(t,e,n,r,i,a,o,s){void 0===s&&(s=!1);var c=t.getClient(),u=c&&c.getOptions()||{},d=new br(e,t,n,r,o,i,s);return(d=Er(d,u,v({name:e.name,parentSampled:e.parentSampled,transactionContext:e,attributes:v({},e.data,e.attributes)},a))).isRecording()&&d.initSpanRecorder(u._experiments&&u._experiments.maxSpans),c&&c.emit&&c.emit("startTransaction",d),d}Tr.tag="sentry_tracingErrorCallback";var Cr,Ar=!1,Rr=o,jr=function(t,e,n){var r,i;return function(a){e.value>=0&&(a||n)&&((i=e.value-(r||0))||void 0===r)&&(r=e.value,e.delta=i,t(e))}},Pr=function(){return Rr.__WEB_VITALS_POLYFILL__?Rr.performance&&(performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]||function(){var t=Rr.performance.timing,e=Rr.performance.navigation.type,n={entryType:"navigation",startTime:0,type:2==e?"back_forward":1===e?"reload":"navigate"};for(var r in t)"navigationStart"!==r&&"toJSON"!==r&&(n[r]=Math.max(t[r]-t.navigationStart,0));return n}()):Rr.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},Nr=function(){var t=Pr();return t&&t.activationStart||0},Dr=function(t,e){var n=Pr(),r="navigate";return n&&(r=Rr.document&&Rr.document.prerendering||Nr()>0?"prerender":n.type.replace(/_/g,"-")),{name:t,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-"+Date.now()+"-"+(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},Mr=function(t,e,n){try{if(PerformanceObserver.supportedEntryTypes.includes(t)){var r=new PerformanceObserver((function(t){e(t.getEntries())}));return r.observe(Object.assign({type:t,buffered:!0},n||{})),r}}catch(t){}},Lr=function(t,e){var n=function n(r){"pagehide"!==r.type&&"hidden"!==Rr.document.visibilityState||(t(r),e&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};Rr.document&&(addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0))},Ur=function(t,e){void 0===e&&(e={});var n,r=Dr("CLS",0),i=0,a=[],o=function(t){t.forEach((function(t){if(!t.hadRecentInput){var e=a[0],o=a[a.length-1];i&&0!==a.length&&t.startTime-o.startTime<1e3&&t.startTime-e.startTime<5e3?(i+=t.value,a.push(t)):(i=t.value,a=[t]),i>r.value&&(r.value=i,r.entries=a,n&&n())}}))},s=Mr("layout-shift",o);if(s){n=jr(t,r,e.reportAllChanges);var c=function(){o(s.takeRecords()),n(!0)};return Lr(c),c}},qr=-1,Fr=function(){return qr<0&&(Rr.document&&Rr.document.visibilityState&&(qr="hidden"!==Rr.document.visibilityState||Rr.document.prerendering?1/0:0),Lr((function(t){var e=t.timeStamp;qr=e}),!0)),{get firstHiddenTime(){return qr}}},Hr=function(t){var e,n=Fr(),r=Dr("FID"),i=function(t){t.startTimee.latency){if(n)n.entries.push(t),n.latency=Math.max(n.latency,t.duration);else{var r={id:t.interactionId,latency:t.duration,entries:[t]};Wr[r.id]=r,Vr.push(r)}Vr.sort((function(t,e){return e.latency-t.latency})),Vr.splice(10).forEach((function(t){delete Wr[t.id]}))}},Kr=function(t,e){e=e||{},$r();var n,r=Dr("INP"),i=function(t){t.forEach((function(t){t.interactionId&&Xr(t),"first-input"===t.entryType&&!Vr.some((function(e){return e.entries.some((function(e){return t.duration===e.duration&&t.startTime===e.startTime}))}))&&Xr(t)}));var e,i=(e=Math.min(Vr.length-1,Math.floor(Gr()/50)),Vr[e]);i&&i.latency!==r.value&&(r.value=i.latency,r.entries=i.entries,n())},a=Mr("event",i,{durationThreshold:e.durationThreshold||40});n=jr(t,r,e.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),Lr((function(){i(a.takeRecords()),r.value<0&&Gr()>0&&(r.value=0,r.entries=[]),n(!0)})))},Qr={},Zr=function(t){var e,n=Fr(),r=Dr("LCP"),i=function(t){var i=t[t.length-1];if(i){var a=Math.max(i.startTime-Nr(),0);aperformance.now())return;n.entries=[t],r(!0)}}))};function ni(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var a=r.value;try{a(e)}catch(e){Ar&&h.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+_t(a)+"\nError:",e)}}}function pi(){return Ur((function(t){fi("cls",{metric:t}),ri=t}),{reportAllChanges:!0})}function li(){return Hr((function(t){fi("fid",{metric:t}),ii=t}))}function hi(){return Zr((function(t){fi("lcp",{metric:t}),ai=t}))}function vi(){return ei((function(t){fi("ttfb",{metric:t}),oi=t}))}function gi(){return Kr((function(t){fi("inp",{metric:t}),si=t}))}function mi(t,e,n,r,i){var a;return void 0===i&&(i=!1),_i(t,e),ui[t]||(a=n(),ui[t]=!0),r&&e({metric:r}),yi(t,e,i?a:void 0)}function _i(t,e){ci[t]=ci[t]||[],ci[t].push(e)}function yi(t,e,n){return function(){n&&n();var r=ci[t];if(r){var i=r.indexOf(e);-1!==i&&r.splice(i,1)}}}var bi=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function Si(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,a=t.port,o=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(a?":"+a:"")+"/"+(r?r+"/":r)+o}function xi(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function Ti(t){var e="string"==typeof t?function(t){var e=bi.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],a=n[2],o=void 0===a?"":a,s=n[3],c=n[4],u=void 0===c?"":c,d="",p=n[5],l=p.split("/");if(l.length>1&&(d=l.slice(0,-1).join("/"),p=l.pop()),p){var h=p.match(/^\d+/);h&&(p=h[0])}return xi({host:s,pass:o,path:d,projectId:p,port:u,protocol:r,publicKey:i})}f((function(){console.error("Invalid Sentry Dsn: "+t)}))}(t):xi(t);if(e&&function(t){if(!i)return!0;var e=t.port,n=t.projectId,r=t.protocol;return!(["protocol","publicKey","host","projectId"].find((function(e){return!t[e]&&(h.error("Invalid Sentry Dsn: "+e+" missing"),!0)}))||(n.match(/^\d+$/)?function(t){return"http"===t||"https"===t}(r)?e&&isNaN(parseInt(e,10))&&(h.error("Invalid Sentry Dsn: Invalid port "+e),1):(h.error("Invalid Sentry Dsn: Invalid protocol "+r),1):(h.error("Invalid Sentry Dsn: Invalid projectId "+n),1)))}(e))return e}function Ei(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return wi(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wi(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function wi(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=0||(i[n]=t[n]);return i}(e,Di);return n&&t.startTimestamp>n&&(t.startTimestamp=n),t.startChild(v({startTimestamp:n},r))}function Ui(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return qi(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?qi(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function qi(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n0?_.join(","):void 0})}return{"sentry-trace":f,baggage:p}}(g,c,s,m,h)}return h}var _=t.fetchData.__span;if(!_)return;var y=r[_];y&&(function(t,e){if(e.response){cr(t,e.response.status);var n=e.response&&e.response.headers&&e.response.headers.get("content-length");if(n){var r=parseInt(n);r>0&&t.setAttribute("http.response_content_length",r)}}else e.error&&t.setStatus("internal_error");t.end()}(y,t),delete r[_])}}(t,c,u,d);if(e){var n=ra(t.fetchData.url),r=n?Pn(n).host:void 0;e.setAttributes({"http.url":n,"server.address":r})}s&&e&&ea(e)})),r&&yn((function(t){var e=function(t,e,n,r){var i,a=t.xhr,o=a&&a[_n];if(fr()&&a&&!a.__sentry_own_request__&&o){var s=e(o.url);if(!t.endTimestamp||!s){var c=Yt(),u=ae(),d=ra(o.url),f=d?Pn(d).host:void 0,p=s?pr({name:o.method+" "+o.url,onlyIfParent:!0,attributes:(i={type:"xhr","http.method":o.method,"http.url":d,url:o.url,"server.address":f},i[sr]="auto.http.browser",i),op:"http.client"}):void 0;p&&(a.__sentry_xhr_span_id__=p.spanContext().spanId,r[a.__sentry_xhr_span_id__]=p);var l=Bt();if(a.setRequestHeader&&n(o.url)&&l){var h=v({},u.getPropagationContext(),c.getPropagationContext()),g=h.traceId,m=h.spanId,_=h.sampled,y=h.dsc;!function(t,e,n){try{t.setRequestHeader("sentry-trace",e),n&&t.setRequestHeader(xt,n)}catch(t){}}(a,p?Pt(p):At(g,m,_),kt(y||(p?$t(p):zt(g,l,c))))}return p}var b=a.__sentry_xhr_span_id__;if(!b)return;var S=r[b];S&&void 0!==o.status_code&&(cr(S,o.status_code),S.end(),delete r[b])}}(t,c,u,d);s&&e&&ea(e)}))}function ea(t){var e=(Mt(t).data||{}).url;if(e&&"string"==typeof e)var n=di("resource",(function(r){r.entries.forEach((function(r){(function(t){return"resource"===t.entryType&&"initiatorType"in t&&"string"==typeof t.nextHopProtocol&&("fetch"===t.initiatorType||"xmlhttprequest"===t.initiatorType)})(r)&&r.name.endsWith(e)&&(function(t){var e=function(t){for(var e,n="unknown",r="unknown",i="",a=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Ki(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ki(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(t);!(e=a()).done;){var o=e.value;if("/"===o){var s=t.split("/");n=s[0],r=s[1];break}if(!isNaN(Number(o))){n="h"===i?"http":i,r=t.split(i)[1];break}i+=o}return i===t&&(n=i),{name:n,version:r}}(t.nextHopProtocol),n=e.name,r=e.version,i=[];return i.push(["network.protocol.version",r],["network.protocol.name",n]),dt?[].concat(i,[["http.request.redirect_start",na(t.redirectStart)],["http.request.fetch_start",na(t.fetchStart)],["http.request.domain_lookup_start",na(t.domainLookupStart)],["http.request.domain_lookup_end",na(t.domainLookupEnd)],["http.request.connect_start",na(t.connectStart)],["http.request.secure_connection_start",na(t.secureConnectionStart)],["http.request.connection_end",na(t.connectEnd)],["http.request.request_start",na(t.requestStart)],["http.request.response_start",na(t.responseStart)],["http.request.response_end",na(t.responseEnd)]]):i}(r).forEach((function(e){return t.setAttribute.apply(t,e)})),setTimeout(n))}))}))}function na(t){return void 0===t&&(t=0),((dt||performance.timeOrigin)+t)/1e3}function ra(t){try{return new URL(t,Rr.location.origin).href}catch(t){return}}var ia=v({},mr,{markBackgroundTransactions:!0,routingInstrumentation:function(t,e,n){if(void 0===e&&(e=!0),void 0===n&&(n=!0),Rr&&Rr.location){var r,i=Rr.location.href;e&&(r=t({name:Rr.location.pathname,startTimestamp:dt?dt/1e3:void 0,op:"pageload",origin:"auto.pageload.browser",metadata:{source:"url"}})),n&&An((function(e){var n=e.to,a=e.from;void 0===a&&i&&-1!==i.indexOf(n)?i=void 0:a!==n&&(i=void 0,r&&(Ar&&h.log("[Tracing] Finishing current transaction with op: "+r.op),r.end()),r=t({name:Rr.location.pathname,op:"navigation",origin:"auto.navigation.browser",metadata:{source:"url"}}))}))}else Ar&&h.warn("Could not initialize routing instrumentation due to invalid location")},startTransactionOnLocationChange:!0,startTransactionOnPageLoad:!0,enableLongTask:!0,enableInp:!1,interactionsSampleRate:1,_experiments:{}},Zi),aa=function(){function t(t){var e;this.name="BrowserTracing",this._hasSetTracePropagationTargets=!1,(e=ne()).__SENTRY__&&(e.__SENTRY__.extensions=e.__SENTRY__.extensions||{},e.__SENTRY__.extensions.startTransaction||(e.__SENTRY__.extensions.startTransaction=Ir),e.__SENTRY__.extensions.traceHeaders||(e.__SENTRY__.extensions.traceHeaders=kr),xr||(xr=!0,Ye(Tr),$e(Tr))),Ar&&(this._hasSetTracePropagationTargets=!(!t||!t.tracePropagationTargets&&!t.tracingOrigins)),this.options=v({},ia,t),void 0!==this.options._experiments.enableLongTask&&(this.options.enableLongTask=this.options._experiments.enableLongTask),t&&!t.tracePropagationTargets&&t.tracingOrigins&&(this.options.tracePropagationTargets=t.tracingOrigins),this._collectWebVitals=Gi(),this._interactionIdToRouteNameMapping={},this.options.enableInp&&function(t,e){if(Bi()&&dt){var n=function(t,e){return n=function(n){var r=n.metric;if(void 0!==r.value){var i=r.entries.find((function(t){return t.duration===r.value&&void 0!==Vi[t.name]})),a=Bt();if(i&&a){var o=Vi[i.name],s=a.getOptions(),c=Hi(dt+i.startTime),u=Hi(r.value),d=void 0!==i.interactionId?t[i.interactionId]:void 0;if(void 0!==d){var f=d.routeName,p=d.parentContext,l=d.activeTransaction,g=d.user,m=d.replayId,_=void 0!==g?g.email||g.id||g.ip_address:void 0,y=void 0!==l?l.getProfileId():void 0,b=new dr({startTimestamp:c,endTimestamp:c+u,op:"ui.interaction."+o,name:j(i.target),attributes:v({release:s.release,environment:s.environment,transaction:f},void 0!==_&&""!==_?{user:_}:{},void 0!==y?{profile_id:y}:{},void 0!==m?{replay_id:m}:{}),exclusiveTime:r.value,measurements:{inp:{value:r.value,unit:"millisecond"}}}),S=function(t,e,n){return!!fr(e)&&(wr(r=void 0!==t&&"function"==typeof e.tracesSampler?e.tracesSampler({transactionContext:t,name:t.name,parentSampled:t.parentSampled,attributes:v({},t.data,t.attributes),location:Rr.location}):void 0!==t&&void 0!==t.sampled?t.sampled:void 0!==e.tracesSampleRate?e.tracesSampleRate:1)?!0===r?n:!1===r?0:r*n:(Ar&&h.warn("[Tracing] Discarding interaction span because of invalid sample rate."),!1));var r}(p,s,e);if(S)if(Math.random() since tab moved to the background, op: "+r),i||t.setStatus(e),t.setTag("visibilitychange","document.hidden"),t.end()}})):Ar&&h.warn("[Tracing] Could not set up background tab detection due to lack of global document")),v.enableInteractions&&this._registerInteractionListener(),this.options.enableInp&&this._registerInpInteractionListener(),ta({traceFetch:d,traceXHR:f,tracePropagationTargets:m,shouldCreateSpanForRequest:p,enableHTTPTimings:l})},e._createRouteTransaction=function(t){var e=this;if(this._getCurrentHub){var n,r=this._getCurrentHub(),i=this.options,a=i.beforeNavigate,o=i.idleTimeout,s=i.finalTimeout,c=i.heartbeatInterval,u="pageload"===t.op;if(u){var d=Ct(u?oa("sentry-trace"):"",u?oa("baggage"):void 0),f=d.traceId,p=d.dsc;n=v({traceId:f,parentSpanId:d.parentSpanId,parentSampled:d.sampled},t,{metadata:v({},t.metadata,{dynamicSamplingContext:p}),trimEnd:!0})}else n=v({trimEnd:!0},t);var l="function"==typeof a?a(n):n,g=void 0===l?v({},n,{sampled:!1}):l;g.metadata=g.name!==n.name?v({},g.metadata,{source:"custom"}):g.metadata,this._latestRoute.name=g.name,this._latestRoute.context=g,!1===g.sampled&&Ar&&h.log("[Tracing] Will not send "+g.op+" transaction because of beforeNavigate."),Ar&&h.log("[Tracing] Starting "+g.op+" transaction on scope");var m=Or(r,g,o,s,!0,{location:Rr.location},c,u);return u&&Rr.document&&(Rr.document.addEventListener("readystatechange",(function(){["interactive","complete"].includes(Rr.document.readyState)&&m.sendAutoFinishSignal()})),["interactive","complete"].includes(Rr.document.readyState)&&m.sendAutoFinishSignal()),m.registerBeforeFinishCallback((function(t){e._collectWebVitals(),function(t){var e=Bi();if(e&&Rr.performance.getEntries&&dt){Ar&&h.log("[Tracing] Adding & adjusting spans using Performance API");var n=Hi(dt),r=e.getEntries(),i=Mt(t),a=i.op,o=i.start_timestamp;if(r.slice(zi).forEach((function(e){var r=Hi(e.startTime),i=Hi(e.duration);if(!("navigation"===t.op&&o&&n+r=o)){var e=$i[t].value,r=n+Hi(e),i=Math.abs(1e3*(r-o)),a=i-e;Ar&&h.log("[Measurements] Normalized "+t+" from "+e+" to "+i+" ("+a+")"),$i[t].value=i}}));var s=$i["mark.fid"];s&&$i.fid&&(Li(t,{description:"first input delay",endTimestamp:s.value+Hi($i.fid.value),op:"ui.action",origin:"auto.ui.browser.metrics",startTimestamp:s.value}),delete $i["mark.fid"]),"fcp"in $i||delete $i.cls,Object.keys($i).forEach((function(t){!function(t,e,n){var r=Sr();r&&r.setMeasurement(t,e,n)}(t,$i[t].value,$i[t].unit)})),function(t){Yi&&(Ar&&h.log("[Measurements] Adding LCP Data"),Yi.element&&t.setTag("lcp.element",j(Yi.element)),Yi.id&&t.setTag("lcp.id",Yi.id),Yi.url&&t.setTag("lcp.url",Yi.url.trim().slice(0,200)),t.setTag("lcp.size",Yi.size)),Ji&&Ji.sources&&(Ar&&h.log("[Measurements] Adding CLS Data"),Ji.sources.forEach((function(e,n){return t.setTag("cls.source."+(n+1),j(e.node))})))}(t)}Yi=void 0,Ji=void 0,$i={}}}(t)})),m}Ar&&h.warn("[Tracing] Did not create "+t.op+" transaction because _getCurrentHub is invalid.")},e._registerInteractionListener=function(){var t,e=this,n=function(){var n,r=e.options,i=r.idleTimeout,a=r.finalTimeout,o=r.heartbeatInterval,s="ui.action.click",c=Sr();if(c&&c.op&&["navigation","pageload"].includes(c.op))Ar&&h.warn("[Tracing] Did not create "+s+" transaction because a pageload or navigation transaction is in progress.");else if(t&&(t.setFinishReason("interactionInterrupted"),t.end(),t=void 0),e._getCurrentHub)if(e._latestRoute.name){var u=e._getCurrentHub(),d=Rr.location,f={name:e._latestRoute.name,op:s,trimEnd:!0,data:(n={},n[ir]=e._latestRoute.context?sa(e._latestRoute.context):"url",n)};t=Or(u,f,i,a,!0,{location:d},o)}else Ar&&h.warn("[Tracing] Did not create "+s+" transaction because _latestRouteName is missing.");else Ar&&h.warn("[Tracing] Did not create "+s+" transaction because _getCurrentHub is invalid.")};["click"].forEach((function(t){Rr.document&&addEventListener(t,n,{once:!1,capture:!0})}))},e._registerInpInteractionListener=function(){var t=this,e=function(e){var n=e.entries,r=Bt(),i=void 0!==r&&void 0!==r.getIntegrationByName?r.getIntegrationByName("Replay"):void 0,a=void 0!==i?i.getReplayId():void 0,o=Sr(),s=Yt(),c=void 0!==s?s.getUser():void 0;n.forEach((function(e){if(function(t){return"duration"in t}(e)){var n=e.interactionId;if(void 0===n)return;var r=t._interactionIdToRouteNameMapping[n],i=e.duration,s=e.startTime,u=Object.keys(t._interactionIdToRouteNameMapping),d=u.length>0?u.reduce((function(e,n){return t._interactionIdToRouteNameMapping[e].durationt._interactionIdToRouteNameMapping[d].duration){var f=t._latestRoute.name,p=t._latestRoute.context;f&&p&&(d&&Object.keys(t._interactionIdToRouteNameMapping).length>=10&&delete t._interactionIdToRouteNameMapping[d],t._interactionIdToRouteNameMapping[n]={routeName:f,duration:i,parentContext:p,user:c,activeTransaction:o,replayId:a,startTime:s})}}}))};di("event",e),di("first-input",e)},t}();function oa(t){var e,n=(e="meta[name="+t+"]",A.document&&A.document.querySelector?A.document.querySelector(e):null);return n?n.getAttribute("content"):void 0}function sa(t){var e=t.attributes&&t.attributes[ir],n=t.data&&t.data[ir],r=t.metadata&&t.metadata.source;return e||n||r}function ca(t){return ca=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ca(t)}function ua(t,e,n){return ua=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}()?Reflect.construct.bind():function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&Xn(i,n.prototype),i},ua.apply(null,arguments)}function da(t){var e="function"==typeof Map?new Map:void 0;return da=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return ua(t,arguments,ca(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),Xn(r,t)},da(t)}var fa=function(t){function e(n,r){var i;return void 0===r&&(r="warn"),(i=t.call(this,n)||this).message=n,i.name=(this instanceof e?this.constructor:void 0).prototype.constructor.name,Object.setPrototypeOf(Wn(i),(this instanceof e?this.constructor:void 0).prototype),i.logLevel=r,i}return Kn(e,t),e}(da(Error)),pa="7";function la(t){var e=t.protocol?t.protocol+":":"",n=t.port?":"+t.port:"";return e+"//"+t.host+n+(t.path?"/"+t.path:"")+"/api/"}function ha(t,e){void 0===e&&(e={});var n="string"==typeof e?e:e.tunnel,r="string"!=typeof e&&e._metadata?e._metadata.sdk:void 0;return n||function(t){return""+la(t)+t.projectId+"/envelope/"}(t)+"?"+function(t,e){return n=v({sentry_key:t.publicKey,sentry_version:pa},e&&{sentry_client:e.name+"/"+e.version}),Object.keys(n).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])})).join("&");var n}(t,r)}function va(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(t);!(e=r()).done;){var i=e.value,a=Object.entries(i.tags),o=a.length>0?"|#"+a.map((function(t){return t[0]+":"+t[1]})).join(","):"";n+=i.name+"@"+i.unit+":"+i.metric+"|"+i.metricType+o+"|T"+i.timestamp+"\n"}return n}(t);return[{type:"statsd",length:e.length},e]}(t);return ki(i,[a])}function ma(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return _a(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_a(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _a(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?" ("+r+" times)":"")),this._outcomes[i]=(this._outcomes[i]||0)+r}},e.captureAggregateMetrics=function(t){tt&&h.log("Flushing aggregated metrics, number of metrics: "+t.length);var e=ga(t,this._dsn,this._options._metadata,this._options.tunnel);this._sendEnvelope(e)},e.on=function(t,e){this._hooks[t]||(this._hooks[t]=[]),this._hooks[t].push(e)},e.emit=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},e._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._transport},e._prepareEvent=function(t,e,n,r){var i=this;void 0===r&&(r=ae());var a=this.getOptions(),s=Object.keys(this._integrations);return!e.integrations&&s.length>0&&(e.integrations=s),this.emit("preprocessEvent",t,e),function(t,e,n,r,i,a){var s=t.normalizeDepth,c=void 0===s?3:s,u=t.normalizeMaxBreadth,d=void 0===u?1e3:u,f=v({},e,{event_id:e.event_id||n.event_id||G(),timestamp:e.timestamp||ct()}),p=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,a=e.maxValueLength,o=void 0===a?250:a;"environment"in t||(t.environment="environment"in e?n:ft),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=D(t.message,o));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=D(s.value,o));var c=t.request;c&&c.url&&(c.url=D(c.url,o))}(f,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(f,p),void 0===e.type&&function(t,e){var n,r=o._sentryDebugIds;if(r){var i=Ut.get(e);i?n=i:(n=new Map,Ut.set(e,n));var a=Object.keys(r).reduce((function(t,i){var a,o=n.get(i);o?a=o:(a=e(i),n.set(i,a));for(var s=a.length-1;s>=0;s--){var c=a[s];if(c.filename){t[c.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=a[t.filename])}))}))}catch(t){}}}(f,t.stackParser);var l=function(t,e){if(!e)return t;var n=t?t.clone():new Kt;return n.update(e),n}(r,n.captureContext);n.mechanism&&K(f,n.mechanism);var h=i&&i.getEventProcessors?i.getEventProcessors():[],g=(Xt||(Xt=new Kt),Xt).getScopeData();a&&Vt(g,a.getScopeData()),l&&Vt(g,l.getScopeData());var m=[].concat(n.attachments||[],g.attachments);return m.length&&(n.attachments=m),Gt(f,g),ot([].concat(h,it(),g.eventProcessors),f,n).then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof c&&c>0?function(t,e,n){if(!t)return null;var r=v({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return v({},t,t.data&&{data:yt(t.data,e,n)})}))},t.user&&{user:yt(t.user,e,n)},t.contexts&&{contexts:yt(t.contexts,e,n)},t.extra&&{extra:yt(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=yt(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){var r=Mt(t).data;return r&&(t.data=yt(r,e,n)),t}))),r}(t,c,d):t}))}(a,t,e,n,this,r).then((function(t){if(null===t)return t;var e=v({},r.getPropagationContext(),n?n.getPropagationContext():void 0);if((!t.contexts||!t.contexts.trace)&&e){var a=e.traceId,o=e.spanId,s=e.parentSpanId,c=e.dsc;t.contexts=v({trace:{trace_id:a,span_id:o,parent_span_id:s}},t.contexts);var u=c||zt(a,i,n);t.sdkProcessingMetadata=v({dynamicSamplingContext:u},t.sdkProcessingMetadata)}return t}))},e._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){if(tt){var e=t;"log"===e.logLevel?h.log(e.message):h.warn(e)}}))},e._processEvent=function(t,e,n){var r=this,i=this.getOptions(),a=i.sampleRate,o=xa(t),s=Sa(t),c=t.type||"error",u="before send for type `"+c+"`";if(s&&"number"==typeof a&&Math.random()>a)return this.recordDroppedEvent("sample_rate","error",t),nt(new fa("Discarding event because it's not included in the random sample (sampling rate = "+a+")","log"));var d="replay_event"===c?"replay":c,f=(t.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(t,e,n,f).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",d,t),new fa("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var a=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;if(Sa(e)&&r)return r(e,n);if(xa(e)&&i){if(e.spans){var a=e.spans.length;e.sdkProcessingMetadata=v({},e.sdkProcessingMetadata,{spanCountBeforeProcessing:a})}return i(e,n)}return e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(k(t))return t.then((function(t){if(!E(t)&&null!==t)throw new fa(n);return t}),(function(t){throw new fa(e+" rejected with "+t)}));if(!E(t)&&null!==t)throw new fa(n);return t}(a,u)})).then((function(i){if(null===i){if(r.recordDroppedEvent("before_send",d,t),o){var a=1+(t.spans||[]).length;r.recordDroppedEvent("before_send","span",a)}throw new fa(u+" returned `null`, will not send event.","log")}var s=n&&n.getSession();if(!o&&s&&r._updateSessionFromEvent(s,i),o){var c=(i.sdkProcessingMetadata&&i.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);c>0&&r.recordDroppedEvent("before_send","span",c)}var f=i.transaction_info;return o&&f&&i.transaction!==t.transaction&&(i.transaction_info=v({},f,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof fa)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new fa("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},e._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},e._sendEnvelope=function(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)return this._transport.send(t).then(null,(function(t){tt&&h.error("Error while sending event:",t)}));tt&&h.error("Transport disabled")},e._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},t}();function Sa(t){return void 0===t.type}function xa(t){return"transaction"===t.type}var Ta=function(t){function e(e){var n;return function(t,e,n,r){void 0===n&&(n=[e]),void 0===r&&(r="npm");var i=t._metadata||{};i.sdk||(i.sdk={name:"sentry.javascript."+e,packages:n.map((function(t){return{name:r+":@sentry/"+t,version:Zt}})),version:Zt}),t._metadata=i}(e,"browser",["browser"],Ee.SENTRY_SDK_SOURCE||"npm"),n=t.call(this,e)||this,e.sendClientReports&&Ee.document&&Ee.document.addEventListener("visibilitychange",(function(){"hidden"===Ee.document.visibilityState&&n._flushOutcomes()})),n}Kn(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=Ze(t,e,n&&n.syntheticException||void 0,r);return K(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),et(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var a=tn(t,e,r&&r.syntheticException||void 0,i);return a.level=n,r&&r.event_id&&(a.event_id=r.event_id),et(a)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,a=v({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:Si(i)}),o=function(t){return[{type:"user_report"},t]}(t);return ki(a,[o])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,ki((n=this._options.tunnel&&Si(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:ct(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(ba);function Ea(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return wa(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wa(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function wa(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){et(t).then((function(){--i||(clearTimeout(a),n(!0))}),r)}))}))}}}(t.bufferSize||Ia));var r={};function i(i){var a=[];if(Ii(i,(function(e,n){var i=ji(n);if(function(t,e,n){return void 0===n&&(n=Date.now()),function(t,e){return t[e]||t.all||0}(t,e)>n}(r,i)){var o=Ca(e,n);t.recordDroppedEvent("ratelimit_backoff",i,o)}else a.push(e)})),0===a.length)return et();var o=ki(i[0],a),s=function(e){Ii(o,(function(n,r){var i=Ca(n,r);t.recordDroppedEvent(e,ji(r),i)}))};return n.add((function(){return e({body:Ci(o,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&tt&&h.warn("Sentry responded with status code "+t.statusCode+" to sent event."),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var a=v({},t),o=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(o)for(var c,u=Ea(o.trim().split(","));!(c=u()).done;){var d=c.value.split(":",5),f=d[0],p=d[1],l=d[4],h=parseInt(f,10),g=1e3*(isNaN(h)?60:h);if(p)for(var m,_=Ea(p.split(";"));!(m=_()).done;){var y=m.value;"metric_bucket"===y&&l&&!l.split(";").includes("custom")||(a[y]=n+g)}else a.all=n+g}else s?a.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?ka:r-e}(s,n):429===r&&(a.all=n+6e4);return a}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof fa)return tt&&h.error("Skipped sending event because buffer is full."),s("queue_overflow"),et();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function Ca(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var Aa=void 0;function Ra(t,e){void 0===e&&(e=function(){if(Aa)return Aa;if(xn(Ee.fetch))return Aa=Ee.fetch.bind(Ee);var t=Ee.document,e=Ee.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return Aa=e.bind(Ee)}());var n=0,r=0;return Oa(t,(function(i){var a=i.body.length;n+=a,r++;var o=v({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,o).then((function(t){return n-=a,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return Aa=void 0,n-=a,r--,nt(t)}}))}var ja="?";function Pa(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var Na=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Da=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ma=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,La=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ua=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,qa=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=vt.test(o)?o.replace(vt,"$1"):o;if(!s.match(/\S*Error: /)){for(var c,u=lt(r);!(c=u()).done;){var d=(0,c.value)(s);if(d){n.push(d);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=Array.from(t);return/sentryWrapped/.test(e[e.length-1].function||"")&&e.pop(),e.reverse(),gt.test(e[e.length-1].function||"")&&(e.pop(),gt.test(e[e.length-1].function||"")&&e.pop()),e.slice(0,50).map((function(t){return v({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=Na.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=Da.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=Fa(e[1]||ja,e[2]),i=r[0];return Pa(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=Ma.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=La.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||ja,a=Fa(i,r);return i=a[0],Pa(r=a[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=Ua.exec(t);return e?Pa(e[2],e[1]||ja,+e[3],e[4]?+e[4]:void 0):void 0}]]),Fa=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:ja,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Ha="Dedupe",Ba=function(){var t;return{name:Ha,setupOnce:function(){},processEvent:function(e){if(e.type)return e;try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!Ja(t,e)&&!!Ya(t,e))))}(t,e)||!!function(t,e){var n=za(e),r=za(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!Ja(t,e)&&!!Ya(t,e)))}(t,e))}(e,t))return null}catch(t){}return t=e}}};function Ya(t,e){var n=$a(t),r=$a(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i>t/4).toString(16)}))}function eo(){return Date.now()/1e3}var no=function(){var t=Qa.performance;if(!t||!t.now)return eo;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/1e3}}(),ro=(function(){var t=Qa.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,a=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function go(t){return t.transaction}var mo=1;function _o(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=yo(t);return lo({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function yo(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function bo(t){var e=jo();if(!e)return{};var n=function(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,a=(n&&n.getUser()||{}).segment,o=lo({environment:r.environment||uo,release:r.release,user_segment:a,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",o),o}(yo(t).trace_id||"",e,Io().getScope()),r=go(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var a=r.metadata,o=a.sampleRate,s=a.source;null!=o&&(n.sample_rate=""+o);var c=yo(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&mo)}(r)),e.emit&&e.emit("createDsc",n),n}var So=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=xo()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=v({},this._tags),e._extra=v({},this._extra),e._contexts=v({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=v({},this._sdkProcessingMetadata),e._propagationContext=v({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&vo(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=v({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=v({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=v({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=v({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=v({},this._tags,r.tags),this._extra=v({},this._extra,r.extra),this._contexts=v({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(Wa(n)){var i=e;this._tags=v({},this._tags,i.tags),this._extra=v({},this._extra,i.extra),this._contexts=v({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=xo(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=v({timestamp:eo()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),function(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,a=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,a=e.contexts,o=e.level,s=e.transactionName,c=lo(n);c&&Object.keys(c).length&&(t.extra=v({},c,t.extra));var u=lo(r);u&&Object.keys(u).length&&(t.tags=v({},u,t.tags));var d=lo(i);d&&Object.keys(d).length&&(t.user=v({},d,t.user));var f=lo(a);f&&Object.keys(f).length&&(t.contexts=v({},f,t.contexts)),o&&(t.level=o),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=v({trace:_o(e)},t.contexts);var n=go(e);if(n){t.sdkProcessingMetadata=v({dynamicSamplingContext:bo(e)},t.sdkProcessingMetadata);var r=yo(n).description;r&&(t.tags=v({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=v({},t.sdkProcessingMetadata,e)}(t,a)}(t,this.getScopeData()),po([].concat(n,Za("globalEventProcessors",(function(){return[]})),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=v({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:to();if(!this._client)return co.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,v({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:to();if(!this._client)return co.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,v({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:to();return this._client?(this._client.captureEvent(t,v({},e,{event_id:n}),this),n):(co.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function xo(){return{traceId:to(),spanId:to().substring(16)}}var To=parseFloat("7.119.1"),Eo=function(){function t(t,e,n,r){var i,a;void 0===r&&(r=To),this._version=r,e?i=e:(i=new So).setClient(t),n?a=n:(a=new So).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=a}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var a=r.value;try{a(e)}catch(e){ro&&co.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+No(a)+"\nError:",e)}}}("console",{args:n,level:t});var i=ao[t];i&&i.apply(Qa.console,n)}}))}))}var qo=["fatal","error","warning","log","info","debug"];function Fo(t){return"warn"===t?"warning":qo.includes(t)?t:"log"}function Ho(t,e){if(!Array.isArray(t))return"";for(var n,r=[],i=0;i(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","import { dynamicRequire, isNodeEnv } from './node';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance(): Performance | undefined {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = (module) => {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: () => {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n","import { isRegExp, isString } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","import type { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*healthcheck.*$/,\n /^.*healthy.*$/,\n /^.*live.*$/,\n /^.*ready.*$/,\n /^.*heartbeat.*$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcess: EventProcessor = (event: Event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n}\n\n/** JSDoc */\nexport function _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nexport function _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n __DEBUG_BUILD__ &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n const { values } = event.exception;\n try {\n const { type = '', value = '' } = (values && values[values.length - 1]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n }\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: { [key: string]: unknown }, name: string, value: unknown): void {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(value: V):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { node } from './node-stack-trace';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = stack.slice(0, STACKTRACE_FRAME_LIMIT);\n\n const lastFrameFunction = localStack[localStack.length - 1].function;\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (lastFrameFunction && /sentryWrapped/.test(lastFrameFunction)) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n const firstFrameFunction = localStack[localStack.length - 1].function;\n // 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)\n if (firstFrameFunction && /captureMessage|captureException/.test(firstFrameFunction)) {\n localStack.pop();\n }\n\n return localStack.map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n const getRandomByte =\n crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","import type { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalSingleton, GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] as const;\nexport type ConsoleLevel = (typeof CONSOLE_LEVELS)[number];\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record<(typeof CONSOLE_LEVELS)[number], LoggerMethod>;\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const originalConsole = GLOBAL_OBJ.console as Console & Record;\n const wrappedLevels: Partial = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] as WrappedFunction).__sentry_original__;\n if (level in originalConsole && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] as LoggerConsoleMethods[typeof level];\n originalConsole[level] = originalWrappedFunc as Console[typeof level];\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level as (typeof CONSOLE_LEVELS)[number]];\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if (__DEBUG_BUILD__) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nlet logger: Logger;\nif (__DEBUG_BUILD__) {\n logger = getGlobalSingleton('logger', makeLogger);\n} else {\n logger = makeLogger();\n}\n\nexport { logger };\n","export const DEFAULT_ENVIRONMENT = 'production';\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States = States.PENDING;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]> = [];\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport {\n arrayify,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isPlainObject,\n isThenable,\n logger,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { updateSession } from './session';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /** Transaction Name */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n this._user = user || {};\n if (this._session) {\n updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as (scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getAttachments(): Attachment[] {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n public applyToEvent(event: Event, hint: EventHint = {}): PromiseLike {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transaction = this._span.transaction;\n if (transaction) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: transaction.getDynamicSamplingContext(),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n __DEBUG_BUILD__ &&\n processor.id &&\n result === null &&\n logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalSingleton, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this._stack = [{ scope }];\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n this.getScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n this.getScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n this.getScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n this.getScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n this.getScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n this.getScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (__DEBUG_BUILD__ && !result) {\n // eslint-disable-next-line no-console\n console.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n public shouldSendDefaultPii(): boolean {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n private _withClient(callback: (client: Client, scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n __DEBUG_BUILD__ && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(carrier) || getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {\n const globalHubTopStack = parent.getStackTop();\n setHubOnCarrier(carrier, new Hub(globalHubTopStack.client, Scope.clone(globalHubTopStack.scope)));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope: Scope) => {\n scope.addEventProcessor((event: SentryEvent) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n}\n","import type {\n Breadcrumb,\n CaptureContext,\n CheckIn,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n MonitorConfig,\n Primitive,\n Severity,\n SeverityLevel,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { logger, uuid4 } from '@sentry/utils';\n\nimport type { Hub } from './hub';\nimport { getCurrentHub } from './hub';\nimport type { Scope } from './scope';\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): ReturnType {\n return getCurrentHub().captureException(exception, { captureContext });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): ReturnType {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event, hint?: EventHint): ReturnType {\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb): ReturnType {\n getCurrentHub().addBreadcrumb(breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): ReturnType {\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): ReturnType {\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): ReturnType {\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): ReturnType {\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): ReturnType {\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const client = getCurrentHub().getClient();\n if (!client) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig);\n }\n\n return uuid4();\n}\n","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\n/** JSDoc */\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nexport class TryCatch implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'TryCatch';\n\n /**\n * @inheritDoc\n */\n public name: string = TryCatch.id;\n\n /** JSDoc */\n private readonly _options: TryCatchOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n public setupOnce(): void {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n}\n\n/** JSDoc */\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: () => void): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type {\n HandlerDataFetch,\n HandlerDataXhr,\n SentryWrappedXMLHttpRequest,\n SentryXhrData,\n WrappedFunction,\n} from '@sentry/types';\n\nimport { isString } from './is';\nimport { CONSOLE_LEVELS, logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v2__';\n\nexport type InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n __DEBUG_BUILD__ && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in WINDOW)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: string): void {\n if (!(level in WINDOW.console)) {\n return;\n }\n\n fill(WINDOW.console, level, function (originalConsoleMethod: () => any): Function {\n return function (...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(WINDOW.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(WINDOW, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(WINDOW, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in WINDOW)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const url = args[1];\n const xhrInfo: SentryXhrData = (this[SENTRY_XHR_DATA_KEY] = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n request_headers: {},\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args: args as [string, string],\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr: this,\n } as HandlerDataXhr);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs as [string, string];\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n if (sentryXhrData && args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in WINDOW)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler: (typeof WINDOW)['onerror'] | null = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n WINDOW.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nlet _oldOnUnhandledRejectionHandler: (typeof WINDOW)['onunhandledrejection'] | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n WINDOW.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n// TODO remove this in v7 (this means the method will no longer be exported, under any name)\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, Severity, SeverityLevel, StackFrame, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n isUnhandledRejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception as DOMError) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n input: string,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\n return event;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Hub, Integration, Primitive, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\n/** JSDoc */\ntype GlobalHandlersIntegrations = Record;\n\n/** Global handlers */\nexport class GlobalHandlers implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GlobalHandlers';\n\n /**\n * @inheritDoc\n */\n public name: string = GlobalHandlers.id;\n\n /** JSDoc */\n private readonly _options: GlobalHandlersIntegrations;\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n private _installFunc: Record void) | undefined> = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n\n /** JSDoc */\n public constructor(options?: GlobalHandlersIntegrations) {\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key as GlobalHandlersIntegrationsOptionKeys];\n if (installFunc && options[key as GlobalHandlersIntegrationsOptionKeys]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key as GlobalHandlersIntegrationsOptionKeys] = undefined;\n }\n }\n }\n}\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler(): void {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler(): void {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e: any) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n __DEBUG_BUILD__ && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions(): [Hub, StackParser, boolean | undefined] {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n .replace(':80', '')\n .replace(':443', '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable max-lines */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event as SentryEvent, HandlerDataFetch, HandlerDataXhr, Integration } from '@sentry/types';\nimport type {\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n addInstrumentationHandler,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n SENTRY_XHR_DATA_KEY,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\ntype HandlerData = Record;\n\n/** JSDoc */\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nexport const BREADCRUMB_INTEGRATION_ID = 'Breadcrumbs';\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nexport class Breadcrumbs implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = BREADCRUMB_INTEGRATION_ID;\n\n /**\n * @inheritDoc\n */\n public name: string = Breadcrumbs.id;\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n public readonly options: Readonly;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n public setupOnce(): void {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n\n /**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\n public addSentryBreadcrumb(event: SentryEvent): void {\n if (this.options.sentry) {\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n }\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerData) => void {\n function _innerDomBreadcrumb(handlerData: HandlerData): void {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n target = _isEvent(event)\n ? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })\n : htmlTreeAsString(event, { keyAttrs, maxStringLength });\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _consoleBreadcrumb(handlerData: HandlerData & { args: unknown[]; level: string }): void {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/6010\n // see: https://github.com/getsentry/sentry-javascript/issues/5916\n for (let i = 0; i < handlerData.args.length; i++) {\n if (handlerData.args[i] === 'ref=Ref<') {\n handlerData.args[i + 1] = 'viewRef';\n break;\n }\n }\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _xhrBreadcrumb(handlerData: HandlerData & HandlerDataXhr): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _fetchBreadcrumb(handlerData: HandlerData & HandlerDataFetch & { response?: Response }): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: handlerData.response && handlerData.response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp,\n endTimestamp,\n };\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _historyBreadcrumb(handlerData: HandlerData & { from: string; to: string }): void {\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return event && !!(event as Record).target;\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, ExtendedError, Integration, StackParser } from '@sentry/types';\nimport { isInstanceOf } from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { exceptionFromError } from '../eventbuilder';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\ninterface LinkedErrorsOptions {\n key: string;\n limit: number;\n}\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: LinkedErrorsOptions['key'];\n\n /**\n * @inheritDoc\n */\n private readonly _limit: LinkedErrorsOptions['limit'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: Partial = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n const client = getCurrentHub().getClient();\n if (!client) {\n return;\n }\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(client.getOptions().stackParser, self._key, self._limit, event, hint) : event;\n });\n }\n}\n\n/**\n * @inheritDoc\n */\nexport function _handler(\n parser: StackParser,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): Event | null {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(parser, limit, hint.originalException as ExtendedError, key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nexport function _walkErrorTree(\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n stack: Exception[] = [],\n): Exception[] {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(parser, error[key]);\n return _walkErrorTree(parser, limit, error[key], key, [exception, ...stack]);\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, Integration } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\n/** HttpContext integration collects information about HTTP request headers */\nexport class HttpContext implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'HttpContext';\n\n /**\n * @inheritDoc\n */\n public name: string = HttpContext.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n if (getCurrentHub().getIntegration(HttpContext)) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n}\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Primitive,\n Span as SpanInterface,\n SpanContext,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[] = [];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * @inheritDoc\n */\n public traceId: string = uuid4();\n\n /**\n * @inheritDoc\n */\n public spanId: string = uuid4().substring(16);\n\n /**\n * @inheritDoc\n */\n public parentSpanId?: string;\n\n /**\n * Internal keeper of the status\n */\n public status?: SpanStatusType | string;\n\n /**\n * @inheritDoc\n */\n public sampled?: boolean;\n\n /**\n * Timestamp in seconds when the span was created.\n */\n public startTimestamp: number = timestampInSeconds();\n\n /**\n * Timestamp in seconds when the span ended.\n */\n public endTimestamp?: number;\n\n /**\n * @inheritDoc\n */\n public op?: string;\n\n /**\n * @inheritDoc\n */\n public description?: string;\n\n /**\n * @inheritDoc\n */\n public tags: { [key: string]: Primitive } = {};\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any } = {};\n\n /**\n * List of spans that were finalized\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n */\n public instrumenter: Instrumenter = 'sentry';\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext?: SpanContext) {\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n if (spanContext.instrumenter) {\n this.instrumenter = spanContext.instrumenter;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startChild(\n spanContext?: Pick>,\n ): Span {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n if (__DEBUG_BUILD__ && childSpan.transaction) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = childSpan.transaction.name || '< unknown name >';\n const idStr = childSpan.transaction.spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };\n logger.log(logMessage);\n }\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public setData(key: string, value: any): this {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setHttpStatus(httpStatus: number): this {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = spanStatusfromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public isSuccess(): boolean {\n return this.status === 'ok';\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): void {\n if (\n __DEBUG_BUILD__ &&\n // Don't call this for transactions\n this.transaction &&\n this.transaction.spanId !== this.spanId\n ) {\n const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n }\n\n /**\n * @inheritDoc\n */\n public toTraceparent(): string {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(spanContext: SpanContext): this {\n this.data = spanContext.data || {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId || this.spanId;\n this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags || {};\n this.traceId = spanContext.traceId || this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getTraceContext(): TraceContext {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public toJSON(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n start_timestamp: number;\n status?: string;\n tags?: { [key: string]: Primitive };\n timestamp?: number;\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function spanStatusfromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n Event,\n Measurements,\n MeasurementUnit,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { Span as SpanClass, SpanRecorder } from './span';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n public metadata: TransactionMetadata;\n\n /**\n * The reference to the current hub.\n */\n public _hub: Hub;\n\n private _name: string;\n\n private _measurements: Measurements = {};\n\n private _contexts: Contexts = {};\n\n private _trimEnd?: boolean;\n\n private _frozenDynamicSamplingContext: Readonly> | undefined = undefined;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this.metadata = {\n source: 'custom',\n ...transactionContext.metadata,\n spanMetadata: {},\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n /** Getter for `name` property */\n public get name(): string {\n return this._name;\n }\n\n /** Setter for `name` property, which also sets `source` as custom */\n public set name(newName: string) {\n this.setName(newName);\n }\n\n /**\n * JSDoc\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.metadata.source = source;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * @inheritDoc\n */\n public setMetadata(newMetadata: Partial): void {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): string | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n __DEBUG_BUILD__ && logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n __DEBUG_BUILD__ && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const metadata = this.metadata;\n\n const transaction: Event = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n dynamicSamplingContext: this.getDynamicSamplingContext(),\n },\n ...(metadata.source && {\n transaction_info: {\n source: metadata.source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n __DEBUG_BUILD__ &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name || '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n */\n public getDynamicSamplingContext(): Readonly> {\n if (this._frozenDynamicSamplingContext) {\n return this._frozenDynamicSamplingContext;\n }\n\n const hub: Hub = this._hub || getCurrentHub();\n const client = hub && hub.getClient();\n\n if (!client) return {};\n\n const { environment, release } = client.getOptions() || {};\n const { publicKey: public_key } = client.getDsn() || {};\n\n const maybeSampleRate = this.metadata.sampleRate;\n const sample_rate = maybeSampleRate !== undefined ? maybeSampleRate.toString() : undefined;\n\n const { segment: user_segment } = hub.getScope().getUser() || {};\n\n const source = this.metadata.source;\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const transaction = source && source !== 'url' ? this.name : undefined;\n\n const dsc = dropUndefinedKeys({\n environment: environment || DEFAULT_ENVIRONMENT,\n release,\n transaction,\n user_segment,\n public_key,\n trace_id: this.traceId,\n sample_rate,\n });\n\n // Uncomment if we want to make DSC immutable\n // this._frozenDynamicSamplingContext = dsc;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n}\n","/* eslint-disable max-lines */\nimport type { TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp?: number) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record = {};\n\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number = 0;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean = false;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean = false;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[] = [];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number] = IDLE_TRANSACTION_FINISH_REASONS[4];\n\n public constructor(\n transactionContext: TransactionContext,\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n __DEBUG_BUILD__ && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._restartIdleTimeout();\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.finish();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public finish(endTimestamp: number = timestampInSeconds()): string | undefined {\n this._finished = true;\n this.activities = {};\n\n if (this.op === 'ui.action.click') {\n this.setTag(FINISH_REASON_TAG, this._finishReason);\n }\n\n if (this.spanRecorder) {\n __DEBUG_BUILD__ &&\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus('cancelled');\n __DEBUG_BUILD__ &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n __DEBUG_BUILD__ &&\n logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n __DEBUG_BUILD__ && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n __DEBUG_BUILD__ && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n const scope = this._idleHub.getScope();\n if (scope.getTransaction() === this) {\n scope.setSpan(undefined);\n }\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n __DEBUG_BUILD__ && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.finish(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n __DEBUG_BUILD__ && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n __DEBUG_BUILD__ && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n __DEBUG_BUILD__ && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n __DEBUG_BUILD__ && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n __DEBUG_BUILD__ && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n __DEBUG_BUILD__ && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n","import type { Options } from '@sentry/types';\n\nimport { getCurrentHub } from '../hub';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getCurrentHub().getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n","import type { Transaction } from '@sentry/types';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * TODO(v7): Reorganize these exports\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n */\nexport { TRACEPARENT_REGEXP, extractTraceparentData } from '@sentry/utils';\n\n/** Grabs active transaction off scope, if any */\nexport function getActiveTransaction(maybeHub?: Hub): T | undefined {\n const hub = maybeHub || getCurrentHub();\n const scope = hub.getScope();\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n","import { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport type { SpanStatusType } from './span';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addInstrumentationHandler('error', errorCallback);\n addInstrumentationHandler('unhandledrejection', errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n __DEBUG_BUILD__ && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n","import type { ClientOptions, CustomSamplingContext, Options, SamplingContext, TransactionContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n const scope = this.getScope();\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': span.toTraceparent(),\n }\n : {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param transaction: The transaction needing a sampling decision\n * @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler`\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample(\n transaction: T,\n options: Pick,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n sampleRate: Number(transaction.sampled),\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setMetadata({\n sampleRate,\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n __DEBUG_BUILD__ && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n const client = this.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n __DEBUG_BUILD__ &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n transactionContext.sampled = false;\n }\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n): IdleTransaction {\n const client = hub.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n","import type { TraceparentData } from '@sentry/types';\n\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent: string): TraceparentData | undefined {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n\n if (!traceparent || !matches) {\n // empty string or no matches is invalid traceparent data\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n","import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n return {\n ...acc,\n ...currBaggageObject,\n };\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext: Partial,\n): string | undefined {\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): number => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport { getActiveTransaction } from '@sentry/core';\nimport type { Measurements } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, htmlTreeAsString, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../types';\nimport { onCLS } from '../web-vitals/getCLS';\nimport { onFID } from '../web-vitals/getFID';\nimport { onLCP } from '../web-vitals/getLCP';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport { observe } from '../web-vitals/lib/observe';\nimport type { NavigatorDeviceMemory, NavigatorNetworkInformation } from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n\n return (): void => {\n if (clsCallback) {\n clsCallback();\n }\n if (lcpCallback) {\n lcpCallback();\n }\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n const entryHandler = (entries: PerformanceEntry[]): void => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n };\n\n observe('longtask', entryHandler);\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n const entryHandler = (entries: PerformanceEventTiming[]): void => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n }\n };\n\n observe('event', entryHandler, { durationThreshold: 0 });\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): ReturnType {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n return onCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): ReturnType {\n return onLCP(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): void {\n onFID(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp: number | undefined;\n let requestStartTimestamp: number | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name as string).replace(WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n __DEBUG_BUILD__ &&\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record, timeOrigin: number): void {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n}\n\nexport interface ResourceEntry extends Record {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceName: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record = {};\n if ('transferSize' in entry) {\n data['http.response_transfer_size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['http.response_content_length'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['http.decoded_response_content_length'] = entry.decodedBodySize;\n }\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (onReport: ReportCallback): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n","/* eslint-disable max-lines */\nimport { getCurrentHub, hasTracingEnabled } from '@sentry/core';\nimport type { DynamicSamplingContext, Span } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n BAGGAGE_HEADER_NAME,\n dynamicSamplingContextToSentryBaggageHeader,\n isInstanceOf,\n SENTRY_XHR_DATA_KEY,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * Default: ['localhost', /^\\//] {@see DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\n/** Data returned from fetch callback */\nexport interface FetchData {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[]; // the arguments passed to the fetch call itself\n fetchData?: {\n method: string;\n url: string;\n // span_id\n __span?: string;\n };\n\n // TODO Should this be unknown instead? If we vendor types, make it a Response\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response?: any;\n error?: unknown;\n\n startTimestamp: number;\n endTimestamp?: number;\n}\n\n/** Data returned from XHR request */\nexport interface XHRData {\n xhr?: {\n [SENTRY_XHR_DATA_KEY]?: {\n method: string;\n url: string;\n status_code: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: Record;\n };\n __sentry_xhr_span_id__?: string;\n setRequestHeader?: (key: string, val: string) => void;\n getRequestHeader?: (key: string) => string;\n __sentry_own_request__?: boolean;\n };\n startTimestamp: number;\n endTimestamp?: number;\n}\n\ntype PolymorphicRequestHeaders =\n | Record\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial): void {\n // eslint-disable-next-line deprecation/deprecation\n const { traceFetch, traceXHR, tracePropagationTargets, tracingOrigins, shouldCreateSpanForRequest } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record = {};\n\n if (traceFetch) {\n addInstrumentationHandler('fetch', (handlerData: FetchData) => {\n fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler('xhr', (handlerData: XHRData) => {\n xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track fetch request spans\n */\nexport function fetchCallback(\n handlerData: FetchData,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): void {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n\n const contentLength: string =\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setData('http.response_content_length', contentLengthNum);\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const { method, url } = handlerData.fetchData;\n const span = currentSpan.startChild({\n data: {\n url,\n type: 'fetch',\n 'http.method': method,\n },\n description: `${method} ${url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n options.headers = addTracingHeadersToFetchRequest(\n request,\n activeTransaction.getDynamicSamplingContext(),\n span,\n options,\n );\n }\n }\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n dynamicSamplingContext: Partial,\n span: Span,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n): PolymorphicRequestHeaders {\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n const sentryTraceHeader = span.toTraceparent();\n\n const headers =\n typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nexport function xhrCallback(\n handlerData: XHRData,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): void {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (\n !hasTracingEnabled() ||\n (xhr && xhr.__sentry_own_request__) ||\n !(xhr && sentryXhrData && shouldCreateSpan(sentryXhrData.url))\n ) {\n return;\n }\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n span.setHttpStatus(sentryXhrData.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...sentryXhrData.data,\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n url: sentryXhrData.url,\n },\n description: `${sentryXhrData.method} ${sentryXhrData.url}`,\n op: 'http.client',\n });\n\n xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url)) {\n try {\n xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n\n const dynamicSamplingContext = activeTransaction.getDynamicSamplingContext();\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n xhr.setRequestHeader(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n","/* eslint-disable max-lines */\nimport type { Hub, IdleTransaction } from '@sentry/core';\nimport {\n addTracingExtensions,\n extractTraceparentData,\n getActiveTransaction,\n startIdleTransaction,\n TRACING_DEFAULTS,\n} from '@sentry/core';\nimport type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';\nimport { baggageHeaderToDynamicSamplingContext, getDomElement, logger } from '@sentry/utils';\n\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport {\n addPerformanceEntries,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nimport { WINDOW } from './types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableLongTask: boolean;\n enableInteractions: boolean;\n onStartRouteTransaction: (t: Transaction | undefined, ctx: TransactionContext, getCurrentHub: () => Hub) => void;\n }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(this: void, context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation(\n this: void,\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nexport class BrowserTracing implements Integration {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string = BROWSER_TRACING_INTEGRATION_ID;\n\n private _getCurrentHub?: () => Hub;\n\n private _latestRouteName?: string;\n private _latestRouteSource?: TransactionSource;\n\n private _collectWebVitals: () => void;\n\n public constructor(_options?: Partial) {\n addTracingExtensions();\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n _experiments,\n } = this.options;\n\n instrumentRouting(\n (context: TransactionContext) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTraceMetaTagValue = isPageloadTransaction ? getMetaContent('sentry-trace') : null;\n const baggageMetaTagValue = isPageloadTransaction ? getMetaContent('baggage') : null;\n\n const traceParentData = sentryTraceMetaTagValue ? extractTraceparentData(sentryTraceMetaTagValue) : undefined;\n const dynamicSamplingContext = baggageMetaTagValue\n ? baggageHeaderToDynamicSamplingContext(baggageMetaTagValue)\n : undefined;\n\n const expandedContext: TransactionContext = {\n ...context,\n ...traceParentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n __DEBUG_BUILD__ &&\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n /** Start listener for interaction transactions */\n private _registerInteractionListener(): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n __DEBUG_BUILD__ && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | null {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : null;\n}\n","import type { Transaction, TransactionContext } from '@sentry/types';\nimport { addInstrumentationHandler, browserPerformanceTimeOrigin, logger } from '@sentry/utils';\n\nimport { WINDOW } from './types';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!WINDOW || !WINDOW.location) {\n __DEBUG_BUILD__ && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = WINDOW.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler('history', ({ to, from }: { to: string; from?: string }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n __DEBUG_BUILD__ && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n","import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n __DEBUG_BUILD__ &&\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n","export const SDK_VERSION = '7.56.0';\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!__DEBUG_BUILD__) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","import type { ConsoleLevel } from './logger';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { Integration, Options } from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\nimport { addGlobalEventProcessor } from './scope';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(integration: Integration, integrationIndex: IntegrationIndex): void {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n __DEBUG_BUILD__ && logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n","import type { ClientOptions, Event, EventHint, StackFrame, StackParser } from '@sentry/types';\nimport { dateTimestampInSeconds, GLOBAL_OBJ, normalize, resolvedSyncPromise, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { Scope } from '../scope';\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n Integration,\n IntegrationClass,\n Outcome,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n SentryError,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport type { IntegrationIndex } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean = false;\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number } = {};\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record = {};\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n __DEBUG_BUILD__ && logger.warn('No DSN provided, client will not do anything.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n __DEBUG_BUILD__ && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n setupIntegration(integration, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n if (this._dsn) {\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n if (this._dsn) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n void this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, _event?: Event): void {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n __DEBUG_BUILD__ && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n\n /** @inheritdoc */\n public on(hook: 'startTransaction' | 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-ignore We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction' | 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n // @ts-ignore we cannot enforce the callback to match the hook\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent(options, event, hint, scope);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (__DEBUG_BUILD__) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n if (this._transport && this._dsn) {\n this.emit('beforeEnvelope', envelope);\n\n return this._transport.send(envelope).then(null, reason => {\n __DEBUG_BUILD__ && logger.error('Error while sending event:', reason);\n });\n } else {\n __DEBUG_BUILD__ && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: string,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n","import type { Scope } from '@sentry/core';\nimport { BaseClient, SDK_VERSION } from '@sentry/core';\nimport type {\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { Breadcrumbs } from './integrations';\nimport { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options & BrowserClientReplayOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint?: EventHint): void {\n // We only want to add the sentry event breadcrumb when the user has the breadcrumb integration installed and\n // activated its `sentry` option.\n // We also do not want to use the `Breadcrumbs` class here directly, because we do not want it to be included in\n // bundles, if it is not used by the SDK.\n // This all sadly is a bit ugly, but we currently don't have a \"pre-send\" hook on the integrations so we do it this\n // way for now.\n const breadcrumbIntegration = this.getIntegrationById(BREADCRUMB_INTEGRATION_ID) as Breadcrumbs | undefined;\n // We check for definedness of `addSentryBreadcrumb` in case users provided their own integration with id\n // \"Breadcrumbs\" that does not have this function.\n if (breadcrumbIntegration && breadcrumbIntegration.addSentryBreadcrumb) {\n breadcrumbIntegration.addSentryBreadcrumb(event);\n }\n\n super.sendEvent(event, hint);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n void this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n __DEBUG_BUILD__ && logger.log('No outcomes to send');\n return;\n }\n\n if (!this._dsn) {\n __DEBUG_BUILD__ && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n void this._sendEnvelope(envelope);\n }\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type { TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, category: string): number {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, category: string, now: number = Date.now()): boolean {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n SentryError,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n __DEBUG_BUILD__ && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n __DEBUG_BUILD__ && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import type { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcessor: EventProcessor = currentEvent => {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n __DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport {\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n Integrations as CoreIntegrations,\n} from '@sentry/core';\nimport type { UserFeedback } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n logger,\n resolvedSyncPromise,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, HttpContext, LinkedErrors, TryCatch } from './integrations';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\nexport const defaultIntegrations = [\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\n];\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nexport function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n __DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n __DEBUG_BUILD__ && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n __DEBUG_BUILD__ && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function flush(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function close(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\nfunction startSessionOnHub(hub: Hub): void {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n __DEBUG_BUILD__ &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getCurrentHub().getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import type { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { CONSOLE_LEVELS, fill, GLOBAL_OBJ, safeJoin, severityLevelFromString } from '@sentry/utils';\n\n/** Send Console API calls as Sentry Events */\nexport class CaptureConsole implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'CaptureConsole';\n\n /**\n * @inheritDoc\n */\n public name: string = CaptureConsole.id;\n\n /**\n * @inheritDoc\n */\n private readonly _levels: readonly string[] = CONSOLE_LEVELS;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { levels?: string[] } = {}) {\n if (options.levels) {\n this._levels = options.levels;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n this._levels.forEach((level: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if (!(level in (GLOBAL_OBJ as any).console)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n fill((GLOBAL_OBJ as any).console, level, (originalConsoleMethod: () => any) => (...args: any[]): void => {\n const hub = getCurrentHub();\n\n if (hub.getIntegration(CaptureConsole)) {\n hub.withScope(scope => {\n scope.setLevel(severityLevelFromString(level));\n scope.setExtra('arguments', args);\n scope.addEventProcessor(event => {\n event.logger = 'console';\n return event;\n });\n\n let message = safeJoin(args, ' ');\n if (level === 'assert') {\n if (args[0] === false) {\n message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n hub.captureMessage(message);\n }\n } else if (level === 'error' && args[0] instanceof Error) {\n hub.captureException(args[0]);\n } else {\n hub.captureMessage(message);\n }\n });\n }\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(GLOBAL_OBJ.console, args);\n }\n });\n });\n }\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["isBrowserBundle","__SENTRY_BROWSER_BUNDLE__","getSDKSource","isNodeEnv","Object","prototype","toString","call","process","dynamicRequire","mod","request","require","WINDOW","getGlobalObject","dateTimestampSource","nowSeconds","Date","now","platformPerformance","module","performance","_","getNodePerformance","timeOrigin","getBrowserPerformance","timestampSource","undefined","dateTimestampInSeconds","bind","timestampInSeconds","browserPerformanceTimeOrigin","threshold","performanceNow","dateNow","timeOriginDelta","Math","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","isGlobalObj","obj","GLOBAL_OBJ","globalThis","window","self","global","getGlobalSingleton","name","creator","gbl","__SENTRY__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","id","loaded","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","defineProperty","enumerable","get","g","this","Function","e","hmd","create","children","set","Error","prop","hasOwnProperty","r","Symbol","toStringTag","value","flarum","core","compat","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","then","isNaN","base","_e","truncate","str","max","length","slice","safeJoin","input","delimiter","Array","isArray","output","i","push","String","join","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","InboundFilters","__initStatic","_proto","_options","__init","setupOnce","addGlobalEventProcessor","getCurrentHub","eventProcess","event","hub","getIntegration","client","getClient","clientOptions","getOptions","options","internalOptions","allowUrls","concat","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","exception","values","type","_isSentryError","message","_ref","_ref$type","_ref$value","oO","_getPossibleEventMessages","_isIgnoredError","transaction","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","frames","stacktrace","frame","filename","_getLastValidUrl","_extends","assign","target","arguments","source","apply","originalFunctionToString","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","nextStr","currentElem","out","height","len","keyAttrs","maxStringLength","_htmlElementAsString","separator","parentNode","reverse","_oO","el","classes","attr","tagName","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","forEach","keyAttrPair","split","allowedAttrs","fill","replacementFactory","original","wrapped","markFunctionWrapped","_Oo","addNonEnumerableProperty","writable","configurable","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","extractExceptionKeysForMessage","maxLength","keys","sort","includedKeys","serialized","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","memoVal","returnValue","_i","_Object$keys","item","FunctionToString","context","_len","args","_key","WEBPACK_ERROR_REGEXP","defaultFunctionName","getFunctionName","fn","uuid4","crypto","msCrypto","randomUUID","replace","getRandomByte","getRandomValues","Uint8Array","random","c","getFirstException","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","err","logger","CONSOLE_LEVELS","enable","disable","States","DEFAULT_ENVIRONMENT","resolvedSyncPromise","SyncPromise","resolve","rejectedSyncPromise","reason","reject","executor","__init2","__init3","__init4","__init5","__init6","_resolve","_reject","_state","PENDING","_handlers","onfulfilled","onrejected","_this","result","_executeHandlers","val","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","state","_value","_this6","cachedHandlers","handler","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","clone","scope","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","addScopeListener","callback","addEventProcessor","setUser","_notifyScopeListeners","getUser","getRequestSession","setRequestSession","requestSession","setTags","tags","setTag","_extends2","setExtras","extras","setExtra","extra","_extends3","setFingerprint","fingerprint","setLevel","level","setTransactionName","setContext","setSpan","span","getSpan","getTransaction","setSession","getSession","update","captureContext","updatedScope","contexts","clear","addBreadcrumb","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","hint","trace","getTraceContext","sdkProcessingMetadata","dynamicSamplingContext","getDynamicSamplingContext","transactionName","_applyFingerprint","breadcrumbs","_notifyEventProcessors","getGlobalEventProcessors","setSDKProcessingMetadata","newData","processors","index","processor","final","maybeArray","API_VERSION","Hub","_version","_stack","bindClient","isOlderThan","version","getStackTop","setupIntegrations","pushScope","getScope","getStack","popScope","pop","withScope","captureException","_lastEventId","syntheticException","_withClient","originalException","captureMessage","captureEvent","lastEventId","_this$getStackTop","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","originalConsole","console","wrappedLevels","originalWrappedFunc","consoleSandbox","emit","configureScope","_this$getStackTop2","run","oldHub","makeMain","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2","_ref2$environment","navigator","startingTime","toJSON","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","_this$getStackTop5","method","sentry","getMainCarrier","extensions","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","ignoreOnError","shouldIgnoreOnError","wrap","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","arg","ex","setTimeout","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","TryCatch","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","originalCallback","originalSend","xhr","wrapOptions","originalFunction","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","isNativeFetch","lastHref","SENTRY_XHR_DATA_KEY","handlers","instrumented","instrument","originalConsoleMethod","triggerHandlers","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","document","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","instrumentDOM","xhrproto","originalOpen","_len3","_key3","xhrInfo","toUpperCase","request_headers","match","__sentry_own_request__","onreadystatechangeHandler","readyState","status_code","endTimestamp","startTimestamp","onreadystatechange","_len4","readyStateArgs","_key4","_len5","setRequestHeaderArgs","_key5","header","sentryXhrData","_len6","_key6","body","instrumentXHR","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","error","chrome","isChromePackagedApp","app","runtime","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","location","href","from","_len7","_key7","historyReplacementFunction","originalHistoryFunction","_len8","_key8","instrumentHistory","_oldOnErrorHandler","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","onunhandledrejection","addInstrumentationHandler","_step","_iterator","_createForOfIteratorHelperLoose","done","resource","debounceTimerID","lastCapturedEvent","debounceDuration","globalListener","isContentEditable","shouldSkipDOMEvent","previous","current","shouldShortcircuitPreviousDebounce","clearTimeout","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","object","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","objName","getPrototypeOf","constructor","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","numAdded","visitable","visitKey","visitValue","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","__serialized__","eventFromPlainObject","synthetic","GlobalHandlers","_installFunc","_installGlobalOnErrorHandler","_installGlobalOnUnhandledRejectionHandler","stackTraceLimit","installFunc","_getHubAndOptions","getHubAndOptions","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","addMechanismAndCapture","_getHubAndOptions2","ev","ev0","ev0s","ev0sf","colno","parseInt","lineno","getLocationHref","in_app","validSeverityLevels","severityLevelFromString","parseUrl","query","fragment","host","path","protocol","search","hash","relative","BREADCRUMB_INTEGRATION_ID","Breadcrumbs","dom","_consoleBreadcrumb","serializeAttribute","_isEvent","category","_xhrBreadcrumb","_fetchBreadcrumb","_historyBreadcrumb","addSentryBreadcrumb","parsedLoc","parsedFrom","parsedTo","LinkedErrors","_limit","limit","parser","linkedErrors","_walkErrorTree","_handler","HttpContext","referrer","headers","Referer","_assertThisInitialized","ReferenceError","_setPrototypeOf","p","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","SpanRecorder","maxlen","_maxlen","spans","spanRecorder","_typeof","iterator","_defineProperties","props","descriptor","prim","toPrimitive","res","TypeError","Transaction","_Span","Constructor","protoProps","transactionContext","_hub","_name","metadata","spanMetadata","_trimEnd","trimEnd","incomingDynamicSamplingContext","_frozenDynamicSamplingContext","_measurements","setName","initSpanRecorder","setMeasurement","unit","setMetadata","newMetadata","finish","sampled","finishedSpans","s","reduce","prev","start_timestamp","transaction_info","measurements","recordDroppedEvent","toContext","updateWithContext","public_key","getDsn","publicKey","maybeSampleRate","sampleRate","sample_rate","user_segment","segment","dsc","trace_id","traceId","setHub","newName","_proto2","Span","spanContext","__init7","spanId","parentSpanId","op","description","instrumenter","substring","startChild","childSpan","setData","setStatus","setHttpStatus","httpStatus","spanStatus","spanStatusfromHttpCode","isSuccess","toTraceparent","sampledString","parent_span_id","span_id","TRACING_DEFAULTS","idleTimeout","finalTimeout","heartbeatInterval","IDLE_TRANSACTION_FINISH_REASONS","IdleTransactionSpanRecorder","_SpanRecorder","_pushActivity","_popActivity","transactionSpanId","IdleTransaction","_Transaction","_idleHub","_idleTimeout","_finalTimeout","_heartbeatInterval","_onScope","_restartIdleTimeout","_finished","_finishReason","activities","_heartbeatCounter","_idleTimeoutCanceledPermanently","_beforeFinishCallbacks","registerBeforeFinishCallback","_pingHeartbeat","cancelIdleTimeout","_temp","restartOnChildSpanChange","_idleTimeoutID","setFinishReason","_beat","heartbeatString","_prevHeartbeatString","_this7","hasTracingEnabled","maybeOptions","enableTracing","getActiveTransaction","maybeHub","errorsInstrumented","errorCallback","activeTransaction","sample","samplingContext","Number","tracesSampler","parentSampled","tracesSampleRate","rate","_startTransaction","_experiments","maxSpans","startIdleTransaction","onScope","tag","TRACEPARENT_REGEXP","RegExp","BAGGAGE_HEADER_NAME","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","dynamicSamplingContextToSentryBaggageHeader","entries","baggageHeader","_ref4","currentIndex","objectKey","objectValue","baggageEntry","encodeURIComponent","newBaggageHeader","objectToBaggageHeader","acc","dscKey","dscValue","baggageHeaderToObject","keyOrValue","decodeURIComponent","trim","_ref3","bindReporter","metric","reportAllChanges","prevValue","delta","forceReport","getNavigationEntry","__WEB_VITALS_POLYFILL__","getEntriesByType","navigation","navigationEntry","entryType","startTime","getNavigationEntryFromPerformanceTiming","getActivationStart","navEntry","activationStart","initMetric","navigationType","prerendering","rating","floor","observe","opts","PerformanceObserver","supportedEntryTypes","po","list","getEntries","buffered","onHidden","cb","once","onHiddenOrPageHide","visibilityState","removeEventListener","firstHiddenTime","getVisibilityWatcher","Infinity","timeStamp","reportedMetricIDs","isMeasurementValue","isFinite","_startChild","ctx","excluded","sourceKeys","indexOf","_objectWithoutPropertiesLoose","_excluded","msToSec","time","getBrowserPerformanceAPI","_lcpEntry","_clsEntry","_performanceCursor","startTrackingWebVitals","onReport","report","visibilityWatcher","handleEntry","handleEntries","mark","entry","processingStart","takeRecords","disconnect","clsCallback","sessionValue","sessionEntries","hadRecentInput","firstSessionEntry","lastSessionEntry","stopListening","onCLS","lcpCallback","lastEntry","capture","onLCP","_addPerformanceNavigationTiming","eventEnd","end","start","DEFAULT_TRACE_PROPAGATION_TARGETS","defaultRequestInstrumentationOptions","traceFetch","traceXHR","tracingOrigins","tracePropagationTargets","DEFAULT_BROWSER_TRACING_OPTIONS","markBackgroundTransactions","routingInstrumentation","customStartTransaction","startTransactionOnPageLoad","startTransactionOnLocationChange","startingUrl","pathname","enableLongTask","BrowserTracing","_collectWebVitals","enableInteractions","_step2","_iterator2","durationThreshold","_getCurrentHub","_this$options","instrumentRouting","shouldCreateSpanForRequest","_createRouteTransaction","onStartRouteTransaction","_registerInteractionListener","_traceFetch$traceXHR$","shouldCreateSpan","shouldAttachHeadersWithTargets","shouldAttachHeaders","__span","contentLength","contentLengthNum","currentScope","currentSpan","_handlerData$fetchDat","sentryBaggageHeader","sentryTraceHeader","newHeaders","append","existingBaggageHeader","baggage","newBaggageHeaders","addTracingHeadersToFetchRequest","fetchCallback","__sentry_xhr_span_id__","setRequestHeader","xhrCallback","instrumentOutgoingRequests","_this$options2","beforeNavigate","isPageloadTransaction","sentryTraceMetaTagValue","getMetaContent","baggageMetaTagValue","traceParentData","traceparent","matches","extractTraceparentData","baggageObject","curr","baggageHeaderToDynamicSamplingContext","expandedContext","modifiedContext","finalContext","_latestRouteName","_latestRouteSource","idleTransaction","responseStartTimestamp","requestStartTimestamp","performanceEntries","requestStart","responseEnd","responseStart","_addRequest","_addNavigationSpans","measureStartTimestamp","measureEndTimestamp","_addMeasureSpans","firstHidden","shouldRecord","resourceName","origin","initiatorType","transferSize","encodedBodySize","decodedBodySize","renderBlockingStatus","_addResourceSpans","connection","effectiveType","rtt","deviceMemory","hardwareConcurrency","_trackNavigator","oldValue","measurementTimestamp","normalizedValue","fidMark","cls","measurementName","element","size","sources","node","_tagMetricInfo","addPerformanceEntries","inflightInteractionTransaction","registerInteractionTransaction","_this3$options","currentTransaction","metaName","selector","metaTag","querySelector","SDK_VERSION","DSN_REGEX","dsnToString","dsn","withPassword","pass","port","projectId","dsnFromComponents","components","makeDsn","exec","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","createEnvelope","items","forEachEnvelopeItem","envelope","envelopeItem","encodeUTF8","textEncoder","TextEncoder","encode","serializeEnvelope","envHeaders","parts","next","itemHeaders","payload","stringifiedPayload","buffers","_step3","totalLength","buf","merged","offset","_iterator3","buffer","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","sdk","_metadataOrEvent$sdk","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","Wrapper","SentryError","_Error","logLevel","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","tunnel","sdkInfo","_metadata","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","_encodedAuth","installedIntegrations","setupIntegration","integrationIndex","debugIdStackParserCache","WeakMap","BaseClient","_dsn","_transport","transport","transportOptions","_integrations","_integrationsInitialized","_numProcessing","_outcomes","_hooks","_process","eventFromException","_captureEvent","promisedEvent","eventFromMessage","_isEnabled","sendSession","getSdkMetadata","getTransport","flush","timeout","_isClientDoneProcessing","clientFinished","transportFlushed","close","enabled","integrations","getIntegrationById","integrationId","addIntegration","sendEvent","newItem","env","eventType","packages","enhanceEventWithSdkInfo","envelopeHeaders","sent_at","createEventEnvelopeHeaders","createEventEnvelope","attachments","promise","_sendEnvelope","sendResponse","createSessionEnvelope","_event","sendClientReports","on","hook","rest","_updateSessionFromEvent","crashed","errored","exceptions","sessionNonTerminal","ticked","interval","clearInterval","_prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","dist","_options$maxValueLeng","maxValueLength","applyClientOptions","integrationNames","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","filenameDebugIdMap","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","b","normalizeEvent","prepareEvent","_processEvent","finalEvent","isTransaction","isTransactionEvent","beforeSendLabel","dataCategory","__sentry__","beforeSend","beforeSendTransaction","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","transactionInfo","send","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","sdkSource","SENTRY_SDK_SOURCE","_flushOutcomes","breadcrumbIntegration","captureUserFeedback","feedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","platform","discarded_events","DEFAULT_RETRY_AFTER","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","remove","task","$","taskProducer","drain","counter","capturedSetTimeout","makePromiseBuffer","bufferSize","rateLimits","filteredEnvelopeItems","limits","envelopeItemDataCategory","all","disabledUntil","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","_limit$split","retryAfter","categories","headerDelay","delay","headerDate","parse","parseRetryAfterHeader","updateRateLimits","__sentry__baseTransport__","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","lastFrameFunction","firstFrameFunction","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","Dedupe","eventProcessor","currentEvent","previousEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","_previousEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","script","async","src","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","injectionPoint","Integrations","CaptureConsole","levels","_levels","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","replaysSessionSampleRate","replaysOnErrorSampleRate","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"forum.tracing.js","mappings":";2BAAA,IAAIA,EAAUC,EAAAA,KAAAA,QACd,SAASC,IACP,aACAC,EAAOC,QAAUF,EAAsB,WACrC,OAAOE,CACT,EAAGD,EAAOC,QAAQC,YAAa,EAAMF,EAAOC,QAAiB,QAAID,EAAOC,QACxE,IAAIA,EAAU,CAAC,EACbE,EAAKC,OAAOC,UACZC,EAASH,EAAGI,eACZC,EAAiBJ,OA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WAC/B4tD,GAAiB,CAAEphD,QAASF,EAAMG,SAAU2E,KAAM49C,OAAOM,YAAY,UAGhEhjD,CACT,EAEA84B,iBAAkB8pB,EAAO9pB,iBACzBmqB,yBAA0BL,EAAOK,yBACjCC,yBAA0BN,EAAOM,yBAEjCppC,aAAc,GAAA/hB,OAAI+hB,GAAc,CAAA8oC,EAAOO,gBAAkB,IAAIZ,KAAkBlnD,OAAOhC,UACtF,EAE4BgU,cAAAA,GAAei0C,iBAAAA,IAE/C9rD,OAAOktD,OAAOM,YAAc,SAACI,QAAQ,IAARA,IAAAA,EAAW,YAEtC,IAAIC,EAAW,CAAC,EAGhB,GAAI75B,IAAK,KAAA85B,EAGoCC,EAFrCz+C,EAAkB,OAAdw+C,EAAG95B,IAAAA,cAAW,EAAX85B,EAAax+C,KAEtB0kB,IAAAA,SAAe1kB,GAAqB,GAAbA,EAAKpJ,OACtB6nD,EAAG,CACTv+C,WAAY,WACZtJ,GAAIoJ,EAAKpJ,OACR0nD,GAAWt+C,EAAKK,WAHnBk+C,EAG6BE,EAGxB/5B,IAAAA,KAAS,6BACZ65B,EAASn+C,MAAQJ,EAAKI,UAEfskB,IAAAA,KAAS3kB,SAAsC,GAA3B2kB,IAAAA,KAAS3kB,QAAQ2+C,SAC9CH,EAAW,CACT3nD,GAAI8tB,IAAAA,KAAS3kB,QAAQ2+C,QAG3B,CAEA,OAAOH,CACT,EAEA75B,IAAAA,aAAiBniB,IAAI,cAAc,WACjCgG,KAAgBmF,QAAQkwC,OAAOM,cACjC","sources":["webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/regeneratorRuntime.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/typeof.js","webpack://@fof/sentry/./node_modules/@babel/runtime/regenerator/index.js","webpack://@fof/sentry/webpack/bootstrap","webpack://@fof/sentry/webpack/runtime/compat get default export","webpack://@fof/sentry/webpack/runtime/define property getters","webpack://@fof/sentry/webpack/runtime/global","webpack://@fof/sentry/webpack/runtime/hasOwnProperty shorthand","webpack://@fof/sentry/webpack/runtime/make namespace object","webpack://@fof/sentry/external root \"flarum.core.compat['forum/app']\"","webpack://@fof/sentry/../../src/debug-build.ts","webpack://@fof/sentry/../../src/worldwide.ts","webpack://@fof/sentry/../../src/logger.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://@fof/sentry/../../src/is.ts","webpack://@fof/sentry/../../src/browser.ts","webpack://@fof/sentry/../../src/string.ts","webpack://@fof/sentry/../../src/object.ts","webpack://@fof/sentry/../../src/misc.ts","webpack://@fof/sentry/../../src/syncpromise.ts","webpack://@fof/sentry/../../src/eventProcessors.ts","webpack://@fof/sentry/../../src/time.ts","webpack://@fof/sentry/../../src/constants.ts","webpack://@fof/sentry/../../src/session.ts","webpack://@fof/sentry/../../src/stacktrace.ts","webpack://@fof/sentry/../../src/normalize.ts","webpack://@fof/sentry/../../src/memo.ts","webpack://@fof/sentry/../../src/baggage.ts","webpack://@fof/sentry/../../src/tracing.ts","webpack://@fof/sentry/../../../src/utils/spanUtils.ts","webpack://@fof/sentry/../../../src/utils/prepareEvent.ts","webpack://@fof/sentry/../../src/exports.ts","webpack://@fof/sentry/../../../src/utils/getRootSpan.ts","webpack://@fof/sentry/../../../src/tracing/dynamicSamplingContext.ts","webpack://@fof/sentry/../../../src/utils/applyScopeDataToEvent.ts","webpack://@fof/sentry/../../src/scope.ts","webpack://@fof/sentry/../../src/version.ts","webpack://@fof/sentry/../../src/hub.ts","webpack://@fof/sentry/../../src/integration.ts","webpack://@fof/sentry/../../../src/integrations/inboundfilters.ts","webpack://@fof/sentry/../../../src/integrations/functiontostring.ts","webpack://@fof/sentry/../../../src/helpers.ts","webpack://@fof/sentry/../../../../src/integrations/trycatch.ts","webpack://@fof/sentry/../../../src/instrument/_handlers.ts","webpack://@fof/sentry/../../../src/instrument/globalError.ts","webpack://@fof/sentry/../../../src/instrument/globalUnhandledRejection.ts","webpack://@fof/sentry/../../../src/eventbuilder.ts","webpack://@fof/sentry/../../../../src/integrations/globalhandlers.ts","webpack://@fof/sentry/../../../src/instrument/console.ts","webpack://@fof/sentry/../../../src/instrument/dom.ts","webpack://@fof/sentry/../../../src/instrument/xhr.ts","webpack://@fof/sentry/../../src/supports.ts","webpack://@fof/sentry/../../../src/instrument/fetch.ts","webpack://@fof/sentry/../../../src/vendor/supportsHistory.ts","webpack://@fof/sentry/../../../src/instrument/history.ts","webpack://@fof/sentry/../../src/severity.ts","webpack://@fof/sentry/../../src/url.ts","webpack://@fof/sentry/../../../../src/integrations/breadcrumbs.ts","webpack://@fof/sentry/../../src/aggregate-errors.ts","webpack://@fof/sentry/../../../../src/integrations/linkederrors.ts","webpack://@fof/sentry/../../../src/metrics/metric-summary.ts","webpack://@fof/sentry/../../../../src/integrations/httpcontext.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/typeof.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/createClass.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/toPrimitive.js","webpack://@fof/sentry/../../src/semanticAttributes.ts","webpack://@fof/sentry/../../../src/tracing/spanstatus.ts","webpack://@fof/sentry/../../../src/tracing/span.ts","webpack://@fof/sentry/../../../src/utils/hasTracingEnabled.ts","webpack://@fof/sentry/../../../src/tracing/trace.ts","webpack://@fof/sentry/../../../src/tracing/transaction.ts","webpack://@fof/sentry/../../../src/tracing/idletransaction.ts","webpack://@fof/sentry/../../../src/tracing/utils.ts","webpack://@fof/sentry/../../../src/tracing/errors.ts","webpack://@fof/sentry/../../../src/tracing/sampling.ts","webpack://@fof/sentry/../../../src/tracing/hubextensions.ts","webpack://@fof/sentry/../../../src/common/debug-build.ts","webpack://@fof/sentry/../../../../../../src/browser/web-vitals/lib/polyfills/interactionCountPolyfill.ts","webpack://@fof/sentry/../../../src/browser/types.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/bindReporter.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getNavigationEntry.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getActivationStart.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/initMetric.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/generateUniqueID.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/observe.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/onHidden.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getCLS.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getVisibilityWatcher.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getFID.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getINP.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getLCP.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/onTTFB.ts","webpack://@fof/sentry/../../../src/browser/instrument.ts","webpack://@fof/sentry/../../src/dsn.ts","webpack://@fof/sentry/../../src/envelope.ts","webpack://@fof/sentry/../../src/span.ts","webpack://@fof/sentry/../../../../src/browser/metrics/utils.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","webpack://@fof/sentry/../../../../src/browser/metrics/index.ts","webpack://@fof/sentry/../../../src/browser/request.ts","webpack://@fof/sentry/../../../src/common/fetch.ts","webpack://@fof/sentry/../../../src/browser/browsertracing.ts","webpack://@fof/sentry/../../../src/browser/router.ts","webpack://@fof/sentry/../../../src/browser/backgroundtab.ts","webpack://@fof/sentry/../../../src/tracing/measurement.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://@fof/sentry/../../src/error.ts","webpack://@fof/sentry/../../src/api.ts","webpack://@fof/sentry/../../../src/metrics/envelope.ts","webpack://@fof/sentry/../../../src/metrics/utils.ts","webpack://@fof/sentry/../../src/baseclient.ts","webpack://@fof/sentry/../../../src/client.ts","webpack://@fof/sentry/../../../src/utils/sdkMetadata.ts","webpack://@fof/sentry/../../src/env.ts","webpack://@fof/sentry/../../../src/userfeedback.ts","webpack://@fof/sentry/../../src/clientreport.ts","webpack://@fof/sentry/../../src/ratelimit.ts","webpack://@fof/sentry/../../../src/transports/base.ts","webpack://@fof/sentry/../../src/promisebuffer.ts","webpack://@fof/sentry/../../../../src/transports/utils.ts","webpack://@fof/sentry/../../../../src/transports/fetch.ts","webpack://@fof/sentry/../../../src/stack-parsers.ts","webpack://@fof/sentry/../../../../src/integrations/dedupe.ts","webpack://@fof/sentry/../../../src/sdk.ts","webpack://@fof/sentry/../../../src/captureconsole.ts","webpack://@fof/sentry/./src/forum/index.js"],"sourcesContent":["var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","export const DEFAULT_ENVIRONMENT = 'production';\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // 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)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n for (const key of Object.keys(currBaggageObject)) {\n acc[key] = currBaggageObject[key];\n }\n return acc;\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext?: Partial,\n): string | undefined {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n","import type { PropagationContext, TraceparentData } from '@sentry/types';\n\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { uuid4 } from './misc';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent?: string): TraceparentData | undefined {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create tracing context from incoming headers.\n *\n * @deprecated Use `propagationContextFromHeaders` instead.\n */\n// TODO(v8): Remove this function\nexport function tracingContextFromHeaders(\n sentryTrace: Parameters[0],\n baggage: Parameters[0],\n): {\n traceparentData: ReturnType;\n dynamicSamplingContext: ReturnType;\n propagationContext: PropagationContext;\n} {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceparentData,\n dynamicSamplingContext: undefined,\n propagationContext: {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n },\n };\n } else {\n return {\n traceparentData,\n dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n propagationContext: {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n },\n };\n }\n}\n\n/**\n * Create a propagation context from incoming headers.\n */\nexport function propagationContextFromHeaders(\n sentryTrace: string | undefined,\n baggage: string | number | boolean | string[] | null | undefined,\n): PropagationContext {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n };\n } else {\n return {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n };\n }\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n traceId: string = uuid4(),\n spanId: string = uuid4().substring(16),\n sampled?: boolean,\n): string {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial | EventHint): hint is Partial {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","export const SDK_VERSION = '7.119.1';\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n IntegrationFnResult,\n Options,\n} from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { addGlobalEventProcessor } from './eventProcessors';\nimport { getClient } from './exports';\nimport { getCurrentHub } from './hub';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Pick): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1) {\n // eslint-disable-next-line deprecation/deprecation\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (client.on && typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (client.addEventProcessor && typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client || !client.addIntegration) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Convert a new integration function to the legacy class syntax.\n * In v8, we can remove this and instead export the integration functions directly.\n *\n * @deprecated This will be removed in v8!\n */\nexport function convertIntegrationFnToClass(\n name: string,\n fn: Fn,\n): IntegrationClass {\n return Object.assign(\n function ConvertedIntegration(...args: Parameters): Integration {\n return fn(...args);\n },\n { id: name },\n ) as unknown as IntegrationClass;\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration(fn: Fn): (...args: Parameters) => IntegrationFnResult {\n return fn;\n}\n","import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/,\n /^Cannot redefine property: googletag$/,\n];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options: Partial = {}) => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\n/**\n * Inbound filters configurable by the user.\n * @deprecated Use `inboundFiltersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const InboundFilters = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n inboundFiltersIntegration,\n) as IntegrationClass void }> & {\n new (\n options?: Partial<{\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n }>,\n ): Integration;\n};\n\nfunction _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if (DEBUG_BUILD && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","import type { Client, Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\nimport { getClient } from '../exports';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nlet originalFunctionToString: () => void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * @deprecated Use `functionToStringIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const FunctionToString = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n functionToStringIntegration,\n) as IntegrationClass void }>;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type FunctionToString = typeof FunctionToString;\n","import type { browserTracingIntegration } from '@sentry-internal/tracing';\nimport { BrowserTracing } from '@sentry-internal/tracing';\nimport { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Integration, Mechanism, WrappedFunction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n *\n * @deprecated This type will be removed in the next major version of the Sentry SDK. `showReportDialog` will still be around, however the `eventId` option will now be required.\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n /** Callback after reportDialog closed */\n onClose?(this: void): void;\n}\n\n/**\n * This is a slim shim of `browserTracingIntegration` for the CDN bundles.\n * Since the actual functional integration uses a different code from `BrowserTracing`,\n * we want to avoid shipping both of them in the CDN bundles, as that would blow up the size.\n * Instead, we provide a functional integration with the same API, but the old implementation.\n * This means that it's not possible to register custom routing instrumentation, but that's OK for now.\n * We also don't expose the utilities for this anyhow in the CDN bundles.\n * For users that need custom routing in CDN bundles, they have to continue using `new BrowserTracing()` until v8.\n */\nexport function bundleBrowserTracingIntegration(\n options: Parameters[0] = {},\n): Integration {\n // Migrate some options from the old integration to the new one\n // eslint-disable-next-line deprecation/deprecation\n const opts: ConstructorParameters[0] = options;\n\n if (typeof options.markBackgroundSpan === 'boolean') {\n opts.markBackgroundTransactions = options.markBackgroundSpan;\n }\n\n if (typeof options.instrumentPageLoad === 'boolean') {\n opts.startTransactionOnPageLoad = options.instrumentPageLoad;\n }\n\n if (typeof options.instrumentNavigation === 'boolean') {\n opts.startTransactionOnLocationChange = options.instrumentNavigation;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return new BrowserTracing(opts);\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'TryCatch';\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\nconst _browserApiErrorsIntegration = ((options: Partial = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n * @deprecated Use `browserApiErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const TryCatch = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n browserApiErrorsIntegration,\n) as IntegrationClass & {\n new (options?: {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n }): Integration;\n};\n\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: VoidFunction,): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n","import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import { getClient } from '@sentry/core';\nimport type {\n Event,\n EventHint,\n Exception,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isParameterizedString,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const client = getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n message: ParameterizedString,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception: Record,\n { isUnhandledRejection }: { isUnhandledRejection?: boolean },\n): string {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n try {\n const prototype: Prototype | null = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { captureEvent, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Primitive,\n StackParser,\n} from '@sentry/types';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record;\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options: Partial = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\n/**\n * Global handlers.\n * @deprecated Use `globalHandlersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const GlobalHandlers = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n globalHandlersIntegration,\n) as IntegrationClass void }> & {\n new (options?: Partial): Integration;\n};\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e as unknown);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = error as any;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n return e.reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n return e.detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable max-lines */\nimport { addBreadcrumb, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event as SentryEvent,\n HandlerDataConsole,\n HandlerDataDom,\n HandlerDataFetch,\n HandlerDataHistory,\n HandlerDataXhr,\n Integration,\n IntegrationClass,\n IntegrationFn,\n} from '@sentry/types';\nimport type {\n Breadcrumb,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n SENTRY_XHR_DATA_KEY,\n addClickKeypressInstrumentationHandler,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n getComponentName,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options: Partial = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry && client.on) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Default Breadcrumbs instrumentations\n *\n * @deprecated Use `breadcrumbsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Breadcrumbs = convertIntegrationFnToClass(INTEGRATION_NAME, breadcrumbsIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (\n options?: Partial<{\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n }>,\n ): Integration;\n};\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client: Client): (handlerData: HandlerDataConsole) => void {\n return function _consoleBreadcrumb(handlerData: HandlerDataConsole): void {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record).target;\n}\n","import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Aggregrate linked errors in an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n","import type { MeasurementUnit, Span } from '@sentry/types';\nimport type { MetricSummary } from '@sentry/types';\nimport type { Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { getActiveSpan } from '../tracing';\nimport type { MetricType } from './types';\n\n/**\n * key: bucketKey\n * value: [exportKey, MetricSummary]\n */\ntype MetricSummaryStorage = Map;\n\nlet SPAN_METRIC_SUMMARY: WeakMap | undefined;\n\nfunction getMetricStorageForSpan(span: Span): MetricSummaryStorage | undefined {\n return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined;\n}\n\n/**\n * Fetches the metric summary if it exists for the passed span\n */\nexport function getMetricSummaryJsonForSpan(span: Span): Record> | undefined {\n const storage = getMetricStorageForSpan(span);\n\n if (!storage) {\n return undefined;\n }\n const output: Record> = {};\n\n for (const [, [exportKey, summary]] of storage) {\n if (!output[exportKey]) {\n output[exportKey] = [];\n }\n\n output[exportKey].push(dropUndefinedKeys(summary));\n }\n\n return output;\n}\n\n/**\n * Updates the metric summary on the currently active span\n */\nexport function updateMetricSummaryOnActiveSpan(\n metricType: MetricType,\n sanitizedName: string,\n value: number,\n unit: MeasurementUnit,\n tags: Record,\n bucketKey: string,\n): void {\n const span = getActiveSpan();\n if (span) {\n const storage = getMetricStorageForSpan(span) || new Map();\n\n const exportKey = `${metricType}:${sanitizedName}@${unit}`;\n const bucketItem = storage.get(bucketKey);\n\n if (bucketItem) {\n const [, summary] = bucketItem;\n storage.set(bucketKey, [\n exportKey,\n {\n min: Math.min(summary.min, value),\n max: Math.max(summary.max, value),\n count: (summary.count += 1),\n sum: (summary.sum += value),\n tags: summary.tags,\n },\n ]);\n } else {\n storage.set(bucketKey, [\n exportKey,\n {\n min: value,\n max: value,\n count: 1,\n sum: value,\n tags,\n },\n ]);\n }\n\n if (!SPAN_METRIC_SUMMARY) {\n SPAN_METRIC_SUMMARY = new WeakMap();\n }\n\n SPAN_METRIC_SUMMARY.set(span, storage);\n }\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'HttpContext';\n\nconst _httpContextIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const httpContextIntegration = defineIntegration(_httpContextIntegration);\n\n/**\n * HttpContext integration collects information about HTTP request headers.\n * @deprecated Use `httpContextIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const HttpContext = convertIntegrationFnToClass(INTEGRATION_NAME, httpContextIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event) => void }\n>;\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/**\n * The id of the profile that this span occured in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id';\n","import type { Span } from '@sentry/types';\n\n/** The status of an Span.\n *\n * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type\n */\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function getSpanStatusFromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @deprecated Use {@link spanStatusFromHttpCode} instead.\n * This export will be removed in v8 as the signature contains a typo.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport const spanStatusfromHttpCode = getSpanStatusFromHttpCode;\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nexport function setHttpStatus(span: Span, httpStatus: number): void {\n // TODO (v8): Remove these calls\n // Relay does not require us to send the status code as a tag\n // For now, just because users might expect it to land as a tag we keep sending it.\n // Same with data.\n // In v8, we replace both, simply with\n // span.setAttribute('http.response.status_code', httpStatus);\n\n // eslint-disable-next-line deprecation/deprecation\n span.setTag('http.status_code', String(httpStatus));\n // eslint-disable-next-line deprecation/deprecation\n span.setData('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Measurements,\n Primitive,\n Span as SpanInterface,\n SpanAttributeValue,\n SpanAttributes,\n SpanContext,\n SpanContextData,\n SpanJSON,\n SpanOrigin,\n SpanTimeInput,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport {\n SEMANTIC_ATTRIBUTE_PROFILE_ID,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n} from '../semanticAttributes';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport {\n TRACE_FLAG_NONE,\n TRACE_FLAG_SAMPLED,\n spanTimeInputToSeconds,\n spanToJSON,\n spanToTraceContext,\n spanToTraceHeader,\n} from '../utils/spanUtils';\nimport type { SpanStatusType } from './spanstatus';\nimport { setHttpStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n this.spans = [];\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n // eslint-disable-next-line deprecation/deprecation\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * Tags for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public tags: { [key: string]: Primitive };\n\n /**\n * Data for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any };\n\n /**\n * List of spans that were finalized\n *\n * @deprecated This property will no longer be public. Span recording will be handled internally.\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n * @deprecated Use top level `Sentry.getRootSpan()` instead\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n *\n * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class.\n * the instrumenter can only be sentry or otel so we can check the span instance\n * to verify which one it is and remove this field entirely.\n *\n * @deprecated This field will be removed.\n */\n public instrumenter: Instrumenter;\n\n protected _traceId: string;\n protected _spanId: string;\n protected _parentSpanId?: string | undefined;\n protected _sampled: boolean | undefined;\n protected _name?: string | undefined;\n protected _attributes: SpanAttributes;\n /** Epoch timestamp in seconds when the span started. */\n protected _startTime: number;\n /** Epoch timestamp in seconds when the span ended. */\n protected _endTime?: number | undefined;\n /** Internal keeper of the status */\n protected _status?: SpanStatusType | string | undefined;\n protected _exclusiveTime?: number;\n\n protected _measurements: Measurements;\n\n private _logMessage?: string;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext: SpanContext = {}) {\n this._traceId = spanContext.traceId || uuid4();\n this._spanId = spanContext.spanId || uuid4().substring(16);\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags ? { ...spanContext.tags } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data ? { ...spanContext.data } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.instrumenter = spanContext.instrumenter || 'sentry';\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n\n if (spanContext.parentSpanId) {\n this._parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this._sampled = spanContext.sampled;\n }\n if (spanContext.status) {\n this._status = spanContext.status;\n }\n if (spanContext.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n if (spanContext.exclusiveTime !== undefined) {\n this._exclusiveTime = spanContext.exclusiveTime;\n }\n this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {};\n }\n\n // This rule conflicts with another eslint rule :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * An alias for `description` of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name || '';\n }\n\n /**\n * Update the name of the span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set name(name: string) {\n this.updateName(name);\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get description(): string | undefined {\n return this._name;\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set description(description: string | undefined) {\n this._name = description;\n }\n\n /**\n * The ID of the trace.\n * @deprecated Use `spanContext().traceId` instead.\n */\n public get traceId(): string {\n return this._traceId;\n }\n\n /**\n * The ID of the trace.\n * @deprecated You cannot update the traceId of a span after span creation.\n */\n public set traceId(traceId: string) {\n this._traceId = traceId;\n }\n\n /**\n * The ID of the span.\n * @deprecated Use `spanContext().spanId` instead.\n */\n public get spanId(): string {\n return this._spanId;\n }\n\n /**\n * The ID of the span.\n * @deprecated You cannot update the spanId of a span after span creation.\n */\n public set spanId(spanId: string) {\n this._spanId = spanId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `startSpan` functions instead.\n */\n public set parentSpanId(string) {\n this._parentSpanId = string;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).parent_span_id` instead.\n */\n public get parentSpanId(): string | undefined {\n return this._parentSpanId;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated Use `isRecording()` instead.\n */\n public get sampled(): boolean | undefined {\n return this._sampled;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated You cannot update the sampling decision of a span after span creation.\n */\n public set sampled(sampled: boolean | undefined) {\n this._sampled = sampled;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public get attributes(): SpanAttributes {\n return this._attributes;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `setAttributes()` instead.\n */\n public set attributes(attributes: SpanAttributes) {\n this._attributes = attributes;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get startTimestamp(): number {\n return this._startTime;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated In v8, you will not be able to update the span start time after creation.\n */\n public set startTimestamp(startTime: number) {\n this._startTime = startTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get endTimestamp(): number | undefined {\n return this._endTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Set the end time via `span.end()` instead.\n */\n public set endTimestamp(endTime: number | undefined) {\n this._endTime = endTime;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `spanToJSON().status` instead to get the status.\n */\n public get status(): SpanStatusType | string | undefined {\n return this._status;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `.setStatus()` instead to set or update the status.\n */\n public set status(status: SpanStatusType | string | undefined) {\n this._status = status;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `spanToJSON().op` to read the op instead.\n */\n public get op(): string | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op')\n * to update the span instead.\n */\n public set op(op: string | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op);\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `spanToJSON().origin` to read the origin instead.\n */\n public get origin(): SpanOrigin | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined;\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `startSpan()` functions to set the origin instead.\n */\n public set origin(origin: SpanOrigin | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /** @inheritdoc */\n public spanContext(): SpanContextData {\n const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n return {\n spanId,\n traceId,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n };\n }\n\n /**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * Also the `sampled` decision will be inherited.\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startChild(\n spanContext?: Pick>,\n ): SpanInterface {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this._spanId,\n sampled: this._sampled,\n traceId: this._traceId,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder = this.spanRecorder;\n // eslint-disable-next-line deprecation/deprecation\n if (childSpan.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder.add(childSpan);\n }\n\n const rootSpan = getRootSpan(this);\n // TODO: still set span.transaction here until we have a more permanent solution\n // Probably similarly to the weakmap we hold in node-experimental\n // eslint-disable-next-line deprecation/deprecation\n childSpan.transaction = rootSpan as Transaction;\n\n if (DEBUG_BUILD && rootSpan) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = spanToJSON(childSpan).description || '< unknown name >';\n const idStr = rootSpan.spanContext().spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n logger.log(logMessage);\n this._logMessage = logMessage;\n }\n\n return childSpan;\n }\n\n /**\n * Sets the tag attribute on the current span.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key Tag key\n * @param value Tag value\n * @deprecated Use `setAttribute()` instead.\n */\n public setTag(key: string, value: Primitive): this {\n // eslint-disable-next-line deprecation/deprecation\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * Sets the data attribute on the current span\n * @param key Data key\n * @param value Data value\n * @deprecated Use `setAttribute()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setData(key: string, value: any): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /** @inheritdoc */\n public setAttribute(key: string, value: SpanAttributeValue | undefined): void {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n } else {\n this._attributes[key] = value;\n }\n }\n\n /** @inheritdoc */\n public setAttributes(attributes: SpanAttributes): void {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top-level `setHttpStatus()` instead.\n */\n public setHttpStatus(httpStatus: number): this {\n setHttpStatus(this, httpStatus);\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @deprecated Use `.updateName()` instead.\n */\n public setName(name: string): void {\n this.updateName(name);\n }\n\n /**\n * @inheritDoc\n */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).status === 'ok'` instead.\n */\n public isSuccess(): boolean {\n return this._status === 'ok';\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `.end()` instead.\n */\n public finish(endTimestamp?: number): void {\n return this.end(endTimestamp);\n }\n\n /** @inheritdoc */\n public end(endTimestamp?: SpanTimeInput): void {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n const rootSpan = getRootSpan(this);\n if (\n DEBUG_BUILD &&\n // Don't call this for transactions\n rootSpan &&\n rootSpan.spanContext().spanId !== this._spanId\n ) {\n const logMessage = this._logMessage;\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public toTraceparent(): string {\n return spanToTraceHeader(this);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON()` or access the fields directly instead.\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n endTimestamp: this._endTime,\n // eslint-disable-next-line deprecation/deprecation\n op: this.op,\n parentSpanId: this._parentSpanId,\n sampled: this._sampled,\n spanId: this._spanId,\n startTimestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n traceId: this._traceId,\n });\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Update the fields directly instead.\n */\n public updateWithContext(spanContext: SpanContext): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data || {};\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n this._endTime = spanContext.endTimestamp;\n // eslint-disable-next-line deprecation/deprecation\n this.op = spanContext.op;\n this._parentSpanId = spanContext.parentSpanId;\n this._sampled = spanContext.sampled;\n this._spanId = spanContext.spanId || this._spanId;\n this._startTime = spanContext.startTimestamp || this._startTime;\n this._status = spanContext.status;\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags || {};\n this._traceId = spanContext.traceId || this._traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceContext()` util function instead.\n */\n public getTraceContext(): TraceContext {\n return spanToTraceContext(this);\n }\n\n /**\n * Get JSON representation of this span.\n *\n * @hidden\n * @internal This method is purely for internal purposes and should not be used outside\n * of SDK code. If you need to get a JSON representation of a span,\n * use `spanToJSON(span)` instead.\n */\n public getSpanJSON(): SpanJSON {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined,\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n exclusive_time: this._exclusiveTime,\n measurements: Object.keys(this._measurements).length > 0 ? this._measurements : undefined,\n });\n }\n\n /** @inheritdoc */\n public isRecording(): boolean {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * Convert the object to JSON.\n * @deprecated Use `spanToJSON(span)` instead.\n */\n public toJSON(): SpanJSON {\n return this.getSpanJSON();\n }\n\n /**\n * Get the merged data for this span.\n * For now, this combines `data` and `attributes` together,\n * until eventually we can ingest `attributes` directly.\n */\n private _getData():\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n }\n | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const { data, _attributes: attributes } = this;\n\n const hasData = Object.keys(data).length > 0;\n const hasAttributes = Object.keys(attributes).length > 0;\n\n if (!hasData && !hasAttributes) {\n return undefined;\n }\n\n if (hasData && hasAttributes) {\n return {\n ...data,\n ...attributes,\n };\n }\n\n return hasData ? data : attributes;\n }\n}\n","import type { Options } from '@sentry/types';\n\nimport { getClient } from '../exports';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n","import type { Scope, Span, SpanTimeInput, StartSpanOptions, TransactionContext } from '@sentry/types';\n\nimport { addNonEnumerableProperty, dropUndefinedKeys, logger, tracingContextFromHeaders } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '.';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getCurrentScope, withScope } from '../exports';\nimport type { Hub } from '../hub';\nimport { runWithAsyncContext } from '../hub';\nimport { getIsolationScope } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport type { Scope as ScopeClass } from '../scope';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n *\n * This function is meant to be used internally and may break at any time. Use at your own risk.\n *\n * @internal\n * @private\n *\n * @deprecated Use `startSpan` instead.\n */\nexport function trace(\n context: TransactionContext,\n callback: (span?: Span) => T,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onError: (error: unknown, span?: Span) => void = () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n afterFinish: () => void = () => {},\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const scope = getCurrentScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const spanContext = normalizeContext(context);\n const activeSpan = createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: false,\n scope,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n error => {\n activeSpan && activeSpan.setStatus('internal_error');\n onError(error, activeSpan);\n },\n () => {\n activeSpan && activeSpan.end();\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(parentSpan);\n afterFinish();\n },\n );\n}\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpan(context: StartSpanOptions, callback: (span: Span | undefined) => T): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet\n if (activeSpan) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n () => activeSpan && activeSpan.end(),\n );\n });\n });\n}\n\n/**\n * @deprecated Use {@link startSpan} instead.\n */\nexport const startActiveSpan = startSpan;\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. You'll have to call `span.end()` manually.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpanManual(\n context: StartSpanOptions,\n callback: (span: Span | undefined, finish: () => void) => T,\n): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n function finishAndSetSpan(): void {\n activeSpan && activeSpan.end();\n }\n\n return handleCallbackErrors(\n () => callback(activeSpan, finishAndSetSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n if (activeSpan && activeSpan.isRecording()) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startInactiveSpan(context: StartSpanOptions): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const spanContext = normalizeContext(context);\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const parentSpan = context.scope\n ? // eslint-disable-next-line deprecation/deprecation\n context.scope.getSpan()\n : getActiveSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return undefined;\n }\n\n const scope = context.scope || getCurrentScope();\n\n // Even though we don't actually want to make this span active on the current scope,\n // we need to make it active on a temporary scope that we use for event processing\n // as otherwise, it won't pick the correct span for the event when processing it\n const temporaryScope = (scope as ScopeClass).clone();\n\n return createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope: temporaryScope,\n });\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentScope().getSpan();\n}\n\ninterface ContinueTrace {\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers,\n * or in the browser from `` and `` HTML tags.\n *\n * @deprecated Use the version of this function taking a callback as second parameter instead:\n *\n * ```\n * Sentry.continueTrace(sentryTrace: '...', baggage: '...' }, () => {\n * // ...\n * })\n * ```\n *\n */\n ({\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n }): Partial;\n\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from ``\n * and `` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n *\n * Deprecation notice: In the next major version of the SDK the provided callback will not receive a transaction\n * context argument.\n */\n (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n // TODO(v8): Remove parameter from this callback.\n callback: (transactionContext: Partial) => V,\n ): V;\n}\n\nexport const continueTrace: ContinueTrace = (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n callback?: (transactionContext: Partial) => V,\n): V | Partial => {\n // TODO(v8): Change this function so it doesn't do anything besides setting the propagation context on the current scope:\n /*\n return withScope((scope) => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n return callback();\n })\n */\n\n const currentScope = getCurrentScope();\n\n // eslint-disable-next-line deprecation/deprecation\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n currentScope.setPropagationContext(propagationContext);\n\n if (DEBUG_BUILD && traceparentData) {\n logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`);\n }\n\n const transactionContext: Partial = {\n ...traceparentData,\n metadata: dropUndefinedKeys({\n dynamicSamplingContext,\n }),\n };\n\n if (!callback) {\n return transactionContext;\n }\n\n return runWithAsyncContext(() => {\n return callback(transactionContext);\n });\n};\n\nfunction createChildSpanOrTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n {\n parentSpan,\n spanContext,\n forceTransaction,\n scope,\n }: {\n parentSpan: Span | undefined;\n spanContext: TransactionContext;\n forceTransaction?: boolean;\n scope: Scope;\n },\n): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const isolationScope = getIsolationScope();\n\n let span: Span | undefined;\n if (parentSpan && !forceTransaction) {\n // eslint-disable-next-line deprecation/deprecation\n span = parentSpan.startChild(spanContext);\n } else if (parentSpan) {\n // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n const sampled = spanIsSampled(parentSpan);\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n } else {\n const { traceId, dsc, parentSpanId, sampled } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n }\n\n // We always set this as active span on the scope\n // In the case of this being an inactive span, we ensure to pass a detached scope in here in the first place\n // But by having this here, we can ensure that the lookup through `getCapturedScopesOnSpan` results in the correct scope & span combo\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to TransactionContext.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n *\n * Eventually the StartSpanOptions will be more aligned with OpenTelemetry.\n */\nfunction normalizeContext(context: StartSpanOptions): TransactionContext {\n if (context.startTime) {\n const ctx: TransactionContext & { startTime?: SpanTimeInput } = { ...context };\n ctx.startTimestamp = spanTimeInputToSeconds(context.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return context;\n}\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\ntype SpanWithScopes = Span & {\n [SCOPE_ON_START_SPAN_FIELD]?: Scope;\n [ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: Scope;\n};\n\nfunction setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n */\nexport function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {\n return {\n scope: (span as SpanWithScopes)[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: (span as SpanWithScopes)[ISOLATION_SCOPE_ON_START_SPAN_FIELD],\n };\n}\n","import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n MeasurementUnit,\n SpanTimeInput,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionEvent,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes';\nimport { spanTimeInputToSeconds, spanToJSON, spanToTraceContext } from '../utils/spanUtils';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { Span as SpanClass, SpanRecorder } from './span';\nimport { getCapturedScopesOnSpan } from './trace';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n /**\n * The reference to the current hub.\n */\n // eslint-disable-next-line deprecation/deprecation\n public _hub: Hub;\n\n protected _name: string;\n\n private _contexts: Contexts;\n\n private _trimEnd?: boolean | undefined;\n\n // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility.\n private _frozenDynamicSamplingContext: Readonly> | undefined;\n\n private _metadata: Partial;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n *\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n // eslint-disable-next-line deprecation/deprecation\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n this._contexts = {};\n\n // eslint-disable-next-line deprecation/deprecation\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this._metadata = {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.metadata,\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n // TODO (v8): Replace this with another way to set the root span\n // eslint-disable-next-line deprecation/deprecation\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n // This sadly conflicts with the getter/setter ordering :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * Getter for `name` property.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name;\n }\n\n /**\n * Setter for `name` property, which also sets `source` as custom.\n * @deprecated Use `updateName()` and `setMetadata()` instead.\n */\n public set name(newName: string) {\n // eslint-disable-next-line deprecation/deprecation\n this.setName(newName);\n }\n\n /**\n * Get the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public get metadata(): TransactionMetadata {\n // We merge attributes in for backwards compatibility\n return {\n // Defaults\n // eslint-disable-next-line deprecation/deprecation\n source: 'custom',\n spanMetadata: {},\n\n // Legacy metadata\n ...this._metadata,\n\n // From attributes\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && {\n source: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] as TransactionMetadata['source'],\n }),\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && {\n sampleRate: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] as TransactionMetadata['sampleRate'],\n }),\n };\n }\n\n /**\n * Update the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public set metadata(metadata: TransactionMetadata) {\n this._metadata = metadata;\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /**\n * Setter for `name` property, which also sets `source` on the metadata.\n *\n * @deprecated Use `.updateName()` and `.setAttribute()` instead.\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n\n /** @inheritdoc */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Set the context of a transaction event.\n * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction.\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top-level `setMeasurement()` instead.\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * Store metadata on this transaction.\n * @deprecated Use attributes or store data on the scope instead.\n */\n public setMetadata(newMetadata: Partial): void {\n this._metadata = { ...this._metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const timestampInS = spanTimeInputToSeconds(endTimestamp);\n const transaction = this._finishTransaction(timestampInS);\n if (!transaction) {\n return undefined;\n }\n // eslint-disable-next-line deprecation/deprecation\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n // eslint-disable-next-line deprecation/deprecation\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this._name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n // eslint-disable-next-line deprecation/deprecation\n super.updateWithContext(transactionContext);\n\n this._name = transactionContext.name || '';\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n *\n * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead.\n */\n public getDynamicSamplingContext(): Readonly> {\n return getDynamicSamplingContextFromSpan(this);\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n // eslint-disable-next-line deprecation/deprecation\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n\n /**\n * Get the profile id of the transaction.\n */\n public getProfileId(): string | undefined {\n if (this._contexts !== undefined && this._contexts['profile'] !== undefined) {\n return this._contexts['profile'].profile_id as string;\n }\n return undefined;\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n protected _finishTransaction(endTimestamp?: number): TransactionEvent | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this._endTime !== undefined) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && logger.warn('Transaction has no name, falling back to ``.');\n this._name = '';\n }\n\n // just sets the end timestamp\n super.end(endTimestamp);\n\n // eslint-disable-next-line deprecation/deprecation\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this._sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n DEBUG_BUILD && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const finishedSpans = this.spanRecorder\n ? // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans.filter(span => span !== this && spanToJSON(span).timestamp)\n : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n const endTimes = finishedSpans.map(span => spanToJSON(span).timestamp).filter(Boolean) as number[];\n this._endTime = endTimes.reduce((prev, current) => {\n return prev > current ? prev : current;\n });\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n // eslint-disable-next-line deprecation/deprecation\n const { metadata } = this;\n // eslint-disable-next-line deprecation/deprecation\n const { source } = metadata;\n\n const transaction: TransactionEvent = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: spanToTraceContext(this),\n },\n // TODO: Pass spans serialized via `spanToJSON()` here instead in v8.\n spans: finishedSpans,\n start_timestamp: this._startTime,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n capturedSpanScope,\n capturedSpanIsolationScope,\n ...dropUndefinedKeys({\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n }),\n },\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n DEBUG_BUILD && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`);\n\n return transaction;\n }\n}\n","/* eslint-disable max-lines */\nimport type { SpanTimeInput, TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanContext().spanId !== this.transactionSpanId) {\n // We patch span.end() to pop an activity after setting an endTimestamp.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalEnd = span.end;\n span.end = (...rest: unknown[]) => {\n this._popActivity(span.spanContext().spanId);\n return originalEnd.apply(span, rest);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (spanToJSON(span).timestamp === undefined) {\n this._pushActivity(span.spanContext().spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record;\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number];\n\n private _autoFinishAllowed: boolean;\n\n /**\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n public constructor(\n transactionContext: TransactionContext,\n // eslint-disable-next-line deprecation/deprecation\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n /**\n * When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval`\n * option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option)\n * will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is\n * reached, no matter what this option is configured to.\n *\n * Defaults to `false`.\n */\n delayAutoFinishUntilSignal: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n this.activities = {};\n this._heartbeatCounter = 0;\n this._finished = false;\n this._idleTimeoutCanceledPermanently = false;\n this._beforeFinishCallbacks = [];\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];\n this._autoFinishAllowed = !delayAutoFinishUntilSignal;\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n DEBUG_BUILD && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`);\n // eslint-disable-next-line deprecation/deprecation\n _idleHub.getScope().setSpan(this);\n }\n\n if (!delayAutoFinishUntilSignal) {\n this._restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.end();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const endTimestampInS = spanTimeInputToSeconds(endTimestamp);\n\n this._finished = true;\n this.activities = {};\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.op === 'ui.action.click') {\n this.setAttribute(FINISH_REASON_TAG, this._finishReason);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.spanRecorder) {\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestampInS);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanContext().spanId === this.spanContext().spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!spanToJSON(span).timestamp) {\n span.setStatus('cancelled');\n span.end(endTimestampInS);\n DEBUG_BUILD &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const { start_timestamp: startTime, timestamp: endTime } = spanToJSON(span);\n const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(span, undefined, 2);\n if (!spanStartedBeforeTransactionFinish) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);\n }\n }\n\n return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;\n });\n\n DEBUG_BUILD && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n DEBUG_BUILD && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this._idleHub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n if (scope.getTransaction() === this) {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(undefined);\n }\n }\n\n return super.end(endTimestamp);\n }\n\n /**\n * Register a callback function that gets executed before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n DEBUG_BUILD && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.\n */\n public sendAutoFinishSignal(): void {\n if (!this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Received finish signal for idle transaction.');\n this._restartIdleTimeout();\n this._autoFinishAllowed = true;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.end(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n DEBUG_BUILD && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n DEBUG_BUILD && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n if (this._autoFinishAllowed) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n if (this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.end();\n }\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n DEBUG_BUILD && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n","import type { Transaction } from '@sentry/types';\nimport { extractTraceparentData as _extractTraceparentData } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * Grabs active transaction off scope.\n *\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveTransaction(maybeHub?: Hub): T | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = maybeHub || getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const scope = hub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n *\n * @deprecated Import this function from `@sentry/utils` instead\n */\nexport const extractTraceparentData = _extractTraceparentData;\n","import {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n logger,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SpanStatusType } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n DEBUG_BUILD && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n","import type { Options, SamplingContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '../semanticAttributes';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanToJSON } from '../utils/spanUtils';\nimport type { Transaction } from './transaction';\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * This method muttes the given `transaction` and will set the `sampled` value on it.\n * It returns the same transaction, for convenience.\n */\nexport function sampleTransaction(\n transaction: T,\n options: Pick,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.sampled !== undefined) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled));\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n // eslint-disable-next-line deprecation/deprecation\n if (!transaction.sampled) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanToJSON(transaction).description}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nexport function isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n","import type { ClientOptions, CustomSamplingContext, TransactionContext } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { spanToTraceHeader } from '../utils/spanUtils';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { sampleTransaction } from './sampling';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\n// eslint-disable-next-line deprecation/deprecation\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': spanToTraceHeader(span),\n }\n : {};\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n // eslint-disable-next-line deprecation/deprecation\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n DEBUG_BUILD &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n // eslint-disable-next-line deprecation/deprecation\n transactionContext.sampled = false;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new Transaction(transactionContext, this);\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n delayAutoFinishUntilSignal: boolean = false,\n): IdleTransaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new IdleTransaction(\n transactionContext,\n hub,\n idleTimeout,\n finalTimeout,\n heartbeatInterval,\n onScope,\n delayAutoFinishUntilSignal,\n );\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric } from '../../types';\nimport { observe } from '../observe';\n\ndeclare global {\n interface Performance {\n interactionCount: number;\n }\n}\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries: Metric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(e => {\n if (e.interactionId) {\n minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId);\n maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId);\n\n interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;\n }\n });\n};\n\nlet po: PerformanceObserver | undefined;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nexport const getInteractionCount = (): number => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nexport const initInteractionCountPolyfill = (): void => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } as PerformanceObserverInit);\n};\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ &\n // document is not available in all browser environments (webworkers). We make it optional so you have to explicitly check for it\n Omit &\n Partial>;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if ((WINDOW.document && WINDOW.document.prerendering) || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document!.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (\n onReport: ReportCallback,\n options: { reportAllChanges?: boolean } = {},\n): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, options.reportAllChanges);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): void => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n if (WINDOW.document && WINDOW.document.visibilityState) {\n firstHiddenTime = WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n }\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { getInteractionCount, initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { INPMetric } from './types/inp';\n\ninterface Interaction {\n id: number;\n latency: number;\n entries: PerformanceEventTiming[];\n}\n\n/**\n * Returns the interaction count since the last bfcache restore (or for the\n * full page lifecycle if there were no bfcache restores).\n */\nconst getInteractionCountForNavigation = (): number => {\n return getInteractionCount();\n};\n\n// To prevent unnecessary memory usage on pages with lots of interactions,\n// store at most 10 of the longest interactions to consider as INP candidates.\nconst MAX_INTERACTIONS_TO_CONSIDER = 10;\n\n// A list of longest interactions on the page (by latency) sorted so the\n// longest one is first. The list is as most MAX_INTERACTIONS_TO_CONSIDER long.\nconst longestInteractionList: Interaction[] = [];\n\n// A mapping of longest interactions by their interaction ID.\n// This is used for faster lookup.\nconst longestInteractionMap: { [interactionId: string]: Interaction } = {};\n\n/**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\nconst processEntry = (entry: PerformanceEventTiming): void => {\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const existingInteraction = longestInteractionMap[entry.interactionId!];\n\n // Only process the entry if it's possibly one of the ten longest,\n // or if it's part of an existing interaction.\n if (\n existingInteraction ||\n longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n entry.duration > minLongestInteraction.latency\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (existingInteraction) {\n existingInteraction.entries.push(entry);\n existingInteraction.latency = Math.max(existingInteraction.latency, entry.duration);\n } else {\n const interaction = {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n id: entry.interactionId!,\n latency: entry.duration,\n entries: [entry],\n };\n longestInteractionMap[interaction.id] = interaction;\n longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n longestInteractionList.sort((a, b) => b.latency - a.latency);\n longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete longestInteractionMap[i.id];\n });\n }\n};\n\n/**\n * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\nconst estimateP98LongestInteraction = (): Interaction => {\n const candidateInteractionIndex = Math.min(\n longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return longestInteractionList[candidateInteractionIndex];\n};\n\n/**\n * Calculates the [INP](https://web.dev/responsiveness/) value for the current\n * page and calls the `callback` function once the value is ready, along with\n * the `event` performance entries reported for that interaction. The reported\n * value is a `DOMHighResTimeStamp`.\n *\n * A custom `durationThreshold` configuration option can optionally be passed to\n * control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 are\n * reported as 0. Note that this will not affect your 75th percentile INP value\n * unless that value is also less than 40 (well below the recommended\n * [good](https://web.dev/inp/#what-is-a-good-inp-score) threshold).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** INP should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onINP = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/inp/#what's-a-%22good%22-inp-value\n // const thresholds = [200, 500];\n\n // TODO(philipwalton): remove once the polyfill is no longer needed.\n initInteractionCountPolyfill();\n\n const metric = initMetric('INP');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntries = (entries: INPMetric['entries']): void => {\n entries.forEach(entry => {\n if (entry.interactionId) {\n processEntry(entry);\n }\n\n // Entries of type `first-input` don't currently have an `interactionId`,\n // so to consider them in INP we have to first check that an existing\n // entry doesn't match the `duration` and `startTime`.\n // Note that this logic assumes that `event` entries are dispatched\n // before `first-input` entries. This is true in Chrome but it is not\n // true in Firefox; however, Firefox doesn't support interactionId, so\n // it's not an issue at the moment.\n // TODO(philipwalton): remove once crbug.com/1325826 is fixed.\n if (entry.entryType === 'first-input') {\n const noMatchingEntry = !longestInteractionList.some(interaction => {\n return interaction.entries.some(prevEntry => {\n return entry.duration === prevEntry.duration && entry.startTime === prevEntry.startTime;\n });\n });\n if (noMatchingEntry) {\n processEntry(entry);\n }\n }\n });\n\n const inp = estimateP98LongestInteraction();\n\n if (inp && inp.latency !== metric.value) {\n metric.value = inp.latency;\n metric.entries = inp.entries;\n report();\n }\n };\n\n const po = observe('event', handleEntries, {\n // Event Timing entries have their durations rounded to the nearest 8ms,\n // so a duration of 40ms would be any event that spans 2.5 or more frames\n // at 60Hz. This threshold is chosen to strike a balance between usefulness\n // and performance. Running this callback for any interaction that spans\n // just one or two frames is likely not worth the insight that could be\n // gained.\n durationThreshold: opts.durationThreshold || 40,\n } as PerformanceObserverInit);\n\n report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n if (po) {\n // Also observe entries of type `first-input`. This is useful in cases\n // where the first interaction is less than the `durationThreshold`.\n po.observe({ type: 'first-input', buffered: true });\n\n onHidden(() => {\n handleEntries(po.takeRecords() as INPMetric['entries']);\n\n // If the interaction count shows that there were interactions but\n // none were captured by the PerformanceObserver, report a latency of 0.\n if (metric.value < 0 && getInteractionCountForNavigation() > 0) {\n metric.value = 0;\n metric.entries = [];\n }\n\n report(true);\n });\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, stopListening, { once: true, capture: true });\n }\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getNavigationEntry } from './lib/getNavigationEntry';\nimport { initMetric } from './lib/initMetric';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { TTFBMetric } from './types/ttfb';\n\n/**\n * Runs in the next task after the page is done loading and/or prerendering.\n * @param callback\n */\nconst whenReady = (callback: () => void): void => {\n if (!WINDOW.document) {\n return;\n }\n\n if (WINDOW.document.prerendering) {\n addEventListener('prerenderingchange', () => whenReady(callback), true);\n } else if (WINDOW.document.readyState !== 'complete') {\n addEventListener('load', () => whenReady(callback), true);\n } else {\n // Queue a task so the callback runs after `loadEventEnd`.\n setTimeout(callback, 0);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/time-to-first-byte/) value for the\n * current page and calls the `callback` function once the page has loaded,\n * along with the relevant `navigation` performance entry used to determine the\n * value. The reported value is a `DOMHighResTimeStamp`.\n *\n * Note, this function waits until after the page is loaded to call `callback`\n * in order to ensure all properties of the `navigation` entry are populated.\n * This is useful if you want to report on other metrics exposed by the\n * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For\n * example, the TTFB metric starts from the page's [time\n * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it\n * includes time spent on DNS lookup, connection negotiation, network latency,\n * and server processing time.\n */\nexport const onTTFB = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/ttfb/#what-is-a-good-ttfb-score\n // const thresholds = [800, 1800];\n\n const metric = initMetric('TTFB');\n const report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n whenReady(() => {\n const navEntry = getNavigationEntry() as TTFBMetric['entries'][number];\n\n if (navEntry) {\n // The activationStart reference is used because TTFB should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the first byte is received, this time should be clamped at 0.\n metric.value = Math.max(navEntry.responseStart - getActivationStart(), 0);\n\n // In some cases the value reported is negative or is larger\n // than the current page time. Ignore these cases:\n // https://github.com/GoogleChrome/web-vitals/issues/137\n // https://github.com/GoogleChrome/web-vitals/issues/162\n if (metric.value < 0 || metric.value > performance.now()) return;\n\n metric.entries = [navEntry];\n\n report(true);\n }\n });\n};\n","import { getFunctionName, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { onCLS } from './web-vitals/getCLS';\nimport { onFID } from './web-vitals/getFID';\nimport { onINP } from './web-vitals/getINP';\nimport { onLCP } from './web-vitals/getLCP';\nimport { observe } from './web-vitals/lib/observe';\nimport { onTTFB } from './web-vitals/onTTFB';\n\ntype InstrumentHandlerTypePerformanceObserver =\n | 'longtask'\n | 'event'\n | 'navigation'\n | 'paint'\n | 'resource'\n | 'first-input';\n\ntype InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid' | 'ttfb' | 'inp';\n\n// We provide this here manually instead of relying on a global, as this is not available in non-browser environements\n// And we do not want to expose such types\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): Record;\n}\ninterface PerformanceEventTiming extends PerformanceEntry {\n processingStart: number;\n processingEnd: number;\n duration: number;\n cancelable?: boolean;\n target?: unknown | null;\n interactionId?: number;\n}\n\ninterface Metric {\n /**\n * The name of the metric (in acronym form).\n */\n name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';\n\n /**\n * The current value of the metric.\n */\n value: number;\n\n /**\n * The rating as to whether the metric value is within the \"good\",\n * \"needs improvement\", or \"poor\" thresholds of the metric.\n */\n rating: 'good' | 'needs-improvement' | 'poor';\n\n /**\n * The delta between the current value and the last-reported value.\n * On the first report, `delta` and `value` will always be the same.\n */\n delta: number;\n\n /**\n * A unique ID representing this particular metric instance. This ID can\n * be used by an analytics tool to dedupe multiple values sent for the same\n * metric instance, or to group multiple deltas together and calculate a\n * total. It can also be used to differentiate multiple different metric\n * instances sent from the same page, which can happen if the page is\n * restored from the back/forward cache (in that case new metrics object\n * get created).\n */\n id: string;\n\n /**\n * Any performance entries relevant to the metric value calculation.\n * The array may also be empty if the metric value was not based on any\n * entries (e.g. a CLS value of 0 given no layout shifts).\n */\n entries: PerformanceEntry[];\n\n /**\n * The type of navigation\n *\n * Navigation Timing API (or `undefined` if the browser doesn't\n * support that API). For pages that are restored from the bfcache, this\n * value will be 'back-forward-cache'.\n */\n navigationType: 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender';\n}\n\ntype InstrumentHandlerType = InstrumentHandlerTypeMetric | InstrumentHandlerTypePerformanceObserver;\n\ntype StopListening = undefined | void | (() => void);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentHandlerCallback = (data: any) => void;\n\ntype CleanupHandlerCallback = () => void;\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\nlet _previousCls: Metric | undefined;\nlet _previousFid: Metric | undefined;\nlet _previousLcp: Metric | undefined;\nlet _previousTtfb: Metric | undefined;\nlet _previousInp: Metric | undefined;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nexport function addClsInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nexport function addLcpInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nexport function addTtfbInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addFidInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addInpInstrumentationHandler(\n callback: (data: { metric: Omit & { entries: PerformanceEventTiming[] } }) => void,\n): CleanupHandlerCallback {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\nexport function addPerformanceInstrumentationHandler(\n type: 'event' | 'first-input',\n callback: (data: { entries: ((PerformanceEntry & { target?: unknown | null }) | PerformanceEventTiming)[] }) => void,\n): CleanupHandlerCallback;\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback;\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls(): StopListening {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentFid(): void {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp(): StopListening {\n return onLCP(metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n });\n}\n\nfunction instrumentTtfb(): StopListening {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp(): void {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type: InstrumentHandlerTypeMetric,\n callback: InstrumentHandlerCallback,\n instrumentFn: () => StopListening,\n previousValue: Metric | undefined,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n let stopListening: StopListening | undefined;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type: InstrumentHandlerTypePerformanceObserver): void {\n const options: PerformanceObserverInit = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type: InstrumentHandlerType,\n callback: InstrumentHandlerCallback,\n stopListening: StopListening,\n): CleanupHandlerCallback {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import type { DsnComponents, SpanEnvelope, SpanItem } from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Create envelope from Span item.\n */\nexport function createSpanEnvelope(spans: Span[], dsn?: DsnComponents): SpanEnvelope {\n const headers: SpanEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const items = spans.map(createSpanItem);\n return createEnvelope(headers, items);\n}\n\nfunction createSpanItem(span: Span): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n return [spanHeaders, span];\n}\n","import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n *\n * Note: this will not be possible anymore in v8,\n * unless we do some special handling for browser here...\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n // eslint-disable-next-line deprecation/deprecation\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.startTimestamp = startTimestamp;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport {\n Span,\n getActiveTransaction,\n getClient,\n hasTracingEnabled,\n isValidSampleRate,\n setMeasurement,\n} from '@sentry/core';\nimport type { ClientOptions, Measurements, SpanContext, TransactionContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getComponentName, htmlTreeAsString, logger, parseUrl } from '@sentry/utils';\n\nimport { spanToJSON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport {\n addClsInstrumentationHandler,\n addFidInstrumentationHandler,\n addInpInstrumentationHandler,\n addLcpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n addTtfbInstrumentationHandler,\n} from '../instrument';\nimport { WINDOW } from '../types';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport type {\n InteractionRouteNameMapping,\n NavigatorDeviceMemory,\n NavigatorNetworkInformation,\n} from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\nimport { createSpanEnvelope } from '@sentry/core';\nimport { getNavigationEntry } from '../web-vitals/lib/getNavigationEntry';\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals.\n * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured.\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n const fidCallback = _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n const ttfbCallback = _trackTtfb();\n\n return (): void => {\n fidCallback();\n clsCallback();\n lcpCallback();\n ttfbCallback();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n });\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const span: SpanContext = {\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n };\n\n const componentName = getComponentName(entry.target);\n if (componentName) {\n span.attributes = { 'ui.component_name': componentName };\n }\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild(span);\n }\n }\n });\n}\n\n/**\n * Start tracking INP webvital events.\n */\nexport function startTrackingINP(\n interactionIdtoRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n const inpCallback = _trackINP(interactionIdtoRouteNameMapping, interactionsSampleRate);\n\n return (): void => {\n inpCallback();\n };\n }\n\n return () => undefined;\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): () => void {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n }, true);\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): () => void {\n return addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n }, true);\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): () => void {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n DEBUG_BUILD && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\nfunction _trackTtfb(): () => void {\n return addTtfbInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' };\n });\n}\n\nconst INP_ENTRY_MAP: Record = {\n click: 'click',\n pointerdown: 'click',\n pointerup: 'click',\n mousedown: 'click',\n mouseup: 'click',\n touchstart: 'click',\n touchend: 'click',\n mouseover: 'hover',\n mouseout: 'hover',\n mouseenter: 'hover',\n mouseleave: 'hover',\n pointerover: 'hover',\n pointerout: 'hover',\n pointerenter: 'hover',\n pointerleave: 'hover',\n dragstart: 'drag',\n dragend: 'drag',\n drag: 'drag',\n dragenter: 'drag',\n dragleave: 'drag',\n dragover: 'drag',\n drop: 'drag',\n keydown: 'press',\n keyup: 'press',\n keypress: 'press',\n input: 'press',\n};\n\n/** Starts tracking the Interaction to Next Paint on the current page. */\nfunction _trackINP(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n return addInpInstrumentationHandler(({ metric }) => {\n if (metric.value === undefined) {\n return;\n }\n const entry = metric.entries.find(\n entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name] !== undefined,\n );\n const client = getClient();\n if (!entry || !client) {\n return;\n }\n const interactionType = INP_ENTRY_MAP[entry.name];\n const options = client.getOptions();\n /** Build the INP span, create an envelope from the span, and then send the envelope */\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(metric.value);\n const interaction =\n entry.interactionId !== undefined ? interactionIdToRouteNameMapping[entry.interactionId] : undefined;\n if (interaction === undefined) {\n return;\n }\n const { routeName, parentContext, activeTransaction, user, replayId } = interaction;\n const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const profileId = activeTransaction !== undefined ? activeTransaction.getProfileId() : undefined;\n const span = new Span({\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n op: `ui.interaction.${interactionType}`,\n name: htmlTreeAsString(entry.target),\n attributes: {\n release: options.release,\n environment: options.environment,\n transaction: routeName,\n ...(userDisplay !== undefined && userDisplay !== '' ? { user: userDisplay } : {}),\n ...(profileId !== undefined ? { profile_id: profileId } : {}),\n ...(replayId !== undefined ? { replay_id: replayId } : {}),\n },\n exclusiveTime: metric.value,\n measurements: {\n inp: { value: metric.value, unit: 'millisecond' },\n },\n });\n\n /** Check to see if the span should be sampled */\n const sampleRate = getSampleRate(parentContext, options, interactionsSampleRate);\n\n if (!sampleRate) {\n return;\n }\n\n if (Math.random() < (sampleRate as number | boolean)) {\n const envelope = span ? createSpanEnvelope([span], client.getDsn()) : undefined;\n const transport = client && client.getTransport();\n if (transport && envelope) {\n transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending interaction:', reason);\n });\n }\n return;\n }\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n DEBUG_BUILD && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n const { op, start_timestamp: transactionStartTime } = spanToJSON(transaction);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n _addResourceSpans(transaction, entry, entry.name as string, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (op === 'pageload') {\n _addTtfbRequestTimeToMeasurements(_measurements);\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || !transactionStartTime || timeOrigin >= transactionStartTime) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transactionStartTime) * 1000);\n const delta = normalizedValue - oldValue;\n\n DEBUG_BUILD && logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n setMeasurement(measurementName, _measurements[measurementName].value, _measurements[measurementName].unit);\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n origin: 'auto.resource.browser.metrics',\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record, timeOrigin: number): void {\n if (entry.responseEnd) {\n // It is possible that we are collecting these metrics when the page hasn't finished loading yet, for example when the HTML slowly streams in.\n // In this case, ie. when the document request hasn't finished yet, `entry.responseEnd` will be 0.\n // In order not to produce faulty spans, where the end timestamp is before the start timestamp, we will only collect\n // these spans when the responseEnd value is available. The backend (Relay) would drop the entire transaction if it contained faulty spans.\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n }\n}\n\nexport interface ResourceEntry extends Record {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceUrl: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n const parsedUrl = parseUrl(resourceUrl);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record = {};\n setResourceEntrySizeData(data, entry, 'transferSize', 'http.response_transfer_size');\n setResourceEntrySizeData(data, entry, 'encodedBodySize', 'http.response_content_length');\n setResourceEntrySizeData(data, entry, 'decodedBodySize', 'http.decoded_response_content_length');\n\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n if (parsedUrl.protocol) {\n data['url.scheme'] = parsedUrl.protocol.split(':').pop(); // the protocol returned by parseUrl includes a :, but OTEL spec does not, so we remove it.\n }\n\n if (parsedUrl.host) {\n data['server.address'] = parsedUrl.host;\n }\n\n data['url.same_origin'] = resourceUrl.includes(WINDOW.location.origin);\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceUrl.replace(WINDOW.location.origin, ''),\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n origin: 'auto.resource.browser.metrics',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nfunction setResourceEntrySizeData(\n data: Record,\n entry: ResourceEntry,\n key: keyof Pick,\n dataKey: 'http.response_transfer_size' | 'http.response_content_length' | 'http.decoded_response_content_length',\n): void {\n const entryVal = entry[key];\n if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {\n data[dataKey] = entryVal;\n }\n}\n\n/**\n * Add ttfb request time information to measurements.\n *\n * ttfb information is added via vendored web vitals library.\n */\nfunction _addTtfbRequestTimeToMeasurements(_measurements: Measurements): void {\n const navEntry = getNavigationEntry();\n if (!navEntry) {\n return;\n }\n\n const { responseStart, requestStart } = navEntry;\n\n if (requestStart <= responseStart) {\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB Request Time');\n _measurements['ttfb.requestTime'] = {\n value: responseStart - requestStart,\n unit: 'millisecond',\n };\n }\n}\n\n/** Taken from @sentry/core sampling.ts */\nfunction getSampleRate(\n transactionContext: TransactionContext | undefined,\n options: ClientOptions,\n interactionsSampleRate: number,\n): number | boolean {\n if (!hasTracingEnabled(options)) {\n return false;\n }\n let sampleRate;\n if (transactionContext !== undefined && typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler({\n transactionContext,\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n location: WINDOW.location,\n });\n } else if (transactionContext !== undefined && transactionContext.sampled !== undefined) {\n sampleRate = transactionContext.sampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n } else {\n sampleRate = 1;\n }\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding interaction span because of invalid sample rate.');\n return false;\n }\n if (sampleRate === true) {\n return interactionsSampleRate;\n } else if (sampleRate === false) {\n return 0;\n }\n return sampleRate * interactionsSampleRate;\n}\n","/* eslint-disable max-lines */\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToJSON,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, Span } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n SENTRY_XHR_DATA_KEY,\n addFetchInstrumentationHandler,\n addXhrInstrumentationHandler,\n browserPerformanceTimeOrigin,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n parseUrl,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nimport { instrumentFetchRequest } from '../common/fetch';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport { WINDOW } from './types';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * @deprecated Use the top-level `tracePropagationTargets` option in `Sentry.init` instead.\n * This option will be removed in v8.\n *\n * Default: ['localhost', /^\\//] @see {DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * If true, Sentry will capture http timings and add them to the corresponding http spans.\n *\n * Default: true\n */\n enableHTTPTimings: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial): void {\n const {\n traceFetch,\n traceXHR,\n // eslint-disable-next-line deprecation/deprecation\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record = {};\n\n if (traceFetch) {\n addFetchInstrumentationHandler(handlerData => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n // We cannot use `window.location` in the generic fetch instrumentation,\n // but we need it for reliable `server.address` attribute.\n // so we extend this in here\n if (createdSpan) {\n const fullUrl = getFullURL(handlerData.fetchData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n createdSpan.setAttributes({\n 'http.url': fullUrl,\n 'server.address': host,\n });\n }\n\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry as PerformanceResourceTiming).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span: Span): void {\n const { url } = spanToJSON(span).data || {};\n\n if (!url || typeof url !== 'string') {\n return;\n }\n\n const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setAttribute(...data));\n // In the next tick, clean this handler up\n // We have to wait here because otherwise this cleans itself up before it is fully done\n setTimeout(cleanup);\n }\n });\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nexport function extractNetworkProtocol(nextHopProtocol: string): { name: string; version: string } {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/');\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1];\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time: number = 0): number {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming: PerformanceResourceTiming): [string, string | number][] {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData: [string, string | number][] = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nexport function xhrCallback(\n handlerData: HandlerDataXhr,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): Span | undefined {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span && sentryXhrData.status_code !== undefined) {\n setHttpStatus(span, sentryXhrData.status_code);\n span.end();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const isolationScope = getIsolationScope();\n\n const fullUrl = getFullURL(sentryXhrData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${sentryXhrData.method} ${sentryXhrData.url}`,\n onlyIfParent: true,\n attributes: {\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n 'http.url': fullUrl,\n url: sentryXhrData.url,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n const client = getClient();\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) {\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n\n return span;\n}\n\nfunction setHeaderOnXhr(\n xhr: SentryWrappedXMLHttpRequest,\n sentryTraceHeader: string,\n sentryBaggageHeader: string | undefined,\n): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n // By adding a base URL to new URL(), this will also work for relative urls\n // If `url` is a full URL, the base URL is ignored anyhow\n const parsed = new URL(url, WINDOW.location.origin);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n","import {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { Client, HandlerDataFetch, Scope, Span, SpanOrigin } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n isInstanceOf,\n parseUrl,\n} from '@sentry/utils';\n\ntype PolymorphicRequestHeaders =\n | Record\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\n/**\n * Create and track fetch request spans for usage in combination with `addInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n handlerData: HandlerDataFetch,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n spanOrigin: SpanOrigin = 'auto.http.browser',\n): Span | undefined {\n if (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const client = getClient();\n\n const { method, url } = handlerData.fetchData;\n\n const fullUrl = getFullURL(url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${method} ${url}`,\n onlyIfParent: true,\n attributes: {\n url,\n type: 'fetch',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n client: Client,\n scope: Scope,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n requestSpan?: Span,\n): PolymorphicRequestHeaders | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const span = requestSpan || scope.getSpan();\n\n const isolationScope = getIsolationScope();\n\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n const headers =\n options.headers ||\n (typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : undefined);\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n\nfunction endSpan(span: Span, handlerData: HandlerDataFetch): void {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength =\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.end();\n}\n","/* eslint-disable max-lines */\nimport type { Hub, IdleTransaction } from '@sentry/core';\nimport { getClient, getCurrentScope } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n TRACING_DEFAULTS,\n addTracingExtensions,\n getActiveTransaction,\n startIdleTransaction,\n} from '@sentry/core';\nimport type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';\nimport { getDomElement, logger, propagationContextFromHeaders } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport {\n addPerformanceEntries,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nimport { WINDOW } from './types';\nimport type { InteractionRouteNameMapping } from './web-vitals/types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * If true, Sentry will capture INP web vitals as standalone spans .\n *\n * Default: false\n */\n enableInp: boolean;\n\n /**\n * Sample rate to determine interaction span sampling.\n * interactionsSampleRate is applied on top of the global tracesSampleRate.\n * ie a tracesSampleRate of 0.1 and interactionsSampleRate of 0.5 will result in a 0.05 sample rate for interactions.\n *\n * Default: 1\n */\n interactionsSampleRate: number;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableLongTask: boolean;\n enableInteractions: boolean;\n // eslint-disable-next-line deprecation/deprecation\n onStartRouteTransaction: (t: Transaction | undefined, ctx: TransactionContext, getCurrentHub: () => Hub) => void;\n }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(this: void, context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation(\n this: void,\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n enableInp: false,\n interactionsSampleRate: 1,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */\nconst MAX_INTERACTIONS = 10;\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n *\n * @deprecated Use `browserTracingIntegration()` instead.\n */\nexport class BrowserTracing implements Integration {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n // eslint-disable-next-line deprecation/deprecation\n private _getCurrentHub?: () => Hub;\n\n private _collectWebVitals: () => void;\n\n private _hasSetTracePropagationTargets: boolean;\n private _interactionIdToRouteNameMapping: InteractionRouteNameMapping;\n private _latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n };\n\n public constructor(_options?: Partial) {\n this.name = BROWSER_TRACING_INTEGRATION_ID;\n this._hasSetTracePropagationTargets = false;\n\n addTracingExtensions();\n\n if (DEBUG_BUILD) {\n this._hasSetTracePropagationTargets = !!(\n _options &&\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n );\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */\n this._interactionIdToRouteNameMapping = {};\n\n if (this.options.enableInp) {\n startTrackingINP(this._interactionIdToRouteNameMapping, this.options.interactionsSampleRate);\n }\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n\n this._latestRoute = {\n name: undefined,\n context: undefined,\n };\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const clientOptions = client && client.getOptions();\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n _experiments,\n } = this.options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;\n if (DEBUG_BUILD && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n instrumentRouting(\n (context: TransactionContext) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n if (this.options.enableInp) {\n this._registerInpInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n let expandedContext: TransactionContext;\n if (isPageloadTransaction) {\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined;\n const { traceId, dsc, parentSpanId, sampled } = propagationContextFromHeaders(sentryTrace, baggage);\n expandedContext = {\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...context,\n metadata: {\n // eslint-disable-next-line deprecation/deprecation\n ...context.metadata,\n dynamicSamplingContext: dsc,\n },\n trimEnd: true,\n };\n } else {\n expandedContext = {\n trimEnd: true,\n ...context,\n };\n }\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? // eslint-disable-next-line deprecation/deprecation\n { ...finalContext.metadata, source: 'custom' }\n : // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata;\n\n this._latestRoute.name = finalContext.name;\n this._latestRoute.context = finalContext;\n\n // eslint-disable-next-line deprecation/deprecation\n if (finalContext.sampled === false) {\n DEBUG_BUILD && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n DEBUG_BUILD && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n isPageloadTransaction, // should wait for finish signal if it's a pageload transaction\n );\n\n if (isPageloadTransaction) {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n if (['interactive', 'complete'].includes(WINDOW.document!.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n });\n\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n }\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n /** Start listener for interaction transactions */\n private _registerInteractionListener(): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n // eslint-disable-next-line deprecation/deprecation\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.end();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: this._latestRoute.name,\n op,\n trimEnd: true,\n data: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: this._latestRoute.context\n ? getSource(this._latestRoute.context)\n : undefined || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n }\n });\n }\n\n /** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */\n private _registerInpInteractionListener(): void {\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const client = getClient();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay =\n client !== undefined && client.getIntegrationByName !== undefined\n ? (client.getIntegrationByName('Replay') as Integration & { getReplayId: () => string })\n : undefined;\n const replayId = replay !== undefined ? replay.getReplayId() : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n const currentScope = getCurrentScope();\n const user = currentScope !== undefined ? currentScope.getUser() : undefined;\n entries.forEach(entry => {\n if (isPerformanceEventTiming(entry)) {\n const interactionId = entry.interactionId;\n if (interactionId === undefined) {\n return;\n }\n const existingInteraction = this._interactionIdToRouteNameMapping[interactionId];\n const duration = entry.duration;\n const startTime = entry.startTime;\n const keys = Object.keys(this._interactionIdToRouteNameMapping);\n const minInteractionId =\n keys.length > 0\n ? keys.reduce((a, b) => {\n return this._interactionIdToRouteNameMapping[a].duration <\n this._interactionIdToRouteNameMapping[b].duration\n ? a\n : b;\n })\n : undefined;\n // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time.\n // This is also checked in the web-vitals library.\n if (entry.entryType === 'first-input') {\n const matchingEntry = keys\n .map(key => this._interactionIdToRouteNameMapping[key])\n .some(interaction => {\n return interaction.duration === duration && interaction.startTime === startTime;\n });\n if (matchingEntry) {\n return;\n }\n }\n // Interactions with an id of 0 and are not first-input are not valid.\n if (!interactionId) {\n return;\n }\n // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses.\n if (existingInteraction) {\n existingInteraction.duration = Math.max(existingInteraction.duration, duration);\n } else if (\n keys.length < MAX_INTERACTIONS ||\n minInteractionId === undefined ||\n duration > this._interactionIdToRouteNameMapping[minInteractionId].duration\n ) {\n // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry.\n const routeName = this._latestRoute.name;\n const parentContext = this._latestRoute.context;\n if (routeName && parentContext) {\n if (minInteractionId && Object.keys(this._interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._interactionIdToRouteNameMapping[minInteractionId];\n }\n this._interactionIdToRouteNameMapping[interactionId] = {\n routeName,\n duration,\n parentContext,\n user,\n activeTransaction,\n replayId,\n startTime,\n };\n }\n }\n }\n });\n };\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n }\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\nfunction getSource(context: TransactionContext): TransactionSource | undefined {\n const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromData = context.data && context.data[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromMetadata = context.metadata && context.metadata.source;\n\n return sourceFromAttributes || sourceFromData || sourceFromMetadata;\n}\n\nfunction isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n","import type { Transaction, TransactionContext } from '@sentry/types';\nimport { addHistoryInstrumentationHandler, browserPerformanceTimeOrigin, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!WINDOW || !WINDOW.location) {\n DEBUG_BUILD && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = WINDOW.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n origin: 'auto.pageload.browser',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.end();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n origin: 'auto.navigation.browser',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n","import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction, spanToJSON } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document!.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n const { op, status } = spanToJSON(activeTransaction);\n\n DEBUG_BUILD &&\n logger.log(`[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${op}`);\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!status) {\n activeTransaction.setStatus(statusType);\n }\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.end();\n }\n });\n } else {\n DEBUG_BUILD && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n","import type { MeasurementUnit } from '@sentry/types';\n\nimport { getActiveTransaction } from './utils';\n\n/**\n * Adds a measurement to the current active transaction.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit): void {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction();\n if (transaction) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setMeasurement(name, value, unit);\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","import type { ConsoleLevel } from '@sentry/types';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\nimport { serializeMetricBuckets } from './utils';\n\n/**\n * Create envelope from a metric aggregate.\n */\nexport function createMetricEnvelope(\n metricBucketItems: Array,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): StatsdEnvelope {\n const headers: StatsdEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const item = createMetricEnvelopeItem(metricBucketItems);\n return createEnvelope(headers, [item]);\n}\n\nfunction createMetricEnvelopeItem(metricBucketItems: MetricBucketItem[]): StatsdItem {\n const payload = serializeMetricBuckets(metricBucketItems);\n const metricHeaders: StatsdItem[0] = {\n type: 'statsd',\n length: payload.length,\n };\n return [metricHeaders, payload];\n}\n","import type { MeasurementUnit, MetricBucketItem, Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport type { MetricType } from './types';\n\n/**\n * Generate bucket key from metric properties.\n */\nexport function getBucketKey(\n metricType: MetricType,\n name: string,\n unit: MeasurementUnit,\n tags: Record,\n): string {\n const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));\n return `${metricType}${name}${unit}${stringifiedTags}`;\n}\n\n/* eslint-disable no-bitwise */\n/**\n * Simple hash function for strings.\n */\nexport function simpleHash(s: string): number {\n let rv = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n rv = (rv << 5) - rv + c;\n rv &= rv;\n }\n return rv >>> 0;\n}\n/* eslint-enable no-bitwise */\n\n/**\n * Serialize metrics buckets into a string based on statsd format.\n *\n * Example of format:\n * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677\n * Segments:\n * name: metric.name\n * unit: second\n * value: [1, 1.2]\n * type of metric: d (distribution)\n * tags: { a: value, b: anothervalue }\n * timestamp: 12345677\n */\nexport function serializeMetricBuckets(metricBucketItems: MetricBucketItem[]): string {\n let out = '';\n for (const item of metricBucketItems) {\n const tagEntries = Object.entries(item.tags);\n const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';\n out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\\n`;\n }\n return out;\n}\n\n/** Sanitizes units */\nexport function sanitizeUnit(unit: string): string {\n return unit.replace(/[^\\w]+/gi, '_');\n}\n\n/** Sanitizes metric keys */\nexport function sanitizeMetricKey(key: string): string {\n return key.replace(/[^\\w\\-.]+/gi, '_');\n}\n\nfunction sanitizeTagKey(key: string): string {\n return key.replace(/[^\\w\\-./]+/gi, '');\n}\n\nconst tagValueReplacements: [string, string][] = [\n ['\\n', '\\\\n'],\n ['\\r', '\\\\r'],\n ['\\t', '\\\\t'],\n ['\\\\', '\\\\\\\\'],\n ['|', '\\\\u{7c}'],\n [',', '\\\\u{2c}'],\n];\n\nfunction getCharOrReplacement(input: string): string {\n for (const [search, replacement] of tagValueReplacements) {\n if (input === search) {\n return replacement;\n }\n }\n\n return input;\n}\n\nfunction sanitizeTagValue(value: string): string {\n return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), '');\n}\n\n/**\n * Sanitizes tags.\n */\nexport function sanitizeTags(unsanitizedTags: Record): Record {\n const tags: Record = {};\n for (const key in unsanitizedTags) {\n if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {\n const sanitizedKey = sanitizeTagKey(key);\n tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));\n }\n }\n return tags;\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n EventProcessor,\n FeedbackEvent,\n Integration,\n IntegrationClass,\n MetricBucketItem,\n MetricsAggregator,\n Outcome,\n ParameterizedString,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n StartSpanOptions,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n SentryError,\n SyncPromise,\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isParameterizedString,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport { getClient } from './exports';\nimport { getIsolationScope } from './hub';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport { createMetricEnvelope } from './metrics/envelope';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /**\n * A reference to a metrics aggregator\n *\n * @experimental Note this is alpha API. It may experience breaking changes in the future.\n */\n public metricsAggregator?: MetricsAggregator;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n protected _eventProcessors: EventProcessor[];\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(\n this._captureEvent(event, hint, capturedSpanScope || scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n if (this.metricsAggregator) {\n this.metricsAggregator.flush();\n }\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n if (this.metricsAggregator) {\n this.metricsAggregator.close();\n }\n return result;\n });\n }\n\n /** Get all installed event processors. */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * This is an internal function to setup all integrations that should run on the client.\n * @deprecated Use `client.init()` instead.\n */\n public setupIntegrations(forceInitialize?: boolean): void {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._setupIntegrations();\n }\n }\n\n /** @inheritdoc */\n public init(): void {\n if (this._isEnabled()) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this.getIntegrationByName(integrationId);\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n public getIntegrationByName(integrationName: string): T | undefined {\n return this._integrations[integrationName] as T | undefined;\n }\n\n /**\n * Returns the client's instance of the given integration class, it any.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, eventOrCount?: Event | number): void {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /**\n * @inheritDoc\n */\n public captureAggregateMetrics(metricBucketItems: Array): void {\n DEBUG_BUILD && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);\n const metricsEnvelope = createMetricEnvelope(\n metricBucketItems,\n this._dsn,\n this._options._metadata,\n this._options.tunnel,\n );\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(metricsEnvelope);\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n public on(hook: 'startTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'startPageLoadSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'startPageLoadSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: 'startNavigationSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n protected _setupIntegrations(): void {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n\n // TODO v8: We don't need this flag anymore\n this._integrationsInitialized = true;\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope = getIsolationScope(),\n ): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n const propagationContext = {\n ...isolationScope.getPropagationContext(),\n ...(scope ? scope.getPropagationContext() : undefined),\n };\n\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n DEBUG_BUILD && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/**\n * Add an event processor to the current client.\n * This event processor will run for all events processed by this client.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n const client = getClient();\n\n if (!client || !client.addEventProcessor) {\n return;\n }\n\n client.addEventProcessor(callback);\n}\n","import type { Scope } from '@sentry/core';\nimport { applySdkMetadata } from '@sentry/core';\nimport { BaseClient } from '@sentry/core';\nimport type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n ParameterizedString,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(options, 'browser', ['browser'], sdkSource);\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n}\n","import type { Options } from '@sentry/types';\nimport { SDK_VERSION } from '../version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: Options, name: string, names = [name], source = 'npm'): void {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-expect-error __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type { DataCategory, TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = Date.now()): boolean {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n SentryError,\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n DEBUG_BUILD && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/**\n * Deduplication filter.\n * @deprecated Use `dedupeIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Dedupe = convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n>;\n\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport { functionToStringIntegration, inboundFiltersIntegration } from '@sentry/core';\nimport {\n captureSession,\n getClient,\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n startSession,\n} from '@sentry/core';\nimport type { Integration, Options, UserFeedback } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n logger,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs';\nimport { dedupeIntegration } from './integrations/dedupe';\nimport { globalHandlersIntegration } from './integrations/globalhandlers';\nimport { httpContextIntegration } from './integrations/httpcontext';\nimport { linkedErrorsIntegration } from './integrations/linkederrors';\nimport { browserApiErrorsIntegration } from './integrations/trycatch';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\n/** @deprecated Use `getDefaultIntegrations(options)` instead. */\nexport const defaultIntegrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n];\n\n/** Get the default integrations for the browser SDK. */\nexport function getDefaultIntegrations(_options: Options): Integration[] {\n // We return a copy of the defaultIntegrations here to avoid mutating this\n return [\n // eslint-disable-next-line deprecation/deprecation\n ...defaultIntegrations,\n ];\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\ntype NewReportDialogOptions = ReportDialogOptions & { eventId: string }; // eslint-disable-line\n\ninterface ShowReportDialogFunction {\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\n (options: NewReportDialogOptions): void;\n\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n *\n * @deprecated Please always pass an `options` argument with `eventId`. The `hub` argument will not be used in the next version of the SDK.\n */\n // eslint-disable-next-line deprecation/deprecation\n (options?: ReportDialogOptions, hub?: Hub): void;\n}\n\nexport const showReportDialog: ShowReportDialogFunction = (\n // eslint-disable-next-line deprecation/deprecation\n options: ReportDialogOptions = {},\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub = getCurrentHub(),\n) => {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n // eslint-disable-next-line deprecation/deprecation\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event: MessageEvent): void => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n};\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import {\n captureException,\n captureMessage,\n convertIntegrationFnToClass,\n defineIntegration,\n getClient,\n withScope,\n} from '@sentry/core';\nimport type { CaptureContext, Client, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport {\n CONSOLE_LEVELS,\n GLOBAL_OBJ,\n addConsoleInstrumentationHandler,\n addExceptionMechanism,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\ninterface CaptureConsoleOptions {\n levels?: string[];\n}\n\nconst INTEGRATION_NAME = 'CaptureConsole';\n\nconst _captureConsoleIntegration = ((options: CaptureConsoleOptions = {}) => {\n const levels = options.levels || CONSOLE_LEVELS;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.includes(level)) {\n return;\n }\n\n consoleHandler(args, level);\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);\n\n/**\n * Send Console API calls as Sentry Events.\n * @deprecated Use `captureConsoleIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const CaptureConsole = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n captureConsoleIntegration,\n) as IntegrationClass void }> & {\n new (options?: { levels?: string[] }): Integration;\n};\n\nfunction consoleHandler(args: unknown[], level: string): void {\n const captureContext: CaptureContext = {\n level: severityLevelFromString(level),\n extra: {\n arguments: args,\n },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'console';\n\n addExceptionMechanism(event, {\n handled: false,\n type: 'console',\n });\n\n return event;\n });\n\n if (level === 'assert' && args[0] === false) {\n const message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n captureMessage(message, captureContext);\n return;\n }\n\n const error = args.find(arg => arg instanceof Error);\n if (level === 'error' && error) {\n captureException(error, captureContext);\n return;\n }\n\n const message = safeJoin(args, ' ');\n captureMessage(message, captureContext);\n });\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["_typeof","require","_regeneratorRuntime","module","exports","__esModule","Op","Object","prototype","hasOwn","hasOwnProperty","defineProperty","obj","key","desc","value","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","fn","arg","type","call","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","result","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","undefined","done","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","methodName","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","runtime","regeneratorRuntime","accidentalStrictMode","globalThis","Function","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","n","getter","d","a","definition","o","get","g","e","window","prop","r","flarum","core","compat","DEBUG_BUILD","__SENTRY_DEBUG__","isGlobalObj","Math","GLOBAL_OBJ","global","getGlobalObject","getGlobalSingleton","creator","gbl","__SENTRY__","CONSOLE_LEVELS","originalConsoleMethods","consoleSandbox","callback","console","wrappedFuncs","wrappedLevels","level","originalConsoleMethod","enabled","logger","enable","disable","isEnabled","_len","arguments","args","Array","_key","_GLOBAL_OBJ$console","apply","PREFIX","concat","_extends","assign","bind","target","source","objectToString","toString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isParameterizedString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","base","_e","isVueViewModel","__isVue","_isVue","WINDOW","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","options","nextStr","currentElem","out","height","len","keyAttrs","isArray","maxStringLength","_htmlElementAsString","separator","parentNode","join","_oO","el","classes","attr","tagName","HTMLElement","dataset","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","keyAttrPair","id","split","allowedAttrs","getComponentName","truncate","str","max","safeJoin","input","delimiter","output","String","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","fill","replacementFactory","original","wrapped","markFunctionWrapped","addNonEnumerableProperty","o_O","log","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","message","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","isPojo","memoVal","returnValue","set","_i","_Object$keys","item","uuid4","crypto","msCrypto","getRandomByte","random","randomUUID","replace","getRandomValues","typedArray","Uint8Array","_","c","getFirstException","event","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","States","resolvedSyncPromise","SyncPromise","rejectedSyncPromise","reason","executor","__init","__init2","__init3","__init4","_state","PENDING","_handlers","_resolve","_reject","_proto","onfulfilled","onrejected","_this","_executeHandlers","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","_value","_this6","cachedHandlers","handler","getGlobalEventProcessors","addGlobalEventProcessor","notifyEventProcessors","processors","hint","index","processor","final","ONE_SECOND_IN_MS","dateTimestampInSeconds","Date","now","timestampInSeconds","performance","approxStartingTimeOrigin","timeOrigin","createUnixTimestampInSecondsFunc","browserPerformanceTimeOrigin","threshold","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","DEFAULT_ENVIRONMENT","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","abnormal_mechanism","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","defaultFunctionName","getFunctionName","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","document","objName","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","toJSON","numAdded","visitable","visitKey","visitValue","BAGGAGE_HEADER_NAME","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","dynamicSamplingContextToSentryBaggageHeader","dynamicSamplingContext","entries","reduce","baggageHeader","_ref4","currentIndex","objectKey","objectValue","baggageEntry","encodeURIComponent","newBaggageHeader","warn","objectToBaggageHeader","acc","_ref2","dscKey","dscValue","baggageHeaderToObject","keyOrValue","decodeURIComponent","trim","_ref3","TRACEPARENT_REGEXP","RegExp","propagationContextFromHeaders","sentryTrace","baggage","traceparentData","traceparent","parentSampled","matches","match","traceId","parentSpanId","extractTraceparentData","baggageObject","curr","currBaggageObject","_ref","baggageHeaderToDynamicSamplingContext","substring","spanId","sampled","dsc","generateSentryTraceHeader","sampledString","TRACE_FLAG_SAMPLED","spanToTraceContext","span","_span$spanContext","spanContext","span_id","trace_id","_spanToJSON","spanToJSON","op","parent_span_id","tags","origin","spanToTraceHeader","_span$spanContext2","spanIsSampled","spanTimeInputToSeconds","ensureTimestampInSeconds","getTime","getSpanJSON","spanIsSpanClass","traceFlags","debugIdStackParserCache","WeakMap","captureContextKeys","captureEvent","getCurrentHub","addBreadcrumb","breadcrumb","getClient","getCurrentScope","getScope","getRootSpan","transaction","getDynamicSamplingContextFromClient","client","scope","getOptions","public_key","getDsn","publicKey","user_segment","getUser","segment","emit","getDynamicSamplingContextFromSpan","txn","v7FrozenDsc","_frozenDynamicSamplingContext","_txn$metadata","metadata","maybeSampleRate","sampleRate","sample_rate","jsonSpan","description","applyScopeDataToEvent","fingerprint","breadcrumbs","sdkProcessingMetadata","extra","contexts","transactionName","cleanedExtra","cleanedTags","cleanedUser","cleanedContexts","applyDataToEvent","trace","rootSpan","applySpanToEvent","maybeArray","applyFingerprintToEvent","mergedBreadcrumbs","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","eventProcessors","attachments","propagationContext","mergeAndOverwriteScopeData","mergeVal","globalScope","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","_propagationContext","generatePropagationContext","clone","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","_client","setClient","addScopeListener","addEventProcessor","setUser","_notifyScopeListeners","getRequestSession","setRequestSession","requestSession","setTags","setTag","_extends2","setExtras","extras","setExtra","_extends3","setFingerprint","setLevel","setTransactionName","setContext","setSpan","getSpan","getTransaction","setSession","getSession","update","captureContext","scopeToMerge","scopeData","getScopeData","scopeContext","clear","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","additionalEventProcessors","setSDKProcessingMetadata","newData","setPropagationContext","getPropagationContext","captureException","syntheticException","originalException","captureMessage","SDK_VERSION","API_VERSION","parseFloat","Hub","isolationScope","_version","assignedScope","assignedIsolationScope","_stack","bindClient","_isolationScope","isOlderThan","version","top","getStackTop","setupIntegrations","pushScope","getStack","popScope","withScope","maybePromiseResult","res","getIsolationScope","_lastEventId","lastEventId","_this$getStackTop","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","configureScope","_this$getStackTop2","run","oldHub","makeMain","getIntegration","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2$environment","navigator","startingTime","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","sentry","getMainCarrier","extensions","hub","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","installedIntegrations","afterSetupIntegrations","integrations","_step","_iterator","_createForOfIteratorHelperLoose","afterAllSetup","setupIntegration","integrationIndex","indexOf","setupOnce","setup","on","preprocessEvent","processEvent","convertIntegrationFnToClass","originalFunctionToString","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","INTEGRATION_NAME","inboundFiltersIntegration","_hint","clientOptions","mergedOptions","internalOptions","allowUrls","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","_isSentryError","lastException","possibleMessages","_getPossibleEventMessages","_isIgnoredError","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","InboundFilters","frames","stacktrace","frame","filename","_getLastValidUrl","oO","SETUP_CLIENTS","functionToStringIntegration","originalFunction","FunctionToString","ignoreOnError","shouldIgnoreOnError","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","ex","setTimeout","rest","hintIsScopeOrFunction","hintIsScopeContext","parseEventHintOrCaptureContext","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","browserApiErrorsIntegration","_options","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","TryCatch","originalCallback","function","originalSend","xhr","wrapOptions","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","handlers","instrumented","addHandler","maybeInstrument","instrumentFn","triggerHandlers","typeHandlers","_oldOnErrorHandler","addGlobalErrorInstrumentationHandler","instrumentError","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","addGlobalUnhandledRejectionInstrumentationHandler","instrumentUnhandledRejection","onunhandledrejection","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","getNonErrorObjectExceptionValue","__serialized__","eventFromPlainObject","synthetic","__sentry_template_string__","__sentry_template_values__","logentry","params","maxLength","sort","includedKeys","serialized","extractExceptionKeysForMessage","captureType","getObjectClassName","globalHandlersIntegration","stackTraceLimit","_getOptions","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","_installGlobalOnErrorHandler","globalHandlerLog","_getOptions2","e2","_getUnhandledRejectionError","_installGlobalOnUnhandledRejectionHandler","GlobalHandlers","ev","ev0","ev0s","ev0sf","colno","parseInt","lineno","location","href","getLocationHref","in_app","instrumentConsole","debounceTimerID","lastCapturedEventType","lastCapturedEventTargetId","DEBOUNCE_DURATION","instrumentDOM","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","globalListener","getEventTarget","eventType","isContentEditable","shouldSkipDOMEvent","_sentryId","isSimilarToLastCapturedEvent","clearTimeout","SENTRY_XHR_DATA_KEY","addXhrInstrumentationHandler","instrumentXHR","xhrproto","originalOpen","startTimestamp","toUpperCase","parseUrl","request_headers","__sentry_own_request__","onreadystatechangeHandler","xhrInfo","readyState","status_code","endTimestamp","onreadystatechange","readyStateArgs","_len3","setRequestHeaderArgs","_key3","header","sentryXhrData","_len4","_key4","body","isNativeFetch","addFetchInstrumentationHandler","instrumentFetch","EdgeRuntime","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","resource","lastHref","addHistoryInstrumentationHandler","instrumentHistory","isChromePackagedApp","chromeVar","chrome","app","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","from","historyReplacementFunction","originalHistoryFunction","validSeverityLevels","query","fragment","host","path","protocol","search","hash","relative","MAX_ALLOWED_STRING_LENGTH","breadcrumbsIntegration","dom","category","_getConsoleBreadcrumbHandler","addClickKeypressInstrumentationHandler","componentName","serializeAttribute","element","_isEvent","_getDomBreadcrumbHandler","_getXhrBreadcrumbHandler","_getFetchBreadcrumbHandler","parsedLoc","parsedFrom","parsedTo","_getHistoryBreadcrumbHandler","_getSentryBreadcrumbHandler","Breadcrumbs","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","parser","maxValueLimit","limit","exceptions","maxValueLength","aggregateExceptionsFromError","prevExceptions","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","childError","is_exception_group","exception_id","parentId","parent_id","SPAN_METRIC_SUMMARY","linkedErrorsIntegration","LinkedErrors","httpContextIntegration","request","referrer","headers","Referer","HttpContext","_assertThisInitialized","ReferenceError","_setPrototypeOf","p","_inheritsLoose","subClass","superClass","_defineProperties","props","descriptor","prim","toPrimitive","_createClass","Constructor","protoProps","staticProps","getMetricSummaryJsonForSpan","storage","getMetricStorageForSpan","_step$value$","exportKey","summary","SpanStatus","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","setHttpStatus","httpStatus","setData","spanStatus","getSpanStatusFromHttpCode","setStatus","SpanRecorder","maxlen","_maxlen","spans","spanRecorder","Span","_traceId","_spanId","_startTime","instrumenter","_attributes","setAttributes","attributes","_name","_parentSpanId","_sampled","_status","_endTime","exclusiveTime","_exclusiveTime","_measurements","measurements","_proto2","startChild","childSpan","logMessage","_logMessage","_extends4","setAttribute","setName","updateName","isSuccess","end","toTraceparent","toContext","_getData","updateWithContext","getTraceContext","start_timestamp","_metrics_summary","profile_id","exclusive_time","isRecording","hasData","hasAttributes","string","startTime","endTime","hasTracingEnabled","maybeOptions","enableTracing","startInactiveSpan","ctx","normalizeContext","parentSpan","onlyIfParent","temporaryScope","forceTransaction","_parentSpan$spanConte","_isolationScope$getPr","ISOLATION_SCOPE_ON_START_SPAN_FIELD","SCOPE_ON_START_SPAN_FIELD","setCapturedScopesOnSpan","createChildSpanOrTransaction","Transaction","_Span","transactionContext","_hub","_metadata","_trimEnd","trimEnd","incomingDynamicSamplingContext","initSpanRecorder","setMeasurement","unit","setMetadata","newMetadata","timestampInS","_finishTransaction","getDynamicSamplingContext","setHub","getProfileId","recordDroppedEvent","finishedSpans","endTimes","current","_getCapturedScopesOnS","capturedSpanScope","capturedSpanIsolationScope","transaction_info","newName","spanMetadata","TRACING_DEFAULTS","idleTimeout","finalTimeout","heartbeatInterval","IDLE_TRANSACTION_FINISH_REASONS","IdleTransactionSpanRecorder","_SpanRecorder","_pushActivity","_popActivity","transactionSpanId","originalEnd","IdleTransaction","_Transaction","_idleHub","_idleTimeout","_finalTimeout","_heartbeatInterval","_onScope","delayAutoFinishUntilSignal","activities","_heartbeatCounter","_finished","_idleTimeoutCanceledPermanently","_beforeFinishCallbacks","_finishReason","_autoFinishAllowed","_restartIdleTimeout","endTimestampInS","spanStartedBeforeTransactionFinish","timeoutWithMarginOfError","spanEndedBeforeFinalTimeout","stringifiedSpan","registerBeforeFinishCallback","_pingHeartbeat","cancelIdleTimeout","_temp","restartOnChildSpanChange","_idleTimeoutID","setFinishReason","sendAutoFinishSignal","_beat","heartbeatString","_prevHeartbeatString","_this7","getActiveTransaction","maybeHub","errorsInstrumented","errorCallback","activeTransaction","sampleTransaction","samplingContext","Number","tracesSampler","tracesSampleRate","isValidSampleRate","rate","_startTransaction","configInstrumenter","transactionInstrumenter","_experiments","maxSpans","startIdleTransaction","onScope","tag","po","bindReporter","metric","reportAllChanges","prevValue","delta","forceReport","getNavigationEntry","__WEB_VITALS_POLYFILL__","getEntriesByType","navigation","navigationEntry","entryType","getNavigationEntryFromPerformanceTiming","getActivationStart","navEntry","activationStart","initMetric","navigationType","prerendering","rating","floor","observe","opts","PerformanceObserver","supportedEntryTypes","list","getEntries","buffered","onHidden","cb","once","onHiddenOrPageHide","visibilityState","removeEventListener","onCLS","onReport","report","sessionValue","sessionEntries","handleEntries","hadRecentInput","firstSessionEntry","lastSessionEntry","stopListening","takeRecords","firstHiddenTime","getVisibilityWatcher","Infinity","timeStamp","onFID","visibilityWatcher","handleEntry","processingStart","disconnect","interactionCountEstimate","minKnownInteractionId","maxKnownInteractionId","updateEstimate","interactionId","min","initInteractionCountPolyfill","durationThreshold","getInteractionCountForNavigation","interactionCount","longestInteractionList","longestInteractionMap","processEntry","minLongestInteraction","existingInteraction","latency","interaction","b","onINP","prevEntry","candidateInteractionIndex","inp","reportedMetricIDs","onLCP","lastEntry","capture","whenReady","onTTFB","responseStart","_previousCls","_previousFid","_previousLcp","_previousTtfb","_previousInp","addPerformanceInstrumentationHandler","instrumentPerformanceObserver","getCleanupCallback","instrumentCls","instrumentFid","instrumentLcp","instrumentTtfb","instrumentInp","addMetricObserver","previousValue","stopOnCallback","DSN_REGEX","dsnToString","dsn","withPassword","pass","port","projectId","dsnFromComponents","components","makeDsn","exec","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","find","component","isValidProtocol","validateDsn","createEnvelope","items","forEachEnvelopeItem","envelope","envelopeItem","encodeUTF8","textEncoder","TextEncoder","encode","serializeEnvelope","envHeaders","parts","append","_step2","_iterator2","itemHeaders","payload","stringifiedPayload","buffers","_step3","totalLength","buf","merged","offset","_iterator3","buffer","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","feedback","statsd","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","sdk","_metadataOrEvent$sdk","createSpanItem","isMeasurementValue","isFinite","_startChild","excluded","sourceKeys","_objectWithoutPropertiesLoose","_excluded","MAX_INT_AS_BYTES","msToSec","time","getBrowserPerformanceAPI","_lcpEntry","_clsEntry","_performanceCursor","startTrackingWebVitals","fidCallback","_ref5","clsCallback","lcpCallback","addLcpInstrumentationHandler","ttfbCallback","_ref6","INP_ENTRY_MAP","click","pointerdown","pointerup","mousedown","mouseup","touchstart","touchend","mouseover","mouseout","mouseenter","mouseleave","pointerover","pointerout","pointerenter","pointerleave","dragstart","dragend","drag","dragenter","dragleave","dragover","drop","keydown","keyup","keypress","_addPerformanceNavigationTiming","eventEnd","start","setResourceEntrySizeData","dataKey","entryVal","DEFAULT_TRACE_PROPAGATION_TARGETS","defaultRequestInstrumentationOptions","traceFetch","traceXHR","enableHTTPTimings","tracingOrigins","tracePropagationTargets","instrumentOutgoingRequests","_traceFetch$traceXHR$","shouldCreateSpanForRequest","shouldCreateSpan","shouldAttachHeadersWithTargets","shouldAttachHeaders","createdSpan","spanOrigin","shouldCreateSpanResult","_handlerData$fetchDat","fullUrl","URL","getFullURL","__span","requestSpan","sentryTraceHeader","sentryBaggageHeader","newHeaders","existingBaggageHeader","newBaggageHeaders","addTracingHeadersToFetchRequest","contentLength","contentLengthNum","endSpan","instrumentFetchRequest","addHTTPTimings","__sentry_xhr_span_id__","setRequestHeader","setHeaderOnXhr","xhrCallback","cleanup","nextHopProtocol","initiatorType","isPerformanceResourceTiming","endsWith","resourceTiming","_extractNetworkProtoc","char","_nextHopProtocol$spli","extractNetworkProtocol","timingSpanData","getAbsoluteTime","redirectStart","fetchStart","domainLookupStart","domainLookupEnd","connectStart","secureConnectionStart","connectEnd","requestStart","responseEnd","resourceTimingEntryToSpanData","DEFAULT_BROWSER_TRACING_OPTIONS","markBackgroundTransactions","routingInstrumentation","customStartTransaction","startTransactionOnPageLoad","startTransactionOnLocationChange","startingUrl","pathname","enableLongTask","enableInp","interactionsSampleRate","BrowserTracing","_hasSetTracePropagationTargets","_collectWebVitals","_interactionIdToRouteNameMapping","interactionIdtoRouteNameMapping","inpCallback","interactionIdToRouteNameMapping","_ref7","interactionType","routeName","parentContext","replayId","userDisplay","profileId","replay_id","getSampleRate","sent_at","transport","getTransport","send","_trackINP","startTrackingINP","enableInteractions","_latestRoute","_getCurrentHub","_this$options","instrumentRouting","clientOptionsTracePropagationTargets","_createRouteTransaction","onStartRouteTransaction","statusType","_registerInteractionListener","_registerInpInteractionListener","expandedContext","_this$options2","beforeNavigate","isPageloadTransaction","_propagationContextFr","getMetaContent","modifiedContext","finalContext","idleTransaction","performanceEntries","transactionStartTime","_addRequest","_addNavigationSpans","measureStartTimestamp","measureEndTimestamp","_addMeasureSpans","firstHidden","shouldRecord","resourceUrl","parsedUrl","renderBlockingStatus","_addResourceSpans","connection","effectiveType","rtt","deviceMemory","hardwareConcurrency","_trackNavigator","_addTtfbRequestTimeToMeasurements","oldValue","measurementTimestamp","normalizedValue","fidMark","cls","measurementName","size","sources","node","_tagMetricInfo","addPerformanceEntries","inflightInteractionTransaction","registerInteractionTransaction","_data","_this3$options","currentTransaction","getSource","replay","getIntegrationByName","getReplayId","currentScope","isPerformanceEventTiming","minInteractionId","metaName","selector","metaTag","querySelector","sourceFromAttributes","sourceFromData","sourceFromMetadata","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","Wrapper","SentryError","_Error","logLevel","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","tunnel","sdkInfo","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","_encodedAuth","createMetricEnvelope","metricBucketItems","tagEntries","maybeTags","metricType","serializeMetricBuckets","createMetricEnvelopeItem","ALREADY_SEEN_ERROR","BaseClient","_integrations","_integrationsInitialized","_numProcessing","_outcomes","_hooks","_dsn","_transport","transportOptions","_process","eventFromException","_captureEvent","eventMessage","promisedEvent","eventFromMessage","sendSession","getSdkMetadata","flush","timeout","metricsAggregator","_isClientDoneProcessing","clientFinished","transportFlushed","close","getEventProcessors","eventProcessor","forceInitialize","_isEnabled","_setupIntegrations","getIntegrationById","integrationId","integrationName","addIntegration","isAlreadyInstalled","sendEvent","newItem","env","packages","enhanceEventWithSdkInfo","envelopeHeaders","createEventEnvelopeHeaders","createEventEnvelope","promise","_sendEnvelope","sendResponse","createSessionEnvelope","eventOrCount","sendClientReports","count","captureAggregateMetrics","metricsEnvelope","hook","_updateSessionFromEvent","crashed","errored","sessionNonTerminal","ticked","interval","clearInterval","_prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","dist","_options$maxValueLeng","applyClientOptions","integrationNames","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","filenameDebugIdMap","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","getFinalScope","clientEventProcessors","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","normalizeEvent","prepareEvent","_processEvent","finalEvent","sentryError","isTransaction","isTransactionEvent","beforeSendLabel","dataCategory","__sentry__","beforeSend","beforeSendTransaction","spanCountBefore","spanCountBeforeProcessing","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","spanCount","droppedSpanCount","transactionInfo","_this8","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","names","applySdkMetadata","SENTRY_SDK_SOURCE","_flushOutcomes","captureUserFeedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","platform","discarded_events","DEFAULT_RETRY_AFTER","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","remove","task","$","taskProducer","drain","counter","capturedSetTimeout","makePromiseBuffer","bufferSize","rateLimits","filteredEnvelopeItems","limits","all","disabledUntil","isRateLimited","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","_limit$split","retryAfter","categories","namespaces","headerDelay","delay","headerDate","parse","parseRetryAfterHeader","updateRateLimits","__sentry__baseTransport__","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","dedupeIntegration","previousEvent","currentEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","script","crossOrigin","src","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","onClose","reportDialogClosedMessageHandler","injectionPoint","makeLogger","severityLevelFromString","CaptureConsole","levels","consoleHandler","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","replaysSessionSampleRate","replaysOnErrorSampleRate","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file diff --git a/js/dist/forum.tracing.replay.js b/js/dist/forum.tracing.replay.js index cbb2c62..5fcdf8b 100644 --- a/js/dist/forum.tracing.replay.js +++ b/js/dist/forum.tracing.replay.js @@ -1,3 +1,3 @@ /*! For license information please see forum.tracing.replay.js.LICENSE.txt */ -(()=>{var t={476:(t,e,n)=>{"use strict";function r(){return"undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&!!__SENTRY_BROWSER_BUNDLE__}function i(){return"npm"}n.d(e,{S:()=>i,n:()=>r})},538:(t,e,n)=>{"use strict";n.d(e,{KV:()=>i,l$:()=>a});var r=n(476);function i(){return!(0,r.n)()&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}function a(t,e){return t.require(e)}t=n.hmd(t)},910:(t,e,n)=>{"use strict";n.d(e,{Z1:()=>d,ph:()=>l,yW:()=>c});var r=n(538),i=n(899);t=n.hmd(t);var a=(0,i.Rf)(),o={nowSeconds:function(){return Date.now()/1e3}},s=(0,r.KV)()?function(){try{return(0,r.l$)(t,"perf_hooks").performance}catch(t){return}}():function(){var t=a.performance;if(t&&t.now)return{now:function(){return t.now()},timeOrigin:Date.now()-t.now()}}(),u=void 0===s?o:{nowSeconds:function(){return(s.timeOrigin+s.now())/1e3}},c=o.nowSeconds.bind(o),l=u.nowSeconds.bind(u),d=function(){var t=a.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i{"use strict";function r(t){return t&&t.Math==Math?t:void 0}n.d(e,{Rf:()=>a,YO:()=>o,n2:()=>i});var i="object"==typeof globalThis&&r(globalThis)||"object"==typeof window&&r(window)||"object"==typeof self&&r(self)||"object"==typeof n.g&&r(n.g)||function(){return this}()||{};function a(){return i}function o(t,e,n){var r=n||i,a=r.__SENTRY__=r.__SENTRY__||{};return a[t]||(a[t]=e())}},648:(t,e,n)=>{var r=n(288).default;function i(){"use strict";t.exports=i=function(){return e},t.exports.__esModule=!0,t.exports.default=t.exports;var e={},n=Object.prototype,a=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},u=s.iterator||"@@iterator",c=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function d(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{d({},"")}catch(t){d=function(t,e,n){return t[e]=n}}function h(t,e,n,r){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),s=new I(r||[]);return o(a,"_invoke",{value:x(t,n,s)}),a}function p(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=h;var f={};function m(){}function v(){}function _(){}var g={};d(g,u,(function(){return this}));var y=Object.getPrototypeOf,b=y&&y(y(R([])));b&&b!==n&&a.call(b,u)&&(g=b);var w=_.prototype=m.prototype=Object.create(g);function k(t){["next","throw","return"].forEach((function(e){d(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function n(i,o,s,u){var c=p(t[i],t,o);if("throw"!==c.type){var l=c.arg,d=l.value;return d&&"object"==r(d)&&a.call(d,"__await")?e.resolve(d.__await).then((function(t){n("next",t,s,u)}),(function(t){n("throw",t,s,u)})):e.resolve(d).then((function(t){l.value=t,s(l)}),(function(t){return n("throw",t,s,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(t,r){function a(){return new e((function(e,i){n(t,r,e,i)}))}return i=i?i.then(a,a):a()}})}function x(t,e,n){var r="suspendedStart";return function(i,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw a;return{value:void 0,done:!0}}for(n.method=i,n.arg=a;;){var o=n.delegate;if(o){var s=E(o,n);if(s){if(s===f)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var u=p(t,e,n);if("normal"===u.type){if(r=n.done?"completed":"suspendedYield",u.arg===f)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(r="completed",n.method="throw",n.arg=u.arg)}}}function E(t,e){var n=e.method,r=t.iterator[n];if(void 0===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=void 0,E(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),f;var i=p(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,f;var a=i.arg;return a?a.done?(e[t.resultName]=a.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,f):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,f)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function C(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function I(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function R(t){if(t){var e=t[u];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n=0;--r){var i=this.tryEntries[r],o=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=a.call(i,"catchLoc"),u=a.call(i,"finallyLoc");if(s&&u){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&a.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),f}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;C(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:R(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),f}},e}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},288:t=>{function e(n){return t.exports=e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.__esModule=!0,t.exports.default=t.exports,e(n)}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports},357:(t,e,n)=>{var r=n(648)();t.exports=r;try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var a=e[r]={id:r,loaded:!1,exports:{}};return t[r](a,a.exports,n),a.loaded=!0,a.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.hmd=t=>((t=Object.create(t)).children||(t.children=[]),Object.defineProperty(t,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+t.id)}}),t),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=Object.prototype.toString;function a(t){switch(i.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return m(t,Error)}}function o(t,e){return i.call(t)==="[object "+e+"]"}function s(t){return o(t,"ErrorEvent")}function u(t){return o(t,"DOMError")}function c(t){return o(t,"String")}function l(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function d(t){return o(t,"Object")}function h(t){return"undefined"!=typeof Event&&m(t,Event)}function p(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function f(t){return"number"==typeof t&&t!=t}function m(t,e){try{return t instanceof e}catch(t){return!1}}function v(t,e){return void 0===e&&(e=0),"string"!=typeof t||0===e||t.length<=e?t:t.slice(0,e)+"..."}function _(t,e){if(!Array.isArray(t))return"";for(var n=[],r=0;r=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(t){return null}}function S(){return S=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&o+3*i.length+n.length>=u);)i.push(n),o+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function R(t,e){var n,r,i,a,o,s=t,u=[];if(!s||!s.tagName)return"";u.push(s.tagName.toLowerCase());var l=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(l&&l.length)l.forEach((function(t){u.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&u.push("#"+s.id),(n=s.className)&&c(n))for(r=n.split(/\s+/),o=0;o"}}function z(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function j(t,e){void 0===e&&(e=40);var n=Object.keys(M(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return v(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:v(i,e)}return""}function F(t){return P(t,new Map)}function P(t,e){if(d(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,a=Object.keys(t);i=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function H(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n>t/4).toString(16)}))}function Y(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function K(t){var e=t.message,n=t.event_id;if(e)return e;var r=Y(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function X(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],a=i[0]=i[0]||{};a.value||(a.value=e||""),a.type||(a.type=n||"Error")}function V(t,e){var n=Y(t);if(n){var r=n.mechanism;if(n.mechanism=S({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=S({},r&&r.data,e.data);n.mechanism.data=i}}}function J(t){if(t&&t.__sentry_captured__)return!0;try{A(t,"__sentry_captured__",!0)}catch(t){}return!1}var $,Q=n(910),tt=["debug","info","warn","error","log","assert","trace"];$={enable:function(){},disable:function(){}},tt.forEach((function(t){$[t]=function(){}}));var et,nt="production";function rt(t){return new at((function(e){e(t)}))}function it(t){return new at((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(et||(et={}));var at=function(){var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this);try{t(this._resolve,this._reject)}catch(t){this._reject(t)}}return t.__init=function(){this._state=et.PENDING},t.__init2=function(){this._handlers=[]},t.then=function(t,n){var r=this;return new e((function(e,i){r._handlers.push([!1,function(n){if(t)try{e(t(n))}catch(t){i(t)}else e(n)},function(t){if(n)try{e(n(t))}catch(t){i(t)}else i(t)}]),r._executeHandlers()}))},t.catch=function(t){return this.then((function(t){return t}),t)},t.finally=function(t){var n=this;return new e((function(e,r){var i,a;return n.then((function(e){a=!1,i=e,t&&t()}),(function(e){a=!0,i=e,t&&t()})).then((function(){a?r(i):e(i)}))}))},t.__init3=function(){var t=this;this._resolve=function(e){t._setResult(et.RESOLVED,e)}},t.__init4=function(){var t=this;this._reject=function(e){t._setResult(et.REJECTED,e)}},t.__init5=function(){var t=this;this._setResult=function(e,n){t._state===et.PENDING&&(p(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},t.__init6=function(){var t=this;this._executeHandlers=function(){if(t._state!==et.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===et.RESOLVED&&e[1](t._value),t._state===et.REJECTED&&e[2](t._value),e[0]=!0)}))}}},e}();function ot(t,e){if(void 0===e&&(e={}),e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||(0,Q.ph)(),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:G()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=""+e.did),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{var n=t.timestamp-t.started;t.duration=n>=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}var st=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={}}t.clone=function(e){var n=new t;return e&&(n._breadcrumbs=[].concat(e._breadcrumbs),n._tags=S({},e._tags),n._extra=S({},e._extra),n._contexts=S({},e._contexts),n._user=e._user,n._level=e._level,n._span=e._span,n._session=e._session,n._transactionName=e._transactionName,n._fingerprint=e._fingerprint,n._eventProcessors=[].concat(e._eventProcessors),n._requestSession=e._requestSession,n._attachments=[].concat(e._attachments),n._sdkProcessingMetadata=S({},e._sdkProcessingMetadata)),n};var e=t.prototype;return e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{},this._session&&ot(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=S({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=S({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=S({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=S({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this.getSpan();return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;if("function"==typeof e){var n=e(this);return n instanceof t?n:this}return e instanceof t?(this._tags=S({},this._tags,e._tags),this._extra=S({},this._extra,e._extra),this._contexts=S({},this._contexts,e._contexts),e._user&&Object.keys(e._user).length&&(this._user=e._user),e._level&&(this._level=e._level),e._fingerprint&&(this._fingerprint=e._fingerprint),e._requestSession&&(this._requestSession=e._requestSession)):d(e)&&(this._tags=S({},this._tags,e.tags),this._extra=S({},this._extra,e.extra),this._contexts=S({},this._contexts,e.contexts),e.user&&(this._user=e.user),e.level&&(this._level=e.level),e.fingerprint&&(this._fingerprint=e.fingerprint),e.requestSession&&(this._requestSession=e.requestSession)),this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=S({timestamp:(0,Q.yW)()},t);return this._breadcrumbs=[].concat(this._breadcrumbs,[r]).slice(-n),this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this._attachments},e.clearAttachments=function(){return this._attachments=[],this},e.applyToEvent=function(t,e){if(void 0===e&&(e={}),this._extra&&Object.keys(this._extra).length&&(t.extra=S({},this._extra,t.extra)),this._tags&&Object.keys(this._tags).length&&(t.tags=S({},this._tags,t.tags)),this._user&&Object.keys(this._user).length&&(t.user=S({},this._user,t.user)),this._contexts&&Object.keys(this._contexts).length&&(t.contexts=S({},this._contexts,t.contexts)),this._level&&(t.level=this._level),this._transactionName&&(t.transaction=this._transactionName),this._span){t.contexts=S({trace:this._span.getTraceContext()},t.contexts);var n=this._span.transaction;if(n){t.sdkProcessingMetadata=S({dynamicSamplingContext:n.getDynamicSamplingContext()},t.sdkProcessingMetadata);var r=n.name;r&&(t.tags=S({transaction:r},t.tags))}}return this._applyFingerprint(t),t.breadcrumbs=[].concat(t.breadcrumbs||[],this._breadcrumbs),t.breadcrumbs=t.breadcrumbs.length>0?t.breadcrumbs:void 0,t.sdkProcessingMetadata=S({},t.sdkProcessingMetadata,this._sdkProcessingMetadata),this._notifyEventProcessors([].concat(ut(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=S({},this._sdkProcessingMetadata,t),this},e._notifyEventProcessors=function(t,e,n,r){var i=this;return void 0===r&&(r=0),new at((function(a,o){var s=t[r];if(null===e||"function"!=typeof s)a(e);else{var u=s(S({},e),n);p(u)?u.then((function(e){return i._notifyEventProcessors(t,e,n,r+1).then(a)})).then(null,o):i._notifyEventProcessors(t,u,n,r+1).then(a).then(null,o)}}))},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},e._applyFingerprint=function(t){var e;t.fingerprint=t.fingerprint?(e=t.fingerprint,Array.isArray(e)?e:[e]):[],this._fingerprint&&(t.fingerprint=t.fingerprint.concat(this._fingerprint)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint},t}();function ut(){return(0,E.YO)("globalEventProcessors",(function(){return[]}))}function ct(t){ut().push(t)}var lt=4,dt=function(){function t(t,e,n){void 0===e&&(e=new st),void 0===n&&(n=lt),this._version=n,this._stack=[{scope:e}],t&&this.bindClient(t)}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;i0}function bt(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return r;if(D(t))return t}catch(e){return t}var i=function(){var r,i=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var a=i.map((function(t){return bt(t,e)}));return t.apply(this,a)}catch(t){throw gt++,setTimeout((function(){gt--})),r=function(n){var r;n.addEventProcessor((function(t){return e.mechanism&&(X(t,void 0,void 0),V(t,e.mechanism)),t.extra=S({},t.extra,{arguments:i}),t})),r=t,ft().captureException(r,{captureContext:undefined})},ft().withScope(r),t}};try{for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(i[a]=t[a])}catch(t){}L(i,t),A(t,"__sentry_wrapped__",i);try{Object.getOwnPropertyDescriptor(i,"name").configurable&&Object.defineProperty(i,"name",{get:function(){return t.name}})}catch(t){}return i}var wt=["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"],kt=function(){e.__initStatic=function(){this.id="TryCatch"};var t=e.prototype;function e(t){e.prototype.__init.call(this),this._options=S({XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){this._options.setTimeout&&O(_t,"setTimeout",St),this._options.setInterval&&O(_t,"setInterval",St),this._options.requestAnimationFrame&&O(_t,"requestAnimationFrame",xt),this._options.XMLHttpRequest&&"XMLHttpRequest"in _t&&O(XMLHttpRequest.prototype,"send",Et);var t=this._options.eventTarget;t&&(Array.isArray(t)?t:wt).forEach(Tt)},e}();function St(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n2?n[2]:void 0;if(i){var a=At,o=String(i);At=o,Ft("history",{from:a,to:o})}return t.apply(this,n)}}}();break;case"error":Zt=Lt.onerror,Lt.onerror=function(t,e,n,r,i){return Ft("error",{column:r,error:i,line:n,msg:t,url:e}),!(!Zt||Zt.__SENTRY_LOADER__)&&Zt.apply(this,arguments)},Lt.onerror.__SENTRY_INSTRUMENTED__=!0;break;case"unhandledrejection":Gt=Lt.onunhandledrejection,Lt.onunhandledrejection=function(t){return Ft("unhandledrejection",t),!(Gt&&!Gt.__SENTRY_LOADER__)||Gt.apply(this,arguments)},Lt.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0;break;default:return}}function jt(t,e){Mt[t]=Mt[t]||[],Mt[t].push(e),zt(t)}function Ft(t,e){if(t&&Mt[t])for(var n,r=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Ot(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ot(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Mt[t]||[]);!(n=r()).done;){var i=n.value;try{i(e)}catch(t){}}}function Pt(t,e){return!!t&&"object"==typeof t&&!!t[e]}function Ut(t){return"string"==typeof t?t:t?Pt(t,"url")?t.url:t.toString?t.toString():"":""}var Bt,Ht,qt=1e3;function Wt(t,e){return void 0===e&&(e=!1),function(n){if(n&&Ht!==n&&!function(t){if("keypress"!==t.type)return!1;try{var e=t.target;if(!e||!e.tagName)return!0;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||e.isContentEditable)return!1}catch(t){}return!0}(n)){var r="keypress"===n.type?"input":n.type;(void 0===Bt||function(t,e){if(!t)return!0;if(t.type!==e.type)return!0;try{if(t.target!==e.target)return!0}catch(t){}return!1}(Ht,n))&&(t({event:n,name:r,global:e}),Ht=n),clearTimeout(Bt),Bt=Lt.setTimeout((function(){Bt=void 0}),qt)}}}var Zt=null,Gt=null;function Yt(t,e,n){void 0===e&&(e=100),void 0===n&&(n=1/0);try{return Xt("",t,e,n)}catch(t){return{ERROR:"**non-serializable** ("+t+")"}}}function Kt(t,e,n){void 0===e&&(e=3),void 0===n&&(n=102400);var r,i=Yt(t,e);return r=i,function(t){return~-encodeURI(t).split(/%..|./).length}(JSON.stringify(r))>n?Kt(t,e-1,n):i}function Xt(t,e,r,i,a){var o,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===a&&(o="function"==typeof WeakSet,s=o?new WeakSet:[],a=[function(t){if(o)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){v[y]="[MaxProperties ~]";break}var b=g[y];v[y]=Xt(y,b,p-1,i,a),_++}return l(e),v}function Vt(t,e){var n=$t(t,e),r={type:e&&e.name,value:te(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Jt(t,e){return{exception:{values:[Vt(t,e)]}}}function $t(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(Qt.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var Qt=/Minified React error #\d+;/i;function te(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function ee(t,e,n,r,i){var c;if(s(e)&&e.error)return Jt(t,e.error);if(u(e)||o(e,"DOMException")){var l=e;if("stack"in e)c=Jt(t,e);else{var p=l.name||(u(l)?"DOMError":"DOMException"),f=l.message?p+": "+l.message:p;X(c=ne(t,f,n,r),f)}return"code"in l&&(c.tags=S({},c.tags,{"DOMException.code":""+l.code})),c}return a(e)?Jt(t,e):d(e)||h(e)?(c=function(t,e,n,r){var i=ft().getClient(),a=i&&i.getOptions().normalizeDepth,o={exception:{values:[{type:h(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:"Non-Error "+(r?"promise rejection":"exception")+" captured with keys: "+j(e)}]},extra:{__serialized__:Kt(e,a)}};if(n){var s=$t(t,n);s.length&&(o.exception.values[0].stacktrace={frames:s})}return o}(t,e,n,i),V(c,{synthetic:!0}),c):(X(c=ne(t,e,n,r),""+e,void 0),V(c,{synthetic:!0}),c)}function ne(t,e,n,r){var i={message:e};if(r&&n){var a=$t(t,n);a.length&&(i.exception={values:[{value:e,stacktrace:{frames:a}}]})}return i}var re=function(){e.__initStatic=function(){this.id="GlobalHandlers"};var t=e.prototype;function e(t){e.prototype.__init.call(this),e.prototype.__init2.call(this),this._options=S({onerror:!0,onunhandledrejection:!0},t)}return t.__init=function(){this.name=e.id},t.__init2=function(){this._installFunc={onerror:ie,onunhandledrejection:ae}},t.setupOnce=function(){Error.stackTraceLimit=50;var t=this._options;for(var e in t){var n=this._installFunc[e];n&&t[e]&&(n(),this._installFunc[e]=void 0)}},e}();function ie(){jt("error",(function(t){var e=ue(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(re)){var a=t.msg,o=t.url,u=t.line,l=t.column,d=t.error;if(!(yt()||d&&d.__sentry_own_request__)){var h=void 0===d&&c(a)?function(t,e,n,r){var i=s(t)?t.message:t,a="Error",o=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return o&&(a=o[1],i=o[2]),oe({exception:{values:[{type:a,value:i}]}},e,n,r)}(a,o,u,l):oe(ee(r,d||a,void 0,i,!1),o,u,l);h.level="error",se(n,d,h,"onerror")}}}))}function ae(){jt("unhandledrejection",(function(t){var e=ue(),n=e[0],r=e[1],i=e[2];if(n.getIntegration(re)){var a=t;try{"reason"in t?a=t.reason:"detail"in t&&"reason"in t.detail&&(a=t.detail.reason)}catch(t){}if(yt()||a&&a.__sentry_own_request__)return!0;var o=l(a)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(a)}]}}:ee(r,a,void 0,i,!0);o.level="error",se(n,a,o,"onunhandledrejection")}}))}function oe(t,e,n,r){var i=t.exception=t.exception||{},a=i.values=i.values||[],o=a[0]=a[0]||{},s=o.stacktrace=o.stacktrace||{},u=s.frames=s.frames||[],l=isNaN(parseInt(r,10))?void 0:r,d=isNaN(parseInt(n,10))?void 0:n,h=c(e)&&e.length>0?e:function(){try{return T.document.location.href}catch(t){return""}}();return 0===u.length&&u.push({colno:l,filename:h,function:"?",in_app:!0,lineno:d}),t}function se(t,e,n,r){V(n,{handled:!1,type:r}),t.captureEvent(n,{originalException:e})}function ue(){var t=ft(),e=t.getClient(),n=e&&e.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1};return[t,n.stackParser,n.attachStacktrace]}re.__initStatic();var ce=["fatal","error","warning","log","info","debug"];function le(t){return"warn"===t?"warning":ce.includes(t)?t:"log"}function de(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var he="Breadcrumbs",pe=function(){e.__initStatic=function(){this.id=he};var t=e.prototype;function e(t){e.prototype.__init.call(this),this.options=S({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t)}return t.__init=function(){this.name=e.id},t.setupOnce=function(){var t;this.options.console&&jt("console",fe),this.options.dom&&jt("dom",(t=this.options.dom,function(e){var n,r="object"==typeof t?t.serializeAttribute:void 0,i="object"==typeof t&&"number"==typeof t.maxStringLength?t.maxStringLength:void 0;i&&i>1024&&(i=1024),"string"==typeof r&&(r=[r]);try{var a=e.event;n=function(t){return t&&!!t.target}(a)?I(a.target,{keyAttrs:r,maxStringLength:i}):I(a,{keyAttrs:r,maxStringLength:i})}catch(t){n=""}0!==n.length&&ft().addBreadcrumb({category:"ui."+e.name,message:n},{event:e.event,name:e.name,global:e.global})})),this.options.xhr&&jt("xhr",me),this.options.fetch&&jt("fetch",ve),this.options.history&&jt("history",_e)},t.addSentryBreadcrumb=function(t){this.options.sentry&&ft().addBreadcrumb({category:"sentry."+("transaction"===t.type?"transaction":"event"),event_id:t.event_id,level:t.level,message:K(t)},{event:t})},e}();function fe(t){for(var e=0;e=e)return i;var a=Vt(t,n[r]);return ye(t,e,n[r],r,[a].concat(i))}ge.__initStatic();var be=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="HttpContext"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(){ct((function(e){if(ft().getIntegration(t)){if(!_t.navigator&&!_t.location&&!_t.document)return e;var n=e.request&&e.request.url||_t.location&&_t.location.href,r=(_t.document||{}).referrer,i=(_t.navigator||{}).userAgent,a=S({},e.request&&e.request.headers,r&&{Referer:r},i&&{"User-Agent":i}),o=S({},e.request,n&&{url:n},{headers:a});return S({},e,{request:o})}return e}))},t}();function we(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function ke(t,e){return ke=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},ke(t,e)}function Se(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,ke(t,e)}be.__initStatic();var xe=function(){var t=e.prototype;function e(t){void 0===t&&(t=1e3),e.prototype.__init.call(this),this._maxlen=t}return t.__init=function(){this.spans=[]},t.add=function(t){this.spans.length>this._maxlen?t.spanRecorder=void 0:this.spans.push(t)},e}();function Ee(t){return Ee="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ee(t)}function Te(t,e){for(var n=0;n"),t.prototype.finish.call(this,e);var r=this._hub.getClient();if(r&&r.emit&&r.emit("finishTransaction",this),!0===this.sampled){var i=this.spanRecorder?this.spanRecorder.spans.filter((function(t){return t!==n&&t.endTimestamp})):[];this._trimEnd&&i.length>0&&(this.endTimestamp=i.reduce((function(t,e){return t.endTimestamp&&e.endTimestamp?t.endTimestamp>e.endTimestamp?t:e:t})).endTimestamp);var a=this.metadata,o=S({contexts:S({},this._contexts,{trace:this.getTraceContext()}),spans:i,start_timestamp:this.startTimestamp,tags:this.tags,timestamp:this.endTimestamp,transaction:this.name,type:"transaction",sdkProcessingMetadata:S({},a,{dynamicSamplingContext:this.getDynamicSamplingContext()})},a.source&&{transaction_info:{source:a.source}});return Object.keys(this._measurements).length>0&&(o.measurements=this._measurements),this._hub.captureEvent(o)}r&&r.recordDroppedEvent("sample_rate","transaction")}},e.toContext=function(){return F(S({},t.prototype.toContext.call(this),{name:this.name,trimEnd:this._trimEnd}))},e.updateWithContext=function(e){return t.prototype.updateWithContext.call(this,e),this.name=e.name||"",this._trimEnd=e.trimEnd,this},e.getDynamicSamplingContext=function(){if(this._frozenDynamicSamplingContext)return this._frozenDynamicSamplingContext;var t=this._hub||ft(),e=t&&t.getClient();if(!e)return{};var n=e.getOptions()||{},r=n.environment,i=n.release,a=(e.getDsn()||{}).publicKey,o=this.metadata.sampleRate,s=void 0!==o?o.toString():void 0,u=(t.getScope().getUser()||{}).segment,c=this.metadata.source,l=c&&"url"!==c?this.name:void 0,d=F({environment:r||nt,release:i,transaction:l,user_segment:u,public_key:a,trace_id:this.traceId,sample_rate:s});return e.emit&&e.emit("createDsc",d),d},e.setHub=function(t){this._hub=t},Ce(n,[{key:"name",get:function(){return this._name},set:function(t){this.setName(t)}}]),n}(function(){var t=e.prototype;function e(t){if(e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this),e.prototype.__init7.call(this),!t)return this;t.traceId&&(this.traceId=t.traceId),t.spanId&&(this.spanId=t.spanId),t.parentSpanId&&(this.parentSpanId=t.parentSpanId),"sampled"in t&&(this.sampled=t.sampled),t.op&&(this.op=t.op),t.description&&(this.description=t.description),t.data&&(this.data=t.data),t.tags&&(this.tags=t.tags),t.status&&(this.status=t.status),t.startTimestamp&&(this.startTimestamp=t.startTimestamp),t.endTimestamp&&(this.endTimestamp=t.endTimestamp),t.instrumenter&&(this.instrumenter=t.instrumenter)}return t.__init2=function(){this.traceId=G()},t.__init3=function(){this.spanId=G().substring(16)},t.__init4=function(){this.startTimestamp=(0,Q.ph)()},t.__init5=function(){this.tags={}},t.__init6=function(){this.data={}},t.__init7=function(){this.instrumenter="sentry"},t.startChild=function(t){var n=new e(S({},t,{parentSpanId:this.spanId,sampled:this.sampled,traceId:this.traceId}));return n.spanRecorder=this.spanRecorder,n.spanRecorder&&n.spanRecorder.add(n),n.transaction=this.transaction,n},t.setTag=function(t,e){var n;return this.tags=S({},this.tags,((n={})[t]=e,n)),this},t.setData=function(t,e){var n;return this.data=S({},this.data,((n={})[t]=e,n)),this},t.setStatus=function(t){return this.status=t,this},t.setHttpStatus=function(t){this.setTag("http.status_code",String(t));var e=function(t){if(t<400&&t>=100)return"ok";if(t>=400&&t<500)switch(t){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(t>=500&&t<600)switch(t){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"}(t);return"unknown_error"!==e&&this.setStatus(e),this},t.isSuccess=function(){return"ok"===this.status},t.finish=function(t){this.endTimestamp="number"==typeof t?t:(0,Q.ph)()},t.toTraceparent=function(){var t="";return void 0!==this.sampled&&(t=this.sampled?"-1":"-0"),this.traceId+"-"+this.spanId+t},t.toContext=function(){return F({data:this.data,description:this.description,endTimestamp:this.endTimestamp,op:this.op,parentSpanId:this.parentSpanId,sampled:this.sampled,spanId:this.spanId,startTimestamp:this.startTimestamp,status:this.status,tags:this.tags,traceId:this.traceId})},t.updateWithContext=function(t){return this.data=t.data||{},this.description=t.description,this.endTimestamp=t.endTimestamp,this.op=t.op,this.parentSpanId=t.parentSpanId,this.sampled=t.sampled,this.spanId=t.spanId||this.spanId,this.startTimestamp=t.startTimestamp||this.startTimestamp,this.status=t.status,this.tags=t.tags||{},this.traceId=t.traceId||this.traceId,this},t.getTraceContext=function(){return F({data:Object.keys(this.data).length>0?this.data:void 0,description:this.description,op:this.op,parent_span_id:this.parentSpanId,span_id:this.spanId,status:this.status,tags:Object.keys(this.tags).length>0?this.tags:void 0,trace_id:this.traceId})},t.toJSON=function(){return F({data:Object.keys(this.data).length>0?this.data:void 0,description:this.description,op:this.op,parent_span_id:this.parentSpanId,span_id:this.spanId,start_timestamp:this.startTimestamp,status:this.status,tags:Object.keys(this.tags).length>0?this.tags:void 0,timestamp:this.endTimestamp,trace_id:this.traceId})},e}());function Re(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._beforeFinishCallbacks);!(r=i()).done;)(0,r.value)(this,e);this.spanRecorder.spans=this.spanRecorder.spans.filter((function(t){return t.spanId===n.spanId||(t.endTimestamp||(t.endTimestamp=e,t.setStatus("cancelled")),t.startTimestamp=3?(this.setStatus("deadline_exceeded"),this._finishReason=Ae[0],this.finish()):this._pingHeartbeat()}},e._pingHeartbeat=function(){var t=this;setTimeout((function(){t._beat()}),this._heartbeatInterval)},n}(Ie);function Me(t){var e=ft().getClient(),n=t||e&&e.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}function Ne(t){return(t||ft()).getScope().getTransaction()}var ze=!1;function je(){var t=Ne();t&&t.setStatus("internal_error")}function Fe(){var t=this.getScope().getSpan();return t?{"sentry-trace":t.toTraceparent()}:{}}function Pe(t,e,n){return Me(e)?void 0!==t.sampled?(t.setMetadata({sampleRate:Number(t.sampled)}),t):("function"==typeof e.tracesSampler?(i=e.tracesSampler(n),t.setMetadata({sampleRate:Number(i)})):void 0!==n.parentSampled?i=n.parentSampled:void 0!==e.tracesSampleRate?(i=e.tracesSampleRate,t.setMetadata({sampleRate:Number(i)})):(i=1,t.setMetadata({sampleRate:i})),f(r=i)||"number"!=typeof r&&"boolean"!=typeof r||r<0||r>1||!i?(t.sampled=!1,t):(t.sampled=Math.random()Ge?t:o}),"")}(Object.entries(t).reduce((function(t,e){var n=e[0],r=e[1];return r&&(t[""+We+n]=r),t}),{}))}function Ke(t){return t.split(",").map((function(t){return t.split("=").map((function(t){return decodeURIComponent(t.trim())}))})).reduce((function(t,e){var n=e[0],r=e[1];return t[n]=r,t}),{})}var Xe=E.n2,Ve=function(t,e,n){var r,i;return function(a){e.value>=0&&(a||n)&&((i=e.value-(r||0))||void 0===r)&&(r=e.value,e.delta=i,t(e))}},Je=function(){return Xe.__WEB_VITALS_POLYFILL__?Xe.performance&&(performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]||function(){var t=Xe.performance.timing,e=Xe.performance.navigation.type,n={entryType:"navigation",startTime:0,type:2==e?"back_forward":1===e?"reload":"navigate"};for(var r in t)"navigationStart"!==r&&"toJSON"!==r&&(n[r]=Math.max(t[r]-t.navigationStart,0));return n}()):Xe.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},$e=function(){var t=Je();return t&&t.activationStart||0},Qe=function(t,e){var n=Je(),r="navigate";return n&&(r=Xe.document.prerendering||$e()>0?"prerender":n.type.replace(/_/g,"-")),{name:t,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-"+Date.now()+"-"+(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},tn=function(t,e,n){try{if(PerformanceObserver.supportedEntryTypes.includes(t)){var r=new PerformanceObserver((function(t){e(t.getEntries())}));return r.observe(Object.assign({type:t,buffered:!0},n||{})),r}}catch(t){}},en=function(t,e){var n=function n(r){"pagehide"!==r.type&&"hidden"!==Xe.document.visibilityState||(t(r),e&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},nn=-1,rn=function(){return nn<0&&(nn="hidden"!==Xe.document.visibilityState||Xe.document.prerendering?1/0:0,en((function(t){var e=t.timeStamp;nn=e}),!0)),{get firstHiddenTime(){return nn}}},an={},on=["startTimestamp"];function sn(t){return"number"==typeof t&&isFinite(t)}function un(t,e){var n=e.startTimestamp,r=function(t,e){if(null==t)return{};var n,r,i={},a=Object.keys(t);for(r=0;r=0||(i[n]=t[n]);return i}(e,on);return n&&t.startTimestamp>n&&(t.startTimestamp=n),t.startChild(S({startTimestamp:n},r))}function cn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return ln(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ln(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function ln(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nn.value&&(n.value=r,n.entries=i,e&&e())}}))},o=tn("layout-shift",a);if(o){e=Ve(t,n);var s=function(){a(o.takeRecords()),e(!0)};return en(s),s}}((function(t){var e=t.entries.pop();e&&(vn.cls={value:t.value,unit:""},fn=e)})),c=function(t){var e,n=rn(),r=Qe("LCP"),i=function(t){var i=t[t.length-1];if(i){var a=Math.max(i.startTime-$e(),0);a0&&a.setData("http.response_content_length",s)}else t.error&&a.setStatus("internal_error");a.finish(),delete r[i]}}else{var u=ft().getScope(),c=u&&u.getSpan(),l=c&&c.transaction;if(c&&l){var d=t.fetchData,h=d.method,p=d.url,f=c.startChild({data:{url:p,type:"fetch","http.method":h},description:h+" "+p,op:"http.client"});t.fetchData.__span=f.spanId,r[f.spanId]=f;var v=t.args[0];t.args[1]=t.args[1]||{};var _=t.args[1];n(t.fetchData.url)&&(_.headers=function(t,e,n,r){var i=Ye(e),a=n.toTraceparent(),o="undefined"!=typeof Request&&m(t,Request)?t.headers:r.headers;if(o){if("undefined"!=typeof Headers&&m(o,Headers)){var s=new Headers(o);return s.append("sentry-trace",a),i&&s.append(qe,i),s}if(Array.isArray(o)){var u=[].concat(o,[["sentry-trace",a]]);return i&&u.push([qe,i]),u}var c="baggage"in o?o.baggage:void 0,l=[];return Array.isArray(c)?l.push.apply(l,c):c&&l.push(c),i&&l.push(i),S({},o,{"sentry-trace":a,baggage:l.length>0?l.join(","):void 0})}return{"sentry-trace":a,baggage:i}}(v,l.getDynamicSamplingContext(),f,_))}}}(t,s,u,c)})),r&&jt("xhr",(function(t){!function(t,e,n,r){var i=t.xhr,a=i&&i[Dt];if(!(!Me()||i&&i.__sentry_own_request__)&&i&&a&&e(a.url))if(t.endTimestamp){var o=i.__sentry_xhr_span_id__;if(!o)return;var s=r[o];s&&(s.setHttpStatus(a.status_code),s.finish(),delete r[o])}else{var u=ft().getScope(),c=u&&u.getSpan(),l=c&&c.transaction;if(c&&l){var d=c.startChild({data:S({},a.data,{type:"xhr","http.method":a.method,url:a.url}),description:a.method+" "+a.url,op:"http.client"});if(i.__sentry_xhr_span_id__=d.spanId,r[i.__sentry_xhr_span_id__]=d,i.setRequestHeader&&n(a.url))try{i.setRequestHeader("sentry-trace",d.toTraceparent());var h=Ye(l.getDynamicSamplingContext());h&&i.setRequestHeader(qe,h)}catch(t){}}}}(t,s,u,c)}))}({traceFetch:u,traceXHR:c,tracePropagationTargets:l,shouldCreateSpanForRequest:d})},t._createRouteTransaction=function(t){var e=this;if(this._getCurrentHub){var n=this.options,r=n.beforeNavigate,i=n.idleTimeout,a=n.finalTimeout,o=n.heartbeatInterval,s="pageload"===t.op,u=s?Sn("sentry-trace"):null,l=s?Sn("baggage"):null,d=u?function(t){var e,n=t.match(He);if(t&&n)return"1"===n[3]?e=!0:"0"===n[3]&&(e=!1),{traceId:n[1],parentSampled:e,parentSpanId:n[2]}}(u):void 0,h=l?function(t){if(c(t)||Array.isArray(t)){var e={};if(Array.isArray(t))e=t.reduce((function(t,e){return S({},t,Ke(e))}),{});else{if(!t)return;e=Ke(t)}var n=Object.entries(e).reduce((function(t,e){var n=e[0],r=e[1];return n.match(Ze)&&(t[n.slice(We.length)]=r),t}),{});return Object.keys(n).length>0?n:void 0}}(l):void 0,p=S({},t,d,{metadata:S({},t.metadata,{dynamicSamplingContext:d&&!h?{}:h}),trimEnd:!0}),f="function"==typeof r?r(p):p,m=void 0===f?S({},p,{sampled:!1}):f;m.metadata=m.name!==p.name?S({},m.metadata,{source:"custom"}):m.metadata,this._latestRouteName=m.name,this._latestRouteSource=m.metadata&&m.metadata.source,m.sampled;var v=Be(this._getCurrentHub(),m,i,a,!0,{location:Xe.location},o);return v.registerBeforeFinishCallback((function(t){e._collectWebVitals(),function(t){var e=hn();if(e&&Xe.performance.getEntries&&Q.Z1){var n,r,i=dn(Q.Z1),a=e.getEntries();if(a.slice(mn).forEach((function(e){var a=dn(e.startTime),o=dn(e.duration);if(!("navigation"===t.op&&i+a=t.startTimestamp)){var n=vn[e].value,r=i+dn(n),a=Math.abs(1e3*(r-t.startTimestamp));vn[e].value=a}}));var o=vn["mark.fid"];o&&vn.fid&&(un(t,{description:"first input delay",endTimestamp:o.value+dn(vn.fid.value),op:"ui.action",startTimestamp:o.value}),delete vn["mark.fid"]),"fcp"in vn||delete vn.cls,Object.keys(vn).forEach((function(e){t.setMeasurement(e,vn[e].value,vn[e].unit)})),function(t){pn&&(pn.element&&t.setTag("lcp.element",I(pn.element)),pn.id&&t.setTag("lcp.id",pn.id),pn.url&&t.setTag("lcp.url",pn.url.trim().slice(0,200)),t.setTag("lcp.size",pn.size)),fn&&fn.sources&&fn.sources.forEach((function(e,n){return t.setTag("cls.source."+(n+1),I(e.node))}))}(t)}pn=void 0,fn=void 0,vn={}}}(t)})),v}},t._registerInteractionListener=function(){var t,e=this,n=function(){var n=e.options,r=n.idleTimeout,i=n.finalTimeout,a=n.heartbeatInterval,o=Ne();if(!(o&&o.op&&["navigation","pageload"].includes(o.op))&&(t&&(t.setFinishReason("interactionInterrupted"),t.finish(),t=void 0),e._getCurrentHub&&e._latestRouteName)){var s=e._getCurrentHub(),u=Xe.location,c={name:e._latestRouteName,op:"ui.action.click",trimEnd:!0,metadata:{source:e._latestRouteSource||"url"}};t=Be(s,c,r,i,!0,{location:u},a)}};["click"].forEach((function(t){addEventListener(t,n,{once:!1,capture:!0})}))},e}();function Sn(t){var e,n=(e="meta[name="+t+"]",T.document&&T.document.querySelector?T.document.querySelector(e):null);return n?n.getAttribute("content"):null}function xn(t){return xn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},xn(t)}function En(t,e,n){return En=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}()?Reflect.construct.bind():function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&ke(i,n.prototype),i},En.apply(null,arguments)}function Tn(t){var e="function"==typeof Map?new Map:void 0;return Tn=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return En(t,arguments,xn(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),ke(r,t)},Tn(t)}function Cn(t,e,n,r,i,a,o){try{var s=t[a](o),u=s.value}catch(t){return void n(t)}s.done?e(u):Promise.resolve(u).then(r,i)}function In(t){return function(){var e=this,n=arguments;return new Promise((function(r,i){var a=t.apply(e,n);function o(t){Cn(a,r,i,o,s,"next",t)}function s(t){Cn(a,r,i,o,s,"throw",t)}o(void 0)}))}}var Rn=n(357),On=n.n(Rn);function An(t,e,n,r){var i=t.normalizeDepth,a=void 0===i?3:i,o=t.normalizeMaxBreadth,s=void 0===o?1e3:o,u=S({},e,{event_id:e.event_id||n.event_id||G(),timestamp:e.timestamp||(0,Q.yW)()}),c=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,a=e.maxValueLength,o=void 0===a?250:a;"environment"in t||(t.environment="environment"in e?n:nt),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=v(t.message,o));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=v(s.value,o));var u=t.request;u&&u.url&&(u.url=v(u.url,o))}(u,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(u,c),void 0===e.type&&function(t,e){var n,r=E.n2._sentryDebugIds;if(r){var i=Ln.get(e);i?n=i:(n=new Map,Ln.set(e,n));var a=Object.keys(r).reduce((function(t,i){var a,o=n.get(i);o?a=o:(a=e(i),n.set(i,a));for(var s=a.length-1;s>=0;s--){var u=a[s];if(u.filename){t[u.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=a[t.filename])}))}))}catch(t){}}}(u,t.stackParser);var l=r;n.captureContext&&(l=st.clone(l).update(n.captureContext));var d=rt(u);if(l){if(l.getAttachments){var h=[].concat(n.attachments||[],l.getAttachments());h.length&&(n.attachments=h)}d=l.applyToEvent(u,n)}return d.then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof a&&a>0?function(t,e,n){if(!t)return null;var r=S({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return S({},t,t.data&&{data:Yt(t.data,e,n)})}))},t.user&&{user:Yt(t.user,e,n)},t.contexts&&{contexts:Yt(t.contexts,e,n)},t.extra&&{extra:Yt(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=Yt(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){return t.data&&(t.data=Yt(t.data,e,n)),t}))),r}(t,a,s):t}))}var Ln=new WeakMap,Dn=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function Mn(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,a=t.port,o=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(a?":"+a:"")+"/"+(r?r+"/":r)+o}function Nn(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function zn(t){var e="string"==typeof t?function(t){var e=Dn.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],a=n[2],o=void 0===a?"":a,s=n[3],u=n[4],c=void 0===u?"":u,l="",d=n[5],h=d.split("/");if(h.length>1&&(l=h.slice(0,-1).join("/"),d=h.pop()),d){var p=d.match(/^\d+/);p&&(d=p[0])}return Nn({host:s,pass:o,path:l,projectId:d,port:c,protocol:r,publicKey:i})}console.error("Invalid Sentry Dsn: "+t)}(t):Nn(t);if(e)return e}function jn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Fn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Fn(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Fn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Jn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n-1?t.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,"$1\\$2"):t}var Sr=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,xr=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,Er=/^(data:)([^,]*),(.*)/i;function Tr(t,e){return(t||"").replace(Sr,(function(t,n,r,i,a,o){var s,u=r||a||o,c=n||i||"";if(!u)return t;if(!xr.test(u))return"url("+c+u+c+")";if(Er.test(u))return"url("+c+u+c+")";if("/"===u[0])return"url("+c+(((s=e).indexOf("//")>-1?s.split("/").slice(0,3).join("/"):s.split("/")[0]).split("?")[0]+u)+c+")";var l=e.split("/"),d=u.split("/");l.pop();for(var h,p=Vn(d);!(h=p()).done;){var f=h.value;"."!==f&&(".."===f?l.pop():l.push(f))}return"url("+c+l.join("/")+c+")"}))}var Cr,Ir,Rr,Or,Ar,Lr,Dr=/^[^ \t\n\r\u000c]+/,Mr=/^[, \t\n\r\u000c]+/;function Nr(t,e){if(!e||""===e.trim())return e;var n=t.createElement("a");return n.href=e,n.href}function zr(t){return Boolean("svg"===t.tagName||t.ownerSVGElement)}function jr(){var t=document.createElement("a");return t.href="",t.href}function Fr(t,e,n,r,i,a,o,s){if(!i)return i;var u=r.toLowerCase(),c=n.toLowerCase();return"src"===u||"href"===u||"xlink:href"===u&&"#"!==i[0]?Nr(t,i):"background"!==u||"table"!==c&&"td"!==c&&"th"!==c?"srcset"===u?function(t,e){if(""===e.trim())return e;var n=0;function r(t){var r,i=t.exec(e.substring(n));return i?(r=i[0],n+=r.length,r):""}for(var i=[];r(Mr),!(n>=e.length);){var a=r(Dr);if(","===a.slice(-1))a=Nr(t,a.substring(0,a.length-1)),i.push(a);else{var o="";a=Nr(t,a);for(var s=!1;;){var u=e.charAt(n);if(""===u){i.push((a+o).trim());break}if(s)")"===u&&(s=!1);else{if(","===u){n+=1,i.push((a+o).trim());break}"("===u&&(s=!0)}o+=u,n+=1}}}return i.join(", ")}(t,i):"style"===u?Tr(i,jr()):"object"===c&&"data"===u?Nr(t,i):a&&function(t,e,n,r){return(!r||!t.matches(r))&&(["placeholder","title","aria-label"].indexOf(e)>-1||"input"===n&&"value"===e&&t.hasAttribute("type")&&["submit","button"].indexOf(t.getAttribute("type").toLowerCase())>-1)}(e,u,c,o)?s?s(i):yr(i):i:Nr(t,i)}function Pr(t,e,n,r,i){if(!t)return!1;if(t.nodeType!==t.ELEMENT_NODE)return Pr(t.parentNode,e,n,r,i);if(r&&(t.matches(r)||t.closest(r)))return!1;if(i)return!0;if("string"==typeof e){if(t.classList.contains(e))return!0}else for(var a=0;ae?(r&&(clearTimeout(r),r=null),i=o,t.apply(u,c)):r||!1===n.trailing||(r=setTimeout((function(){i=!1===n.leading?0:Date.now(),r=null,t.apply(u,c)}),s))}}function Yr(t,e,n,r,i){void 0===i&&(i=window);var a=i.Object.getOwnPropertyDescriptor(t,e);return i.Object.defineProperty(t,e,r?n:{set:function(t){var e=this;setTimeout((function(){n.set.call(e,t)}),0),a&&a.set&&a.set.call(this,t)}}),function(){return Yr(t,e,a||{},!0)}}function Kr(t,e,n){try{if(!(e in t))return function(){};var r=t[e],i=n(r);return"function"==typeof i&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:r}})),t[e]=i,function(){t[e]=r}}catch(t){return function(){}}}function Xr(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Vr(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Jr(t,e,n,r){if(!t)return!1;if(t.nodeType===t.ELEMENT_NODE){var i=!1,a=r&&t.matches(r);return"string"==typeof e?i=void 0!==t.closest?!a&&null!==t.closest("."+e):!a&&t.classList.contains(e):!a&&t.classList.forEach((function(t){e.test(t)&&(i=!0)})),!i&&n&&(i=t.matches(n)),!a&&i||Jr(t.parentNode,e,n,r)}return t.nodeType,t.TEXT_NODE,Jr(t.parentNode,e,n,r)}function $r(t){return"__sn"in t&&t.__sn.id===gr}function Qr(t,e){if(ur(t))return!1;var n=e.getId(t);return!e.has(n)||(!t.parentNode||t.parentNode.nodeType!==t.DOCUMENT_NODE)&&(!t.parentNode||Qr(t.parentNode,e))}function ti(t){return Boolean(t.changedTouches)}function ei(t){return"__sn"in t&&t.__sn.type===$n.Element&&"iframe"===t.__sn.tagName}function ni(t){return Boolean(null==t?void 0:t.shadowRoot)}function ri(t){return"__ln"in t}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Zr=new Proxy(Zr,{get:function(t,e,n){return"map"===e&&console.error(Wr),Reflect.get(t,e,n)}}));var ii=function(){function t(){this.length=0,this.head=null}var e=t.prototype;return e.get=function(t){if(t>=this.length)throw new Error("Position outside of list range");for(var e=this.head,n=0;n=0;m--){var v=n.get(m);if(v){var _=t.mirror.getId(v.value.parentNode),g=r(v.value);if(-1!==_&&-1!==g){h=v;break}}}if(!h){for(;n.head;)n.removeNode(n.head.value);break}d=h.previous,n.removeNode(h.value),i(h.value)}var y={texts:t.texts.map((function(e){return{id:t.mirror.getId(e.node),value:e.value}})).filter((function(e){return t.mirror.has(e.id)})),attributes:t.attributes.map((function(e){return{id:t.mirror.getId(e.node),attributes:e.attributes}})).filter((function(e){return t.mirror.has(e.id)})),removes:t.removes,adds:e};(y.texts.length||y.attributes.length||y.removes.length||y.adds.length)&&(t.texts=[],t.attributes=[],t.removes=[],t.addedSet=new Set,t.movedSet=new Set,t.droppedSet=new Set,t.movedMap={},t.mutationCb(y))}},this.processMutation=function(e){if(!$r(e.target))switch(e.type){case"characterData":var n=e.target.textContent;Jr(e.target,t.blockClass,t.blockSelector,t.unblockSelector)||n===e.oldValue||t.texts.push({value:Pr(e.target,t.maskTextClass,t.maskTextSelector,t.unmaskTextSelector,t.maskAllText)&&n?t.maskTextFn?t.maskTextFn(n):n.replace(/[\S]/g,"*"):n,node:e.target});break;case"attributes":var r=e.target,i=r.getAttribute(e.attributeName);if("value"===e.attributeName&&(i=lr({input:r,maskInputSelector:t.maskInputSelector,unmaskInputSelector:t.unmaskInputSelector,maskInputOptions:t.maskInputOptions,tagName:r.tagName,type:r.getAttribute("type"),value:i,maskInputFn:t.maskInputFn})),Jr(e.target,t.blockClass,t.blockSelector,t.unblockSelector)||i===e.oldValue)return;var a=t.attributes.find((function(t){return t.node===e.target}));if(a||(a={node:e.target,attributes:{}},t.attributes.push(a)),"type"===e.attributeName&&"INPUT"===r.tagName&&"password"===(e.oldValue||"").toLowerCase()&&r.setAttribute("data-rr-is-password","true"),"style"===e.attributeName){var o=t.doc.createElement("span");e.oldValue&&o.setAttribute("style",e.oldValue),void 0!==a.attributes.style&&null!==a.attributes.style||(a.attributes.style={});try{for(var s=a.attributes.style,u=0,c=Array.from(r.style);u>2],i+=Ei[(3&n[e])<<4|n[e+1]>>4],i+=Ei[(15&n[e+1])<<2|n[e+2]>>6],i+=Ei[63&n[e+2]];return r%3==2?i=i.substring(0,i.length-1)+"=":r%3==1&&(i=i.substring(0,i.length-2)+"=="),i}(t);return{rr_type:r,base64:i}}return t instanceof DataView?{rr_type:t.constructor.name,args:[Oi(t.buffer,e,n),t.byteOffset,t.byteLength]}:t instanceof HTMLImageElement?{rr_type:t.constructor.name,src:t.src}:t instanceof ImageData?{rr_type:t.constructor.name,args:[Oi(t.data,e,n),t.width,t.height]}:Li(t,e)||"object"==typeof t?{rr_type:t.constructor.name,index:Ri(t,e,n)}:t}var Ai=function(t,e,n){return[].concat(t).map((function(t){return Oi(t,e,n)}))},Li=function(t,e){var n=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter((function(t){return"function"==typeof e[t]}));return Boolean(n.find((function(n){return t instanceof e[n]})))};function Di(t,e,n,r,i,a,o,s){for(var u,c=[],l=function(){var l=u.value;try{if("function"!=typeof t[l])return"continue";var d=Kr(t,l,(function(u){return function(){for(var c=arguments.length,d=new Array(c),h=0;h1?a-1:0),s=1;s=i,s=r&&t.timestamp-$.timestamp>r;(o||s)&&Ni(!0)}};var nt=function(t){Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.Mutation},t)}))},rt=function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.Scroll},t)}))},it=function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.CanvasMutation},t)}))},at=new Si({mutationCb:nt}),ot=new zi({recordCanvas:U,mutationCb:it,win:window,blockClass:o,blockSelector:u,unblockSelector:l,mirror:Fi}),st=new xi({mutationCb:nt,scrollCb:rt,bypassOptions:{onMutation:V,blockClass:o,blockSelector:u,unblockSelector:l,maskTextClass:v,maskTextSelector:g,unmaskTextSelector:k,maskInputSelector:b,unmaskInputSelector:x,inlineStylesheet:T,maskAllText:I,maskInputOptions:Q,maskTextFn:D,maskInputFn:L,recordCanvas:U,inlineImages:G,sampling:j,slimDOMOptions:tt,iframeManager:at,canvasManager:ot},mirror:Fi});Ni=function(t){var e,n,r,i;void 0===t&&(t=!1),Mi(ji({type:Cr.Meta,data:{href:window.location.href,width:Vr(),height:Xr()}}),t),hi.forEach((function(t){return t.lock()}));var a=function(t,e){var n=e||{},r=n.blockClass,i=n.blockSelector,a=n.unblockSelector,o=n.maskTextClass,s=n.maskTextSelector,u=n.unmaskTextSelector,c=n.inlineStylesheet,l=n.inlineImages,d=n.recordCanvas,h=n.maskInputSelector,p=n.unmaskInputSelector,f=n.maskAllText,m=n.maskAllInputs,v=void 0!==m&&m,_=n.slimDOM,g=void 0!==_&&_,y=n.keepIframeSrcFn,b={};return[Br(t,{doc:t,map:b,blockClass:void 0===r?"rr-block":r,blockSelector:void 0===i?null:i,unblockSelector:void 0===a?null:a,maskTextClass:void 0===o?"rr-mask":o,maskTextSelector:void 0===s?null:s,unmaskTextSelector:void 0===u?null:u,skipChild:!1,inlineStylesheet:void 0===c||c,maskInputSelector:void 0===h?null:h,unmaskInputSelector:void 0===p?null:p,maskAllText:void 0!==f&&f,maskInputOptions:!0===v?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0}:!1===v?{}:v,maskTextFn:n.maskTextFn,maskInputFn:n.maskInputFn,slimDOMOptions:!0===g||"all"===g?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===g,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===g?{}:g,dataURLOptions:n.dataURLOptions,inlineImages:void 0!==l&&l,recordCanvas:void 0!==d&&d,preserveWhiteSpace:n.preserveWhiteSpace,onSerialize:n.onSerialize,onIframeLoad:n.onIframeLoad,iframeLoadTimeout:n.iframeLoadTimeout,keepIframeSrcFn:void 0===y?function(){return!1}:y}),b]}(document,{blockClass:o,blockSelector:u,unblockSelector:l,maskTextClass:v,maskTextSelector:g,unmaskTextSelector:k,maskInputSelector:b,unmaskInputSelector:x,inlineStylesheet:T,maskAllText:I,maskAllInputs:Q,maskTextFn:D,slimDOM:tt,recordCanvas:U,inlineImages:G,onSerialize:function(t){ei(t)&&at.addIframe(t),ni(t)&&st.addShadowRoot(t.shadowRoot,document)},onIframeLoad:function(t,e){at.attachIframe(t,e),st.observeAttachShadow(t)},keepIframeSrcFn:X}),s=a[0],c=a[1];if(!s)return console.warn("Failed to snapshot the document");Fi.map=c,Mi(ji({type:Cr.FullSnapshot,data:{node:s,initialOffset:{left:void 0!==window.pageXOffset?window.pageXOffset:(null===document||void 0===document?void 0:document.documentElement.scrollLeft)||(null===(n=null===(e=null===document||void 0===document?void 0:document.body)||void 0===e?void 0:e.parentElement)||void 0===n?void 0:n.scrollLeft)||(null===document||void 0===document?void 0:document.body.scrollLeft)||0,top:void 0!==window.pageYOffset?window.pageYOffset:(null===document||void 0===document?void 0:document.documentElement.scrollTop)||(null===(i=null===(r=null===document||void 0===document?void 0:document.body)||void 0===r?void 0:r.parentElement)||void 0===i?void 0:i.scrollTop)||(null===document||void 0===document?void 0:document.body.scrollTop)||0}}})),hi.forEach((function(t){return t.unlock()}))};try{var ut=[];ut.push(qr("DOMContentLoaded",(function(){Mi(ji({type:Cr.DomContentLoaded,data:{}}))})));var ct=function(t){var e;return di(bi)({onMutation:V,mutationCb:nt,mousemoveCb:function(t,e){return Mi(ji({type:Cr.IncrementalSnapshot,data:{source:e,positions:t}}))},mouseInteractionCb:function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.MouseInteraction},t)}))},scrollCb:rt,viewportResizeCb:function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.ViewportResize},t)}))},inputCb:function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.Input},t)}))},mediaInteractionCb:function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.MediaInteraction},t)}))},styleSheetRuleCb:function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.StyleSheetRule},t)}))},styleDeclarationCb:function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.StyleDeclaration},t)}))},canvasMutationCb:it,fontCb:function(t){return Mi(ji({type:Cr.IncrementalSnapshot,data:Object.assign({source:Ir.Font},t)}))},blockClass:o,ignoreClass:h,ignoreSelector:f,maskTextClass:v,maskTextSelector:g,unmaskTextSelector:k,maskInputSelector:b,unmaskInputSelector:x,maskInputOptions:Q,inlineStylesheet:T,sampling:j,recordCanvas:U,inlineImages:G,userTriggeredOnInput:H,collectFonts:W,doc:t,maskAllText:I,maskInputFn:L,maskTextFn:D,blockSelector:u,unblockSelector:l,slimDOMOptions:tt,mirror:Fi,iframeManager:at,shadowDomManager:st,canvasManager:ot,plugins:(null===(e=null==Y?void 0:Y.filter((function(t){return t.observer})))||void 0===e?void 0:e.map((function(t){return{observer:t.observer,options:t.options,callback:function(e){return Mi(ji({type:Cr.Plugin,data:{plugin:t.name,payload:e}}))}}})))||[]},M)};at.addLoadListener((function(t){try{ut.push(ct(t.contentDocument))}catch(t){console.warn(t)}}));var lt=function(){Ni(),ut.push(ct(document))};return"interactive"===document.readyState||"complete"===document.readyState?lt():ut.push(qr("load",(function(){Mi(ji({type:Cr.Load,data:{}})),lt()}),window)),function(){ut.forEach((function(t){return t()}))}}catch(t){console.warn(t)}}function Ui(t,e){"sentry.transaction"!==e.category&&(["ui.click","ui.input"].includes(e.category)?t.triggerUserActivity():t.checkAndHandleExpiredSession(),t.addUpdate((function(){return t.throttledAddEvent({type:Cr.Custom,timestamp:1e3*(e.timestamp||0),data:{tag:"breadcrumb",payload:Yt(e,10,1e3)}}),"console"===e.category})))}Pi.addCustomEvent=function(t,e){if(!Mi)throw new Error("please add custom event after start recording");Mi(ji({type:Cr.Custom,data:{tag:t,payload:e}}))},Pi.freezePage=function(){hi.forEach((function(t){return t.freeze()}))},Pi.takeFullSnapshot=function(t){if(!Ni)throw new Error("please take full snapshot after start recording");Ni(t)},Pi.mirror=Fi;var Bi;function Hi(t){var e=qi(t);return e&&e instanceof Element&&e.closest("button,a")||e}function qi(t){return function(t){return"object"==typeof t&&!!t&&"target"in t}(t)?t.target:t}var Wi,Zi=function(){var t=e.prototype;function e(t,n,r){void 0===r&&(r=Ui),e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),this._timeout=n.timeout/1e3,this._multiClickTimeout=n.multiClickTimeout/1e3,this._threshold=n.threshold/1e3,this._scollTimeout=n.scrollTimeout/1e3,this._replay=t,this._ignoreSelector=n.ignoreSelector,this._addBreadcrumbEvent=r}return t.__init=function(){this._lastMutation=0},t.__init2=function(){this._lastScroll=0},t.__init3=function(){this._clicks=[]},t.addListeners=function(){var t,e=this,n=function(){e._lastScroll=Yi()},r=(t=function(){e._lastMutation=Yi()},Bi||(Bi=[],O(Qn,"open",(function(t){return function(){if(Bi)try{Bi.forEach((function(t){return t()}))}catch(t){}for(var e=arguments.length,n=new Array(e),r=0;r-1&&Bi.splice(e,1)}),i=function(t){if(t.target){var n=Hi(t);n&&e._handleMultiClick(n)}},a=new MutationObserver((function(){e._lastMutation=Yi()}));a.observe(Qn.document.documentElement,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),Qn.addEventListener("scroll",n,{passive:!0}),Qn.addEventListener("click",i,{passive:!0}),this._teardown=function(){Qn.removeEventListener("scroll",n),Qn.removeEventListener("click",i),r(),a.disconnect(),e._clicks=[],e._lastMutation=0,e._lastScroll=0}},t.removeListeners=function(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)},t.handleClick=function(t,e){if(!function(t,e){return!Gi.includes(t.tagName)||("INPUT"===t.tagName&&!["submit","button"].includes(t.getAttribute("type")||"")||(!("A"!==t.tagName||!(t.hasAttribute("download")||t.hasAttribute("target")&&"_self"!==t.getAttribute("target")))||!(!e||!t.matches(e))))}(e,this._ignoreSelector)&&function(t){return!(!t.data||"number"!=typeof t.data.nodeId||!t.timestamp)}(t)&&!this._getClick(e)){var n={timestamp:t.timestamp,clickBreadcrumb:t,clickCount:0,node:e};this._clicks.push(n),1===this._clicks.length&&this._scheduleCheckClicks()}},t._handleMultiClick=function(t){var e=this._getClick(t);e&&e.clickCount++},t._getClick=function(t){var e=this,n=Yi();return this._clicks.find((function(r){return r.node===t&&n-r.timestamp=t._multiClickTimeout||r.timestamp+t._timeout<=n)&&e.push(r)}));for(var r=0,i=e;r1){var l={type:"default",message:o.message,timestamp:o.timestamp,category:"ui.multiClick",data:S({},o.data,{url:Qn.location.href,route:e.getCurrentRoute(),clickCount:a,metric:!0})};this._addBreadcrumbEvent(e,l)}},t._scheduleCheckClicks=function(){var t=this;this._checkClickTimeout=setTimeout((function(){return t._checkClicks()}),1e3)},e}(),Gi=["A","BUTTON","INPUT"];function Yi(){return Date.now()/1e3}function Ki(t){return S({timestamp:Date.now()/1e3,type:"default"},t)}!function(t){t[t.Document=0]="Document",t[t.DocumentType=1]="DocumentType",t[t.Element=2]="Element",t[t.Text=3]="Text",t[t.CDATA=4]="CDATA",t[t.Comment=5]="Comment"}(Wi||(Wi={}));var Xi=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled"]);function Vi(t){var e={};for(var n in t)if(Xi.has(n)){var r=n;"data-testid"!==n&&"data-test-id"!==n||(r="testId"),e[r]=t[n]}return e}function Ji(t,e){var n=t&&"__sn"in t&&t.__sn.type===Wi.Element?t.__sn:null;return{message:e,data:n?{nodeId:n.id,node:{id:n.id,tagName:n.tagName,textContent:t?Array.from(t.childNodes).map((function(t){return"__sn"in t&&t.__sn.type===Wi.Text&&t.__sn.textContent})).filter(Boolean).map((function(t){return t.trim()})).join(""):"",attributes:Vi(n.attributes)}}:{}}}var $i=["name","type","startTime","transferSize","duration"];function Qi(t){return function(e){return $i.every((function(n){return t[n]===e[n]}))}}function ta(t){return t>9999999999?t:1e3*t}var ea=function(){var t=e.prototype;function e(){e.prototype.__init.call(this),this.events=[]}return t.__init=function(){this._totalSize=0},t.destroy=function(){this.events=[]},t.addEvent=function(){var t=In(On().mark((function t(e){var n;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=JSON.stringify(e).length,this._totalSize+=n,!(this._totalSize>sr)){t.next=4;break}throw new aa;case 4:this.events.push(e);case 5:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),t.finish=function(){var t=this;return new Promise((function(e){var n=t.events;t.clear(),e(JSON.stringify(n))}))},t.clear=function(){this.events=[],this._totalSize=0},t.getEarliestTimestamp=function(){var t=this.events.map((function(t){return t.timestamp})).sort()[0];return t?ta(t):null},Ce(e,[{key:"hasEvents",get:function(){return this.events.length>0}},{key:"type",get:function(){return"sync"}}]),e}(),na=function(){function t(t){this._worker=t,this._id=0}var e=t.prototype;return e.ensureReady=function(){var t=this;return this._ensureReadyPromise||(this._ensureReadyPromise=new Promise((function(e,n){t._worker.addEventListener("message",(function(t){t.data.success?e():n()}),{once:!0}),t._worker.addEventListener("error",(function(t){n(t)}),{once:!0})}))),this._ensureReadyPromise},e.destroy=function(){this._worker.terminate()},e.postMessage=function(t,e){var n=this,r=this._getAndIncrementId();return new Promise((function(i,a){n._worker.addEventListener("message",(function e(o){var s=o.data;s.method===t&&s.id===r&&(n._worker.removeEventListener("message",e),s.success?i(s.response):a(new Error("Error in compression worker")))})),n._worker.postMessage({id:r,method:t,arg:e})}))},e._getAndIncrementId=function(){return this._id++},t}(),ra=function(){var t=e.prototype;function e(t){e.prototype.__init.call(this),this._worker=new na(t),this._earliestTimestamp=null}return t.__init=function(){this._totalSize=0},t.ensureReady=function(){return this._worker.ensureReady()},t.destroy=function(){this._worker.destroy()},t.addEvent=function(t){var e=ta(t.timestamp);(!this._earliestTimestamp||esr?Promise.reject(new aa):this._sendEventToWorker(n)},t.finish=function(){return this._finishRequest()},t.clear=function(){this._earliestTimestamp=null,this._totalSize=0,this._worker.postMessage("clear")},t.getEarliestTimestamp=function(){return this._earliestTimestamp},t._sendEventToWorker=function(t){return this._worker.postMessage("addEvent",t)},t._finishRequest=function(){var t=In(On().mark((function t(){var e;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this._worker.postMessage("finish");case 2:return e=t.sent,this._earliestTimestamp=null,this._totalSize=0,t.abrupt("return",e);case 6:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),Ce(e,[{key:"hasEvents",get:function(){return!!this._earliestTimestamp}},{key:"type",get:function(){return"worker"}}]),e}(),ia=function(){function t(t){this._fallback=new ea,this._compression=new ra(t),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}var e=t.prototype;return e.destroy=function(){this._fallback.destroy(),this._compression.destroy()},e.clear=function(){return this._used.clear()},e.getEarliestTimestamp=function(){return this._used.getEarliestTimestamp()},e.addEvent=function(t){return this._used.addEvent(t)},e.finish=function(){var t=In(On().mark((function t(){return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.ensureWorkerIsLoaded();case 2:return t.abrupt("return",this._used.finish());case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),e.ensureWorkerIsLoaded=function(){return this._ensureWorkerIsLoadedPromise},e._ensureWorkerIsLoaded=function(){var t=In(On().mark((function t(){return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this._compression.ensureReady();case 3:t.next=9;break;case 5:return t.prev=5,t.t0=t.catch(0),t.abrupt("return");case 9:return t.next=11,this._switchToCompressionWorker();case 11:case"end":return t.stop()}}),t,this,[[0,5]])})));return function(){return t.apply(this,arguments)}}(),e._switchToCompressionWorker=function(){var t=In(On().mark((function t(){var e,n,r,i,a;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:for(e=this._fallback.events,n=[],r=Vn(e);!(i=r()).done;)a=i.value,n.push(this._compression.addEvent(a));return this._used=this._compression,t.prev=4,t.next=7,Promise.all(n);case 7:t.next=12;break;case 9:t.prev=9,t.t0=t.catch(4);case 12:case"end":return t.stop()}}),t,this,[[4,9]])})));return function(){return t.apply(this,arguments)}}(),Ce(t,[{key:"type",get:function(){return this._used.type}},{key:"hasEvents",get:function(){return this._used.hasEvents}}]),t}();var aa=function(t){function e(){return t.call(this,"Event buffer exceeded maximum size of "+sr+".")||this}return Se(e,t),e}(Tn(Error));function oa(t,e,n){return void 0===n&&(n=+new Date),null===t||void 0===e||e<0||0!==e&&t+e<=n}function sa(t,e,n){return void 0===n&&(n=+new Date),oa(t.started,e.maxSessionLife,n)||oa(t.lastActivity,e.sessionIdleExpire,n)}function ua(t){return void 0!==t&&Math.random()=300)||(_a(n)&&n.contexts&&n.contexts.trace&&n.contexts.trace.trace_id?t.getContext().traceIds.add(n.contexts.trace.trace_id):va(n)&&(n.event_id&&t.getContext().errorIds.add(n.event_id),"buffer"===t.recordingMode&&n.tags&&n.tags.replayId&&setTimeout((function(){t.sendBufferedReplayOrFlush()}))))}}}function ya(t,e){return e.map((function(e){var n=e.type,r=e.start,i=e.end,a=e.name,o=e.data,s=t.throttledAddEvent({type:Cr.Custom,timestamp:r,data:{tag:"performanceSpan",payload:{op:n,description:a,startTimestamp:r,endTimestamp:i,data:o}}});return"string"==typeof s?Promise.resolve(null):s}))}function ba(t,e){t.isEnabled()&&null!==e&&(function(t){var e=ft().getClient(),n=e&&e.getDsn();return!!n&&t.includes(n.host)}(e.name)||t.addUpdate((function(){return ya(t,[e]),!0})))}var wa=10,ka=11,Sa=12,xa=13,Ea=14,Ta=15,Ca=20,Ia=21,Ra=22,Oa=23,Aa=["true","false","null"];function La(t,e,n){var r=t[t.length-1],i=e[n];if(!/\s/.test(i))if('"'!==i||Da(e,n))switch(i){case"{":!function(t,e){e&&e!==xa?(e===Ia&&t.push(wa),e===Ca&&t.push(wa)):t.push(wa)}(t,r);break;case"[":!function(t,e){e?e===xa?(t.push(Ca),t.push(Ia)):(e===Ia&&(t.push(Ca),t.push(Ia)),e===Ca&&(t.push(Ca),t.push(Ia))):(t.push(Ca),t.push(Ia))}(t,r);break;case":":!function(t,e){e===ka&&(t.pop(),t.push(xa))}(t,r);break;case",":!function(t,e){if(e!==xa)return e===Ta?(t.pop(),void t.pop()):void(e!==Ia&&e===Oa&&t.pop());t.pop()}(t,r);break;case"}":!function(t,e){e===wa&&t.pop(),e===xa&&(t.pop(),t.pop()),e===Ta&&(t.pop(),t.pop(),t.pop()),t[t.length-1]===xa&&t.push(Ta),t[t.length-1]===Ia&&t.push(Oa)}(t,r);break;case"]":!function(t,e){e===Ca&&t.pop(),e===Ia&&(t.pop(),t.pop()),e===Oa&&(t.pop(),t.pop(),t.pop()),t[t.length-1]===xa&&t.push(Ta),t[t.length-1]===Ia&&t.push(Oa)}(t,r)}else!function(t,e){e===Ea?(t.pop(),t.push(Ta)):e===Ra?(t.pop(),t.push(Oa)):e!==xa?e!==Ia?e!==wa?e===Sa&&(t.pop(),t.push(ka)):t.push(Sa):t.push(Ra):t.push(Ea)}(t,r)}function Da(t,e){return"\\"===t[e-1]&&!Da(t,e-1)}function Ma(t){return function(t,e){if(!e.length)return t;var n=t,r=e.length-1;n=function(t,e){switch(e){case wa:return t+'"~~":"~~"';case ka:return t+':"~~"';case Sa:return t+'~~":"~~"';case xa:return function(t){var e=t.lastIndexOf(":"),n=t.slice(e+1);return Aa.includes(n.trim())?t+',"~~":"~~"':t.slice(0,e+1)+'"~~"'}(t);case Ea:return t+'~~"';case Ta:return t+',"~~":"~~"';case Ca:return t+'"~~"';case Ia:return function(t){var e=function(t){for(var e=t.length-1;e>=0;e--){var n=t[e];if(","===n||"["===n)return e}return-1}(t);if(e>-1){var n=t.slice(e+1);return Aa.includes(n.trim())?t+',"~~"':t.slice(0,e+1)+'"~~"'}return t}(t);case Ra:return t+'~~"';case Oa:return t+',"~~"'}return t}(n,e[r]);for(var i=r;i>=0;i--)switch(e[i]){case wa:n+="}";break;case Ca:n+="]"}return n}(t,function(t){for(var e=[],n=0;nar;if(n=(e=t)[0],r=e[e.length-1],"["===n&&"]"===r||"{"===n&&"}"===r)try{var a=i?Ma(t.slice(0,ar)):t;return{body:JSON.parse(a),warnings:i?["JSON_TRUNCATED"]:[]}}catch(e){return{body:i?t.slice(0,ar)+"…":t,warnings:i?["INVALID_JSON","TEXT_TRUNCATED"]:["INVALID_JSON"]}}return{body:i?t.slice(0,ar)+"…":t,warnings:i?["TEXT_TRUNCATED"]:[]}}(n),a=i.body,o=i.warnings;return r.body=a,o.length>0&&(r._meta={warnings:o}),r}}function Ba(t,e){return Object.keys(t).reduce((function(n,r){var i=r.toLowerCase();return e.includes(i)&&t[r]&&(n[i]=t[r]),n}),{})}function Ha(t){return new URLSearchParams(t).toString()}function qa(t,e){var n=function(t,e){if(void 0===e&&(e=Qn.document.baseURI),t.startsWith("http://")||t.startsWith("https://")||t.startsWith(Qn.location.origin))return t;var n=new URL(t,e);if(n.origin!==new URL(e).origin)return t;var r=n.href;return!t.endsWith("/")&&r.endsWith("/")?r.slice(0,-1):r}(t);return g(n,e)}function Wa(){return(Wa=In(On().mark((function t(e,n,r){var i,a;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,Za(e,n,r);case 3:i=t.sent,a=Fa("resource.fetch",i),ba(r.replay,a),t.next=11;break;case 8:t.prev=8,t.t0=t.catch(0);case 11:case"end":return t.stop()}}),t,null,[[0,8]])})))).apply(this,arguments)}function Za(t,e,n){return Ga.apply(this,arguments)}function Ga(){return(Ga=In(On().mark((function t(e,n,r){var i,a,o,s,u,c,l,d,h,p,f,m;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=n.startTimestamp,a=n.endTimestamp,o=e.data,s=o.url,u=o.method,c=o.status_code,l=void 0===c?0:c,d=o.request_body_size,h=o.response_body_size,p=qa(s,r.networkDetailAllowUrls),f=p?Ya(r,n.input,d):Pa(d),t.next=6,Ka(p,r,n.response,h);case 6:return m=t.sent,t.abrupt("return",{startTimestamp:i,endTimestamp:a,url:s,method:u,statusCode:l,request:f,response:m});case 8:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function Ya(t,e,n){var r,i,a=t.networkCaptureBodies;return Ua((r=e,i=t.networkRequestHeaders,1===r.length&&"string"!=typeof r[0]?to(r[0],i):2===r.length?to(r[1],i):{}),n,a?ja($a(e)):void 0)}function Ka(t,e,n,r){return Xa.apply(this,arguments)}function Xa(){return(Xa=In(On().mark((function t(e,n,r,i){var a,o,s,u,c,l,d;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(a=n.networkCaptureBodies,o=n.textEncoder,s=n.networkResponseHeaders,e||void 0===i){t.next=3;break}return t.abrupt("return",Pa(i));case 3:if(u=Qa(r.headers,s),a||void 0===i){t.next=6;break}return t.abrupt("return",Ua(u,i,void 0));case 6:return t.prev=6,c=r.clone(),t.next=10,Va(c);case 10:if(l=t.sent,d=l&&l.length&&void 0===i?Na(l,o):i,e){t.next=14;break}return t.abrupt("return",Pa(d));case 14:if(!a){t.next=16;break}return t.abrupt("return",Ua(u,d,l));case 16:return t.abrupt("return",Ua(u,d,void 0));case 19:return t.prev=19,t.t0=t.catch(6),t.abrupt("return",Ua(u,i,void 0));case 22:case"end":return t.stop()}}),t,null,[[6,19]])})))).apply(this,arguments)}function Va(t){return Ja.apply(this,arguments)}function Ja(){return(Ja=In(On().mark((function t(e){return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.text();case 3:return t.abrupt("return",t.sent);case 6:return t.prev=6,t.t0=t.catch(0),t.abrupt("return",void 0);case 9:case"end":return t.stop()}}),t,null,[[0,6]])})))).apply(this,arguments)}function $a(t){if(void 0===t&&(t=[]),2===t.length&&"object"==typeof t[1])return t[1].body}function Qa(t,e){var n={};return e.forEach((function(e){t.get(e)&&(n[e]=t.get(e))})),n}function to(t,e){if(!t)return{};var n=t.headers;return n?n instanceof Headers?Qa(n,e):Array.isArray(n)?{}:Ba(n,e):{}}function eo(){return(eo=In(On().mark((function t(e,n,r){var i,a;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:try{i=no(e,n,r),a=Fa("resource.xhr",i),ba(r.replay,a)}catch(t){}case 1:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function no(t,e,n){var r=e.startTimestamp,i=e.endTimestamp,a=e.input,o=e.xhr,s=t.data,u=s.url,c=s.method,l=s.status_code,d=void 0===l?0:l,h=s.request_body_size,p=s.response_body_size;if(!u)return null;if(!qa(u,n.networkDetailAllowUrls))return{startTimestamp:r,endTimestamp:i,url:u,method:c,statusCode:d,request:Pa(h),response:Pa(p)};var f=o[Dt],m=f?Ba(f.request_headers,n.networkRequestHeaders):{},v=Ba(function(t){var e=t.getAllResponseHeaders();return e?e.split("\r\n").reduce((function(t,e){var n=e.split(": "),r=n[0],i=n[1];return t[r.toLowerCase()]=i,t}),{}):{}}(o),n.networkResponseHeaders);return{startTimestamp:r,endTimestamp:i,url:u,method:c,statusCode:d,request:Ua(m,h,n.networkCaptureBodies?ja(a):void 0),response:Ua(v,p,n.networkCaptureBodies?e.xhr.responseText:void 0)}}function ro(t){var e=ft().getClient();try{var n=new TextEncoder,r=t.getOptions(),i={replay:t,textEncoder:n,networkDetailAllowUrls:r.networkDetailAllowUrls,networkCaptureBodies:r.networkCaptureBodies,networkRequestHeaders:r.networkRequestHeaders,networkResponseHeaders:r.networkResponseHeaders};e&&e.on?e.on("beforeAddBreadcrumb",(function(t,e){return function(t,e,n){if(e.data)try{(function(t){return"xhr"===t.category})(e)&&function(t){return t&&t.xhr}(n)&&(function(t,e,n){var r=e.xhr,i=Na(e.input,n.textEncoder),a=r.getResponseHeader("content-length")?za(r.getResponseHeader("content-length")):Na(r.response,n.textEncoder);void 0!==i&&(t.data.request_body_size=i),void 0!==a&&(t.data.response_body_size=a)}(e,n,t),function(t,e,n){eo.apply(this,arguments)}(e,n,t)),function(t){return"fetch"===t.category}(e)&&function(t){return t&&t.response}(n)&&(function(t,e,n){var r=e.input,i=e.response,a=Na($a(r),n.textEncoder),o=i?za(i.headers.get("content-length")):void 0;void 0!==a&&(t.data.request_body_size=a),void 0!==o&&(t.data.response_body_size=o)}(e,n,t),function(t,e,n){Wa.apply(this,arguments)}(e,n,t))}catch(t){}}(i,t,e)})):(jt("fetch",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.fetchData,i=t.response;if(!n)return null;var a=r.method;return{type:"resource.fetch",start:e/1e3,end:n/1e3,name:r.url,data:{method:a,statusCode:i&&i.status}}}(e);ba(t,n)}}}(t)),jt("xhr",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.xhr[Dt];if(!e||!n||!r)return null;var i=r.method,a=r.url,o=r.status_code;return void 0===a?null:{type:"resource.xhr",name:a,start:e/1e3,end:n/1e3,data:{method:i,statusCode:o}}}(e);ba(t,n)}}}(t)))}catch(t){}}var io=null;function ao(t){return!(!t||!t.on)}function oo(t){return so.apply(this,arguments)}function so(){return(so=In(On().mark((function t(e){return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.abrupt("return",Promise.all(ya(e,[(n=Qn.performance.memory,void 0,void 0,void 0,void 0,r=n.jsHeapSizeLimit,i=n.totalJSHeapSize,a=n.usedJSHeapSize,o=Date.now()/1e3,{type:"memory",name:"memory",start:o,end:o,data:{memory:{jsHeapSizeLimit:r,totalJSHeapSize:i,usedJSHeapSize:a}}})])));case 4:return t.prev=4,t.t0=t.catch(0),t.abrupt("return",[]);case 7:case"end":return t.stop()}var n,r,i,a,o}),t,null,[[0,4]])})))).apply(this,arguments)}var uo=((Kn={resource:function(t){var e=t.entryType,n=t.initiatorType,r=t.name,i=t.responseEnd,a=t.startTime,o=t.decodedBodySize,s=t.encodedBodySize,u=t.responseStatus,c=t.transferSize;return["fetch","xmlhttprequest"].includes(n)?null:{type:e+"."+n,start:lo(a),end:lo(i),name:r,data:{size:c,statusCode:u,decodedBodySize:o,encodedBodySize:s}}},paint:function(t){var e=t.duration,n=t.entryType,r=t.name,i=lo(t.startTime);return{type:n,name:r,start:i,end:i+e,data:void 0}},navigation:function(t){var e=t.entryType,n=t.name,r=t.decodedBodySize,i=t.duration,a=t.domComplete,o=t.encodedBodySize,s=t.domContentLoadedEventStart,u=t.domContentLoadedEventEnd,c=t.domInteractive,l=t.loadEventStart,d=t.loadEventEnd,h=t.redirectCount,p=t.startTime,f=t.transferSize,m=t.type;return 0===i?null:{type:e+"."+m,start:lo(p),end:lo(a),name:n,data:{size:f,decodedBodySize:r,encodedBodySize:o,duration:i,domInteractive:c,domContentLoadedEventStart:s,domContentLoadedEventEnd:u,loadEventStart:l,loadEventEnd:d,domComplete:a,redirectCount:h}}}})["largest-contentful-paint"]=function(t){var e=t.entryType,n=t.startTime,r=t.size,i=0;if(Qn.performance){var a=Qn.performance.getEntriesByType("navigation")[0];i=a&&a.activationStart||0}var o=Math.max(n-i,0),s=lo(i)+o/1e3;return{type:e,name:e,start:s,end:s,data:{value:o,size:r,nodeId:Pi.mirror.getId(t.element)}}},Kn);function co(t){return void 0===uo[t.entryType]?null:uo[t.entryType](t)}function lo(t){return((Q.Z1||Qn.performance.timeOrigin)+t)/1e3}function ho(t,e,n,r){return Pn(Yn(t,Gn(t),r,n),[[{type:"replay_event"},t],[{type:"replay_recording",length:"string"==typeof e?(new TextEncoder).encode(e).length:e.length},e]])}function po(t){var e,n=t.recordingData,r=t.headers,i=JSON.stringify(r)+"\n";if("string"==typeof n)e=""+i+n;else{var a=(new TextEncoder).encode(i);(e=new Uint8Array(a.length+n.length)).set(a),e.set(n,a.length)}return e}function fo(t){return mo.apply(this,arguments)}function mo(){return mo=In(On().mark((function t(e){var n,r,i,a,o,s,u,c,l,d;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=e.client,r=e.scope,i=e.replayId,a=e.event,o="object"!=typeof n._integrations||null===n._integrations||Array.isArray(n._integrations)?void 0:Object.keys(n._integrations),t.next=4,An(n.getOptions(),a,{event_id:i,integrations:o},r);case 4:if(s=t.sent){t.next=7;break}return t.abrupt("return",null);case 7:return s.platform=s.platform||"javascript",u=n.getSdkMetadata&&n.getSdkMetadata(),c=u&&u.sdk||{},l=c.name,d=c.version,s.sdk=S({},s.sdk,{name:l||"sentry.javascript.unknown",version:d||"0.0.0"}),t.abrupt("return",s);case 12:case"end":return t.stop()}}),t)}))),mo.apply(this,arguments)}function vo(t){return _o.apply(this,arguments)}function _o(){return(_o=In(On().mark((function t(e){var n,r,i,a,o,s,u,c,l,d,h,p,f,m,v,_,g,y,b,w,k;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.recordingData,r=e.replayId,i=e.segmentId,a=e.eventContext,o=e.timestamp,s=e.session,u=po({recordingData:n,headers:{segment_id:i}}),c=a.urls,l=a.errorIds,d=a.traceIds,h=a.initialTimestamp,p=ft(),f=p.getClient(),m=p.getScope(),v=f&&f.getTransport(),_=f&&f.getDsn(),f&&m&&v&&_&&s.sampled){t.next=10;break}return t.abrupt("return");case 10:return g={type:er,replay_start_timestamp:h/1e3,timestamp:o/1e3,error_ids:l,trace_ids:d,urls:c,replay_id:r,segment_id:i,replay_type:s.sampled},t.next=13,fo({scope:m,client:f,replayId:r,event:g});case 13:if(y=t.sent){t.next=18;break}return f.recordDroppedEvent("event_processor","replay",g),t.abrupt("return");case 18:return b=ho(y,u,_,f.getOptions().tunnel),t.prev=19,t.next=22,v.send(b);case 22:w=t.sent,t.next=30;break;case 25:t.prev=25,t.t0=t.catch(19),k=new Error(nr);try{k.cause=t.t0}catch(t){}throw k;case 30:if(w){t.next=32;break}return t.abrupt("return",w);case 32:if("number"!=typeof w.statusCode||!(w.statusCode<200||w.statusCode>=300)){t.next=34;break}throw new go(w.statusCode);case 34:return t.abrupt("return",w);case 35:case"end":return t.stop()}}),t,null,[[19,25]])})))).apply(this,arguments)}var go=function(t){function e(e){return t.call(this,"Transport returned status code "+e)||this}return Se(e,t),e}(Tn(Error));function yo(t,e){return bo.apply(this,arguments)}function bo(){return(bo=In(On().mark((function t(e,n){var r,i;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(void 0===n&&(n={count:0,interval:rr}),r=e.recordingData,e.options,r.length){t.next=4;break}return t.abrupt("return");case 4:return t.prev=4,t.next=7,vo(e);case 7:return t.abrupt("return",!0);case 10:if(t.prev=10,t.t0=t.catch(4),!(t.t0 instanceof go)){t.next=14;break}throw t.t0;case 14:if("Replays",a={_retryCount:n.count},ft().setContext("Replays",a),!(n.count>=ir)){t.next=20;break}i=new Error(nr+" - max retries exceeded");try{i.cause=t.t0}catch(t){}throw i;case 20:return n.interval*=++n.count,t.next=23,new Promise((function(t,r){setTimeout(In(On().mark((function i(){return On().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return i.prev=0,i.next=3,yo(e,n);case 3:t(!0),i.next=9;break;case 6:i.prev=6,i.t0=i.catch(0),r(i.t0);case 9:case"end":return i.stop()}}),i,null,[[0,6]])}))),n.interval)}));case 23:return t.abrupt("return",t.sent);case 24:case"end":return t.stop()}var a}),t,null,[[4,10]])})))).apply(this,arguments)}var wo="__THROTTLED";var ko=function(){var t=e.prototype;function e(t){var n,r,i,a,o,s=this,u=t.options,c=t.recordingOptions;e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this),e.prototype.__init7.call(this),e.prototype.__init8.call(this),e.prototype.__init9.call(this),e.prototype.__init10.call(this),e.prototype.__init11.call(this),e.prototype.__init12.call(this),e.prototype.__init13.call(this),e.prototype.__init14.call(this),e.prototype.__init15.call(this),e.prototype.__init16.call(this),e.prototype.__init17.call(this),e.prototype.__init18.call(this),this._recordingOptions=c,this._options=u,this._debouncedFlush=function(t,e,n){var r,i,a,o=n&&n.maxWait?Math.max(n.maxWait,e):0;function s(){return u(),r=t()}function u(){void 0!==i&&clearTimeout(i),void 0!==a&&clearTimeout(a),i=a=void 0}function c(){return i&&clearTimeout(i),i=setTimeout(s,e),o&&void 0===a&&(a=setTimeout(s,o)),r}return c.cancel=u,c.flush=function(){return void 0!==i||void 0!==a?s():r},c}((function(){return s._flush()}),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=(n=function(t,e){return fa(s,t,e)},r=300,i=5,a=new Map,o=!1,function(){var t=Math.floor(Date.now()/1e3);if(function(t){var e=t-i;a.forEach((function(t,n){n=r){var e=o;return o=!0,e?"__SKIPPED":wo}o=!1;var s=a.get(t)||0;return a.set(t,s+1),n.apply(void 0,arguments)});var l=this.getOptions(),d=l.slowClickTimeout,h=l.slowClickIgnoreSelectors,p=d?{threshold:Math.min(3e3,d),timeout:d,scrollTimeout:300,ignoreSelector:h?h.join(","):"",multiClickTimeout:1e3}:void 0;p&&(this.clickDetector=new Zi(this,p))}return t.__init=function(){this.eventBuffer=null},t.__init2=function(){this.performanceEvents=[]},t.__init3=function(){this.recordingMode="session"},t.__init4=function(){this.timeouts={sessionIdlePause:3e5,sessionIdleExpire:9e5,maxSessionLife:36e5}},t.__init5=function(){this._performanceObserver=null},t.__init6=function(){this._flushLock=null},t.__init7=function(){this._lastActivity=Date.now()},t.__init8=function(){this._isEnabled=!1},t.__init9=function(){this._isPaused=!1},t.__init10=function(){this._hasInitializedCoreListeners=!1},t.__init11=function(){this._stopRecording=null},t.__init12=function(){this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""}},t.getContext=function(){return this._context},t.isEnabled=function(){return this._isEnabled},t.isPaused=function(){return this._isPaused},t.getOptions=function(){return this._options},t.initializeSampling=function(){var t=this._options,e=t.errorSampleRate,n=t.sessionSampleRate;e<=0&&n<=0||this._loadAndCheckSession()&&(this.session?(this.session.sampled&&"session"!==this.session.sampled&&(this.recordingMode="buffer"),this._initializeRecording()):this._handleException(new Error("Unable to initialize and create session")))},t.start=function(){if(this._isEnabled&&"session"===this.recordingMode)throw new Error("Replay recording is already in progress");if(this._isEnabled&&"buffer"===this.recordingMode)throw new Error("Replay buffering is in progress, call `flush()` to save the replay");var t=this.session&&this.session.id,e=ha({timeouts:this.timeouts,stickySession:Boolean(this._options.stickySession),currentSession:this.session,sessionSampleRate:1,allowBuffering:!1}).session;e.previousSessionId=t,this.session=e,this._initializeRecording()},t.startBuffering=function(){if(this._isEnabled)throw new Error("Replay recording is already in progress");var t=this.session&&this.session.id,e=ha({timeouts:this.timeouts,stickySession:Boolean(this._options.stickySession),currentSession:this.session,sessionSampleRate:0,allowBuffering:!0}).session;e.previousSessionId=t,this.session=e,this.recordingMode="buffer",this._initializeRecording()},t.startRecording=function(){try{this._stopRecording=Pi(S({},this._recordingOptions,"buffer"===this.recordingMode&&{checkoutEveryNms:6e4},{emit:(t=this,e=!1,function(n,r){if(t.checkAndHandleExpiredSession()){var i=r||!e;e=!0,t.addUpdate((function(){if("buffer"===t.recordingMode&&i&&t.setInitialState(),fa(t,n,i),!i)return!1;if(function(t,e){if(!e||!t.session||0!==t.session.segmentId)return Promise.resolve(null);fa(t,function(t){var e=t.getOptions();return{type:Cr.Custom,timestamp:Date.now(),data:{tag:"options",payload:{sessionSampleRate:e.sessionSampleRate,errorSampleRate:e.errorSampleRate,useCompressionOption:e.useCompression,blockAllMedia:e.blockAllMedia,maskAllText:e.maskAllText,maskAllInputs:e.maskAllInputs,useCompression:!!t.eventBuffer&&"worker"===t.eventBuffer.type,networkDetailHasUrls:e.networkDetailAllowUrls.length>0,networkCaptureBodies:e.networkCaptureBodies,networkRequestHasHeaders:e.networkRequestHeaders.length>0,networkResponseHasHeaders:e.networkResponseHeaders.length>0}}}}(t),!1)}(t,i),t.session&&t.session.previousSessionId)return!0;if("buffer"===t.recordingMode&&t.session&&t.eventBuffer){var e=t.eventBuffer.getEarliestTimestamp();e&&(t.session.started=e,t.getOptions().stickySession&&ca(t.session))}var r=t.getOptions();return r._experiments.delayFlushOnCheckout?(setTimeout((function(){return t.conditionalFlush()}),r._experiments.delayFlushOnCheckout),t.cancelFlush(),!0):("session"===t.recordingMode&&t.flushImmediate(),!0)}))}}),onMutation:this._onMutationHandler}))}catch(t){this._handleException(t)}var t,e},t.stopRecording=function(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(t){return this._handleException(t),!1}},t.stop=function(){var t=In(On().mark((function t(e){return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._isEnabled){t.next=2;break}return t.abrupt("return");case 2:if(t.prev=2,this._isEnabled=!1,this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),"session"!==this.recordingMode){t.next=11;break}return t.next=11,this._flush({force:!0});case 11:this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,e=this,function(){if("sessionStorage"in Qn)try{Qn.sessionStorage.removeItem(tr)}catch(t){}}(),e.session=void 0,t.next=19;break;case 16:t.prev=16,t.t0=t.catch(2),this._handleException(t.t0);case 19:case"end":return t.stop()}var e}),t,this,[[2,16]])})));return function(e){return t.apply(this,arguments)}}(),t.pause=function(){this._isPaused=!0,this.stopRecording()},t.resume=function(){this._loadAndCheckSession()&&(this._isPaused=!1,this.startRecording())},t.sendBufferedReplayOrFlush=function(){var t=In(On().mark((function t(e){var n,r,i,a;return On().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=(void 0===e?{}:e).continueRecording,r=void 0===n||n,"session"!==this.recordingMode){t.next=3;break}return t.abrupt("return",this.flushImmediate());case 3:return i=Date.now(),t.next=6,this.flushImmediate();case 6:if(a=this.stopRecording(),r&&a){t.next=9;break}return t.abrupt("return");case 9:this.recordingMode="session",this.session&&(this.session.shouldRefresh=!1,this._updateUserActivity(i),this._updateSessionActivity(i),this.session.started=i,this._maybeSaveSession()),this.startRecording();case 12:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),t.addUpdate=function(t){var e=t();"buffer"!==this.recordingMode&&!0!==e&&this._debouncedFlush()},t.triggerUserActivity=function(){if(this._updateUserActivity(),this._stopRecording)this.checkAndHandleExpiredSession(),this._updateSessionActivity();else{if(!this._loadAndCheckSession())return;this.resume()}},t.updateUserActivity=function(){this._updateUserActivity(),this._updateSessionActivity()},t.conditionalFlush=function(){return"buffer"===this.recordingMode?Promise.resolve():this.flushImmediate()},t.flushImmediate=function(){return this._debouncedFlush(),this._debouncedFlush.flush()},t.cancelFlush=function(){this._debouncedFlush.cancel()},t.getSessionId=function(){return this.session&&this.session.id},t.checkAndHandleExpiredSession=function(){var t=this.getSessionId();if(this._lastActivity&&oa(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&"session"===this.session.sampled)this.pause();else if(this._loadAndCheckSession())return t===this.getSessionId()||(this._triggerFullSnapshot(),!1)},t.setInitialState=function(){var t=""+Qn.location.pathname+Qn.location.hash+Qn.location.search,e=""+Qn.location.origin+t;this.performanceEvents=[],this._clearContext(),this._context.initialUrl=e,this._context.initialTimestamp=Date.now(),this._context.urls.push(e)},t.throttledAddEvent=function(t,e){var n=this,r=this._throttledAddEvent(t,e);if(r===wo){var i=Ki({category:"replay.throttled"});this.addUpdate((function(){fa(n,{type:Cr.Custom,timestamp:i.timestamp||0,data:{tag:"breadcrumb",payload:i,metric:!0}})}))}return r},t.getCurrentRoute=function(){var t=this.lastTransaction||ft().getScope().getTransaction();if(t&&["route","custom"].includes(t.metadata.source))return t.name},t._initializeRecording=function(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=function(t){if(t.useCompression&&window.Worker)try{var e=(r=new Blob(['/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\nfunction t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const m=t=>t<256?o[t]:o[256+(t>>>7)],b=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},g=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<{g(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)r=r+a[n-1]<<1,i[n]=r;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},x=t=>{t.bi_valid>8?b(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n{let s,r,o,_,f=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+f++],s+=(255&t.pending_buf[t.sym_buf+f++])<<8,r=t.pending_buf[t.sym_buf+f++],0===s?p(t,r,i):(o=l[r],p(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],g(t,r,_)),s--,o=m(s),p(t,o,n),_=a[o],0!==_&&(s-=d[o],g(t,s,_)))}while(f{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o{g(t,0+(i?1:0),3),x(t),b(t,a),b(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var T=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(g(t,2+(i?1:0),3),E(t,s,r)):(g(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(g(t,e-257,5),g(t,a-1,5),g(t,i-4,4),s=0;s{S||((()=>{let t,n,w,m,b;const g=new Array(16);for(w=0,m=0;m<28;m++)for(h[m]=w,t=0;t<1<>=7;m<30;m++)for(d[m]=b<<7,t=0;t<1<(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=a,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{g(t,2,3),p(t,256,s),(t=>{16===t.bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var F=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const L=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var N=(t,e,a,i)=>{const n=L,s=i+a;t^=-1;for(let a=i;a>>8^n[255&(t^e[a])];return-1^t},I={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=O,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:W,Z_OK:q,Z_STREAM_END:J,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>2*t-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_t=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let ft=(t,e,a)=>(e<{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ut=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ct(t.strm)},wt=(t,e)=>{t.pending_buf[t.pending++]=e},mt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=F(t.adler,e,n,a):2===t.state.wrap&&(t.adler=N(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&sr){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_t(t),i+=e),0===t.strm.avail_in)break;if(a=bt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ft(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ft(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},kt=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_outi+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,ct(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(bt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_watern&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(bt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===X)&&e!==P&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===X&&0===t.strm.avail_in&&a===i?1:0,H(t,t.block_start,a,r),t.block_start+=a,ct(t.strm)),r?3:1)},vt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ft(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2},yt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ut(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ut(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2};function xt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const zt=[new xt(0,0,0,0,kt),new xt(4,4,8,4,vt),new xt(4,5,16,8,vt),new xt(4,6,32,32,vt),new xt(4,4,16,16,yt),new xt(8,16,32,32,yt),new xt(8,16,128,128,yt),new xt(8,32,128,256,yt),new xt(32,128,258,1024,yt),new xt(32,258,258,4096,yt)];function At(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Et=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||42!==e.status&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&113!==e.status&&666!==e.status?1:0},Rt=t=>{if(Et(t))return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=-2,C(e),q},Zt=t=>{const e=Rt(t);var a;return e===q&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=zt[a.level].max_lazy,a.good_match=zt[a.level].good_length,a.nice_match=zt[a.level].nice_length,a.max_chain_length=zt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},Ut=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt||8===i&&1!==r)return lt(t,Q);8===i&&(i=9);const o=new At;return t.state=o,o.strm=t,o.status=42,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<Ut(t,e,ot,15,8,st),deflateInit2:Ut,deflateReset:Zt,deflateResetKeep:Rt,deflateSetHeader:(t,e)=>Et(t)||2!==t.state.wrap?Q:(t.state.gzhead=e,q),deflate:(t,e)=>{if(Et(t)||e>W||e<0)return t?lt(t,Q):Q;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||666===a.status&&e!==X)return lt(t,0===t.avail_out?$:Q);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(ct(t),0===t.avail_out)return a.last_flush=-1,q}else if(0===t.avail_in&&ht(e)<=ht(i)&&e!==X)return lt(t,$);if(666===a.status&&0!==t.avail_in)return lt(t,$);if(42===a.status&&0===a.wrap&&(a.status=113),42===a.status){let e=ot+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=at||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,mt(a,e),0!==a.strstart&&(mt(a,t.adler>>>16),mt(a,65535&t.adler)),t.adler=1,a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(57===a.status)if(t.adler=0,wt(a,31),wt(a,139),wt(a,8),a.gzhead)wt(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),wt(a,255&a.gzhead.time),wt(a,a.gzhead.time>>8&255),wt(a,a.gzhead.time>>16&255),wt(a,a.gzhead.time>>24&255),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(wt(a,255&a.gzhead.extra.length),wt(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=N(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,3),a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,ct(t),0!==a.pending)return a.last_flush=-1,q;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(ct(t),0!==a.pending))return a.last_flush=-1,q;wt(a,255&t.adler),wt(a,t.adler>>8&255),t.adler=0}if(a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(0!==t.avail_in||0!==a.lookahead||e!==P&&666!==a.status){let i=0===a.level?kt(a,e):a.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):zt[a.level].func(a,e);if(3!==i&&4!==i||(a.status=666),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),q;if(2===i&&(e===Y?K(a):e!==W&&(H(a,0,0,!1),e===G&&(dt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),ct(t),0===t.avail_out))return a.last_flush=-1,q}return e!==X?q:a.wrap<=0?J:(2===a.wrap?(wt(a,255&t.adler),wt(a,t.adler>>8&255),wt(a,t.adler>>16&255),wt(a,t.adler>>24&255),wt(a,255&t.total_in),wt(a,t.total_in>>8&255),wt(a,t.total_in>>16&255),wt(a,t.total_in>>24&255)):(mt(a,t.adler>>>16),mt(a,65535&t.adler)),ct(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?q:J)},deflateEnd:t=>{if(Et(t))return Q;const e=t.state.status;return t.state=null,113===e?lt(t,V):q},deflateSetDictionary:(t,e)=>{let a=e.length;if(Et(t))return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=F(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=ft(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,q},deflateInfo:"pako deflate (from Nodeca project)"};const Dt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Tt=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(const e in a)Dt(a,e)&&(t[e]=a[e])}}return t},Ot=t=>{let e=0;for(let a=0,i=t.length;a=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Lt[254]=Lt[254]=1;var Nt=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},It=(t,e)=>{const a=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Ft)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a="";for(let i=0;i{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Lt[t[a]]>e?a:e};var Ct=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const Ht=Object.prototype.toString,{Z_NO_FLUSH:Mt,Z_SYNC_FLUSH:jt,Z_FULL_FLUSH:Kt,Z_FINISH:Pt,Z_OK:Yt,Z_STREAM_END:Gt,Z_DEFAULT_COMPRESSION:Xt,Z_DEFAULT_STRATEGY:Wt,Z_DEFLATED:qt}=B;function Jt(t){this.options=Tt({level:Xt,method:qt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Wt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=St.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==Yt)throw new Error(I[a]);if(e.header&&St.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Nt(e.dictionary):"[object ArrayBuffer]"===Ht.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=St.deflateSetDictionary(this.strm,t),a!==Yt)throw new Error(I[a]);this._dict_set=!0}}function Qt(t,e){const a=new Jt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}Jt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Pt:Mt,"string"==typeof t?a.input=Nt(t):"[object ArrayBuffer]"===Ht.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===jt||s===Kt)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=St.deflate(a,s),n===Gt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=St.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Yt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},Jt.prototype.onData=function(t){this.chunks.push(t)},Jt.prototype.onEnd=function(t){t===Yt&&(this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Vt={Deflate:Jt,deflate:Qt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Qt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Qt(t,e)},constants:B};var $t=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg="invalid distance too far back",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg="invalid distance too far back",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a>3,a-=k,c-=k<<3,f&=(1<{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,U,S,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0}while(0!==d);for(h=1<>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whavexe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=me;break}if((15&h)!==we){t.msg="unknown compression method",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg="invalid window size",a.mode=me;break}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=N(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=N(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg="invalid block type",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid code lengths set",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg="invalid bit length repeat",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid literal/lengths set",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg="invalid distances set",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg="invalid literal/length code",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg="invalid distance code",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=F(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:"pako inflate (from Nodeca project)"};var Se=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Te,Z_FINISH:Oe,Z_OK:Fe,Z_STREAM_END:Le,Z_NEED_DICT:Ne,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Tt({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ue.inflateInit2(this.strm,e.windowBits);if(a!==Fe)throw new Error(I[a]);if(this.header=new Se,Ue.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Nt(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Ue.inflateSetDictionary(this.strm,e.dictionary),a!==Fe)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Oe:Te,"[object ArrayBuffer]"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Ue.inflate(a,r),s===Ne&&n&&(s=Ue.inflateSetDictionary(a,n),s===Fe?s=Ue.inflate(a,r):s===Be&&(s=Ne));a.avail_in>0&&s===Le&&a.state.wrap>0&&0!==t[a.next_in];)Ue.inflateReset(a),s=Ue.inflate(a,r);switch(s){case Ie:case Be:case Ne:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Le))if("string"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Fe||0!==o){if(s===Le)return s=Ue.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Fe&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=je,Xe=B;const We=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const e=this._hasEvents?",":"";this.deflate.push(e+t,Xe.Z_SYNC_FLUSH),this._hasEvents=!0}finish(){if(this.deflate.push("]",Xe.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this._init(),t}_init(){this._hasEvents=!1,this.deflate=new Ye,this.deflate.push("[",Xe.Z_NO_FLUSH)}},qe={clear:()=>{We.clear()},addEvent:t=>We.addEvent(t),finish:()=>We.finish(),compress:t=>function(t){return Ge(t)}(t)};addEventListener("message",(function(t){const e=t.data.method,a=t.data.id,i=t.data.arg;if(e in qe&&"function"==typeof qe[e])try{const t=qe[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});']),URL.createObjectURL(r)),n=new Worker(e);return new ia(n)}catch(t){}var r;return new ea}({useCompression:this._options.useCompression}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this.startRecording()},t._handleException=function(t){},t._loadAndCheckSession=function(){var t=ha({timeouts:this.timeouts,stickySession:Boolean(this._options.stickySession),currentSession:this.session,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:this._options.errorSampleRate>0||"buffer"===this.recordingMode}),e=t.type,n=t.session;"new"===e&&this.setInitialState();var r=this.getSessionId();return n.id!==r&&(n.previousSessionId=r),this.session=n,!!this.session.sampled||(this.stop("session unsampled"),!1)},t._addListeners=function(){try{Qn.document.addEventListener("visibilitychange",this._handleVisibilityChange),Qn.addEventListener("blur",this._handleWindowBlur),Qn.addEventListener("focus",this._handleWindowFocus),Qn.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(t=this,e=ft().getScope(),n=ft().getClient(),e&&e.addScopeListener(function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.getLastBreadcrumb&&t.getLastBreadcrumb();return io!==e&&e?(io=e,!e.category||["fetch","xhr","sentry.event","sentry.transaction"].includes(e.category)||e.category.startsWith("ui.")?null:"console"===e.category?function(t){var e=t.data&&t.data.arguments;if(!Array.isArray(e)||0===e.length)return Ki(t);var n=!1,r=e.map((function(t){if(!t)return t;if("string"==typeof t)return t.length>or?(n=!0,t.slice(0,or)+"…"):t;if("object"==typeof t)try{var e=Yt(t,7),r=JSON.stringify(e);if(r.length>or){var i=Ma(r.slice(0,or)),a=JSON.parse(i);return n=!0,a}return e}catch(t){}return t}));return Ki(S({},t,{data:S({},t.data,{arguments:r},n?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{})}))}(e):Ki(e)):null}(e);n&&Ui(t,n)}}}(t)),jt("dom",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=function(t){var e,n="click"===t.name,r=null;try{e=I(r=n?Hi(t.event):qi(t.event),{maxStringLength:200})||""}catch(t){e=""}return{target:r,message:e}}(t),n=e.target,r=e.message;return Ki(S({category:"ui."+t.name},Ji(n,r)))}(e);if(n){var r="click"===e.name,i=r&&e.event;r&&t.clickDetector&&i&&!i.altKey&&!i.metaKey&&!i.ctrlKey&&(a=t.clickDetector,o=n,s=Hi(e.event),a.handleClick(o,s)),Ui(t,n)}}var a,o,s}}(t)),jt("history",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.from,n=t.to,r=Date.now()/1e3;return{type:"navigation.push",start:r,end:r,name:n,data:{previous:e}}}(e);null!==n&&(t.getContext().urls.push(n.name),t.triggerUserActivity(),t.addUpdate((function(){return ya(t,[n]),!1})))}}}(t)),ro(t),ct(function(t,e){void 0===e&&(e=!1);var n=e?ga(t):void 0;return function(e,r){if(function(t){return"replay_event"===t.type}(e))return delete e.breadcrumbs,e;if(!va(e)&&!_a(e))return e;if(function(t,e){return!(t.type||!t.exception||!t.exception.values||!t.exception.values.length)&&(!(!e.originalException||!e.originalException.__rrweb__)||t.exception.values.some((function(t){return!!(t.stacktrace&&t.stacktrace.frames&&t.stacktrace.frames.length)&&t.stacktrace.frames.some((function(t){return t.filename&&t.filename.includes("/rrweb/src/")}))})))}(e,r)&&!t.getOptions()._experiments.captureExceptions)return null;var i=function(t,e){return"buffer"===t.recordingMode&&e.message!==nr&&!(!e.exception||e.type)&&ua(t.getOptions().errorSampleRate)}(t,e);return(i||"session"===t.recordingMode)&&(e.tags=S({},e.tags,{replayId:t.getSessionId()})),n&&n(e,{statusCode:200}),e}}(t,!ao(n))),ao(n)&&(n.on("afterSendEvent",ga(t)),n.on("createDsc",(function(e){var n=t.getSessionId();n&&t.isEnabled()&&"session"===t.recordingMode&&(e.replay_id=n)})),n.on("startTransaction",(function(e){t.lastTransaction=e})),n.on("finishTransaction",(function(e){t.lastTransaction=e}))),this._hasInitializedCoreListeners=!0)}catch(t){this._handleException(t)}var t,e,n;"PerformanceObserver"in Qn&&(this._performanceObserver=function(t){var e=new PerformanceObserver((function(e){var n,r,i,a,o,s,u,c,l,d=(n=t.performanceEvents,r=e.getEntries(),i=n.reduce((function(t,e){return"navigation"===e.entryType?t[0].push(e):"largest-contentful-paint"===e.entryType?t[1].push(e):t[2].push(e),t}),[[],[],[]]),a=i[0],o=i[1],s=i[2],u=[],c=[],l=o.length?o[o.length-1]:void 0,r.forEach((function(t){if("largest-contentful-paint"!==t.entryType)if("navigation"!==t.entryType)u.push(t);else{var e=t;t.duration>0&&!a.find(Qi(e))&&!c.find(Qi(e))&&c.push(e)}else(!l||l.startTime";return Ki({category:"ui.keyDown",message:c,data:S({},Ji(o,c).data,{metaKey:e,shiftKey:n,ctrlKey:r,altKey:i,key:a})})}(e);n&&Ui(t,n)}}(t,e)}},t._doChangeToBackgroundTasks=function(t){if(this.session){var e=sa(this.session,this.timeouts);t&&!e&&this._createCustomBreadcrumb(t),this.conditionalFlush()}},t._doChangeToForegroundTasks=function(t){this.session&&this.checkAndHandleExpiredSession()&&t&&this._createCustomBreadcrumb(t)},t._triggerFullSnapshot=function(t){void 0===t&&(t=!0);try{Pi.takeFullSnapshot(t)}catch(t){this._handleException(t)}},t._updateUserActivity=function(t){void 0===t&&(t=Date.now()),this._lastActivity=t},t._updateSessionActivity=function(t){void 0===t&&(t=Date.now()),this.session&&(this.session.lastActivity=t,this._maybeSaveSession())},t._createCustomBreadcrumb=function(t){var e=this;this.addUpdate((function(){e.throttledAddEvent({type:Cr.Custom,timestamp:t.timestamp||0,data:{tag:"breadcrumb",payload:t}})}))},t._addPerformanceEntries=function(){var t=[].concat(this.performanceEvents);return this.performanceEvents=[],Promise.all(ya(this,function(t){return t.map(co).filter(Boolean)}(t)))},t._clearContext=function(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]},t._updateInitialTimestampFromEventBuffer=function(){var t=this.session,e=this.eventBuffer;if(t&&e&&!t.segmentId){var n=e.getEarliestTimestamp();n&&nr;if(n>t._options.mutationBreadcrumbLimit||i){var a=Ki({category:"replay.mutations",data:{count:n,limit:i}});t._createCustomBreadcrumb(a)}return!i||(t.stop("mutationLimit"),!1)}},e}();function So(t,e,n,r){var i="string"==typeof r?r.split(","):[],a=[].concat(t,i,e);return void 0!==n&&("string"==typeof n&&a.push("."+n),console.warn("[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.")),a.join(",")}function xo(){return"undefined"!=typeof window&&(!(0,Xn.KV)()||"undefined"!=typeof process&&"renderer"===process.type)}var Eo='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',To=["content-length","content-type","accept"],Co=!1,Io=function(){e.__initStatic=function(){this.id="Replay"};var t=e.prototype;function e(t){var n=void 0===t?{}:t,r=n.flushMinDelay,i=void 0===r?5e3:r,a=n.flushMaxDelay,o=void 0===a?5500:a,s=n.stickySession,u=void 0===s||s,c=n.useCompression,l=void 0===c||c,d=n._experiments,h=void 0===d?{}:d,p=n.sessionSampleRate,f=n.errorSampleRate,m=n.maskAllText,v=void 0===m||m,_=n.maskAllInputs,g=void 0===_||_,y=n.blockAllMedia,b=void 0===y||y,w=n.mutationBreadcrumbLimit,k=void 0===w?750:w,x=n.mutationLimit,E=void 0===x?1e4:x,T=n.slowClickTimeout,C=void 0===T?7e3:T,I=n.slowClickIgnoreSelectors,R=void 0===I?[]:I,O=n.networkDetailAllowUrls,A=void 0===O?[]:O,L=n.networkCaptureBodies,D=void 0===L||L,M=n.networkRequestHeaders,N=void 0===M?[]:M,z=n.networkResponseHeaders,j=void 0===z?[]:z,F=n.mask,P=void 0===F?[]:F,U=n.unmask,B=void 0===U?[]:U,H=n.block,q=void 0===H?[]:H,W=n.unblock,Z=void 0===W?[]:W,G=n.ignore,Y=void 0===G?[]:G,K=n.maskFn,X=n.beforeAddRecordingEvent,V=n.blockClass,J=n.blockSelector,$=n.maskInputOptions,Q=n.maskTextClass,tt=n.maskTextSelector,et=n.ignoreClass;if(e.prototype.__init.call(this),this._recordingOptions=S({maskAllInputs:g,maskAllText:v,maskInputOptions:S({},$||{},{password:!0}),maskTextFn:K,maskInputFn:K},function(t){var e=t.unmask,n=t.block,r=t.unblock,i=t.ignore,a=t.blockClass,o=t.blockSelector,s=t.maskTextClass,u=t.ignoreClass,c=So(t.mask,[".sentry-mask","[data-sentry-mask]"],s,t.maskTextSelector),l=So(e,[".sentry-unmask","[data-sentry-unmask]"]),d={maskTextSelector:c,unmaskTextSelector:l,maskInputSelector:c,unmaskInputSelector:l,blockSelector:So(n,[".sentry-block","[data-sentry-block]"].concat(['base[href="/"]']),a,o),unblockSelector:So(r,[".sentry-unblock","[data-sentry-unblock]"]),ignoreSelector:So(i,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'],u)};return a instanceof RegExp&&(d.blockClass=a),s instanceof RegExp&&(d.maskTextClass=s),d}({mask:P,unmask:B,block:q,unblock:Z,ignore:Y,blockClass:V,blockSelector:J,maskTextClass:Q,maskTextSelector:tt,ignoreClass:et}),{slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0}),this._initialOptions={flushMinDelay:i,flushMaxDelay:o,stickySession:u,sessionSampleRate:p,errorSampleRate:f,useCompression:l,blockAllMedia:b,maskAllInputs:g,maskAllText:v,mutationBreadcrumbLimit:k,mutationLimit:E,slowClickTimeout:C,slowClickIgnoreSelectors:R,networkDetailAllowUrls:A,networkCaptureBodies:D,networkRequestHeaders:Ro(N),networkResponseHeaders:Ro(j),beforeAddRecordingEvent:X,_experiments:h},"number"==typeof p&&(console.warn("[Replay] You are passing `sessionSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysSessionSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: "+p+" })"),this._initialOptions.sessionSampleRate=p),"number"==typeof f&&(console.warn("[Replay] You are passing `errorSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysOnErrorSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: "+f+" })"),this._initialOptions.errorSampleRate=f),this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?this._recordingOptions.blockSelector+","+Eo:Eo),this._isInitialized&&xo())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}return t.__init=function(){this.name=e.id},t.setupOnce=function(){var t=this;xo()&&(this._setup(),setTimeout((function(){return t._initialize()})))},t.start=function(){this._replay&&this._replay.start()},t.startBuffering=function(){this._replay&&this._replay.startBuffering()},t.stop=function(){return this._replay?this._replay.stop():Promise.resolve()},t.flush=function(t){return this._replay&&this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(t):Promise.resolve()},t.getReplayId=function(){if(this._replay&&this._replay.isEnabled())return this._replay.getSessionId()},t._initialize=function(){this._replay&&this._replay.initializeSampling()},t._setup=function(){var t=function(t){var e=ft().getClient(),n=e&&e.getOptions(),r=S({sessionSampleRate:0,errorSampleRate:0},F(t));return n?(null==t.sessionSampleRate&&null==t.errorSampleRate&&null==n.replaysSessionSampleRate&&null==n.replaysOnErrorSampleRate&&console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set."),"number"==typeof n.replaysSessionSampleRate&&(r.sessionSampleRate=n.replaysSessionSampleRate),"number"==typeof n.replaysOnErrorSampleRate&&(r.errorSampleRate=n.replaysOnErrorSampleRate),r):(console.warn("SDK client is not available."),r)}(this._initialOptions);this._replay=new ko({options:t,recordingOptions:this._recordingOptions})},Ce(e,[{key:"_isInitialized",get:function(){return Co},set:function(t){Co=t}}]),e}();function Ro(t){return[].concat(To,t.map((function(t){return t.toLowerCase()})))}Io.__initStatic();var Oo="7.56.0",Ao=function(t){function e(n,r){var i;return void 0===r&&(r="warn"),(i=t.call(this,n)||this).message=n,i.name=(this instanceof e?this.constructor:void 0).prototype.constructor.name,Object.setPrototypeOf(we(i),(this instanceof e?this.constructor:void 0).prototype),i.logLevel=r,i}return Se(e,t),e}(Tn(Error)),Lo="7";function Do(t){var e=t.protocol?t.protocol+":":"",n=t.port?":"+t.port:"";return e+"//"+t.host+n+(t.path?"/"+t.path:"")+"/api/"}function Mo(t,e){void 0===e&&(e={});var n="string"==typeof e?e:e.tunnel,r="string"!=typeof e&&e._metadata?e._metadata.sdk:void 0;return n||function(t){return""+Do(t)+t.projectId+"/envelope/"}(t)+"?"+function(t,e){return n=S({sentry_key:t.publicKey,sentry_version:Lo},e&&{sentry_client:e.name+"/"+e.version}),Object.keys(n).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])})).join("&");var n}(t,r)}var No=[];function zo(t,e){e[t.name]=t,-1===No.indexOf(t.name)&&(t.setupOnce(ct,ft),No.push(t.name))}function jo(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Fo(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Fo(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Fo(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},t._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._dsn},t._prepareEvent=function(t,e,n){var r=this.getOptions(),i=Object.keys(this._integrations);return!e.integrations&&i.length>0&&(e.integrations=i),An(r,t,e,n)},t._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){}))},t._processEvent=function(t,e,n){var r=this,i=this.getOptions(),a=i.sampleRate;if(!this._isEnabled())return it(new Ao("SDK not enabled, will not capture event.","log"));var o=Bo(t),s=Uo(t),u=t.type||"error",c="before send for type `"+u+"`";if(s&&"number"==typeof a&&Math.random()>a)return this.recordDroppedEvent("sample_rate","error",t),it(new Ao("Discarding event because it's not included in the random sample (sampling rate = "+a+")","log"));var l="replay_event"===u?"replay":u;return this._prepareEvent(t,e,n).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",l,t),new Ao("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var a=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;return Uo(e)&&r?r(e,n):Bo(e)&&i?i(e,n):e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(p(t))return t.then((function(t){if(!d(t)&&null!==t)throw new Ao(n);return t}),(function(t){throw new Ao(e+" rejected with "+t)}));if(!d(t)&&null!==t)throw new Ao(n);return t}(a,c)})).then((function(i){if(null===i)throw r.recordDroppedEvent("before_send",l,t),new Ao(c+" returned `null`, will not send event.","log");var a=n&&n.getSession();!o&&a&&r._updateSessionFromEvent(a,i);var s=i.transaction_info;return o&&s&&i.transaction!==t.transaction&&(i.transaction_info=S({},s,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof Ao)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new Ao("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},t._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},t._sendEnvelope=function(t){if(this._transport&&this._dsn)return this.emit("beforeEnvelope",t),this._transport.send(t).then(null,(function(t){}))},t._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},e}();function Uo(t){return void 0===t.type}function Bo(t){return"transaction"===t.type}var Ho=n(476),qo=function(t){function e(e){var n,r=_t.SENTRY_SDK_SOURCE||(0,Ho.S)();return e._metadata=e._metadata||{},e._metadata.sdk=e._metadata.sdk||{name:"sentry.javascript.browser",packages:[{name:r+":@sentry/browser",version:Oo}],version:Oo},n=t.call(this,e)||this,e.sendClientReports&&_t.document&&_t.document.addEventListener("visibilitychange",(function(){"hidden"===_t.document.visibilityState&&n._flushOutcomes()})),n}Se(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=ee(t,e,n&&n.syntheticException||void 0,r);return V(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),rt(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var a=ne(t,e,r&&r.syntheticException||void 0,i);return a.level=n,r&&r.event_id&&(a.event_id=r.event_id),rt(a)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.sendEvent=function(e,n){var r=this.getIntegrationById(he);r&&r.addSentryBreadcrumb&&r.addSentryBreadcrumb(e),t.prototype.sendEvent.call(this,e,n)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,a=S({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:Mn(i)}),o=function(t){return[{type:"user_report"},t]}(t);return Pn(a,[o])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,Pn((n=this._options.tunnel&&Mn(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:(0,Q.yW)(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(Po);function Wo(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Zo(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Zo(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Zo(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){rt(t).then((function(){--i||(clearTimeout(a),n(!0))}),r)}))}))}}}(t.bufferSize||Yo));var r={};function i(i){var a=[];if(Un(i,(function(e,n){var i,o,s,u=Zn(n);if(i=r,o=u,void 0===s&&(s=Date.now()),function(t,e){return t[e]||t.all||0}(i,o)>s){var c=Xo(e,n);t.recordDroppedEvent("ratelimit_backoff",u,c)}else a.push(e)})),0===a.length)return rt();var o=Pn(i[0],a),s=function(e){Un(o,(function(n,r){var i=Xo(n,r);t.recordDroppedEvent(e,Zn(r),i)}))};return n.add((function(){return e({body:Hn(o,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var a=S({},t),o=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(o)for(var u,c=Wo(o.trim().split(","));!(u=c()).done;){var l=u.value.split(":",2),d=l[0],h=l[1],p=parseInt(d,10),f=1e3*(isNaN(p)?60:p);if(h)for(var m,v=Wo(h.split(";"));!(m=v()).done;)a[m.value]=n+f;else a.all=n+f}else s?a.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?Go:r-e}(s,n):429===r&&(a.all=n+6e4);return a}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof Ao)return s("queue_overflow"),rt();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function Xo(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var Vo=void 0;function Jo(t,e){void 0===e&&(e=function(){if(Vo)return Vo;if(It(_t.fetch))return Vo=_t.fetch.bind(_t);var t=_t.document,e=_t.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return Vo=e.bind(_t)}());var n=0,r=0;return Ko(t,(function(i){var a=i.body.length;n+=a,r++;var o=S({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,o).then((function(t){return n-=a,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return Vo=void 0,n-=a,r--,it(t)}}))}var $o="?";function Qo(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var ts=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,es=/\((\S*)(?::(\d+))(?::(\d+))\)/,ns=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,rs=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,is=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,as=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=q.test(o)?o.replace(q,"$1"):o;if(!s.match(/\S*Error: /)){for(var u,c=B(r);!(u=c()).done;){var l=(0,u.value)(s);if(l){n.push(l);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=t.slice(0,50),n=e[e.length-1].function;n&&/sentryWrapped/.test(n)&&e.pop(),e.reverse();var r=e[e.length-1].function;return r&&/captureMessage|captureException/.test(r)&&e.pop(),e.map((function(t){return S({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=ts.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=es.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=os(e[1]||$o,e[2]),i=r[0];return Qo(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=ns.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=rs.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||$o,a=os(i,r);return i=a[0],Qo(r=a[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=is.exec(t);return e?Qo(e[2],e[1]||$o,+e[3],e[4]?+e[4]:void 0):void 0}]]),os=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:$o,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},ss=function(){function t(){t.prototype.__init.call(this)}t.__initStatic=function(){this.id="Dedupe"};var e=t.prototype;return e.__init=function(){this.name=t.id},e.setupOnce=function(e,n){var r=function(e){if(e.type)return e;var r=n().getIntegration(t);if(r){try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!cs(t,e)&&!!us(t,e))))}(t,e)||!!function(t,e){var n=ls(e),r=ls(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!cs(t,e)&&!!us(t,e)))}(t,e))}(e,r._previousEvent))return null}catch(t){return r._previousEvent=e}return r._previousEvent=e}return e};r.id=this.name,e(r)},t}();function us(t,e){var n=ds(t),r=ds(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i{var t={495:(t,e,n)=>{"use strict";function r(){return!("undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&__SENTRY_BROWSER_BUNDLE__)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}n.d(e,{KV:()=>r}),t=n.hmd(t)},648:(t,e,n)=>{var r=n(288).default;function i(){"use strict";t.exports=i=function(){return e},t.exports.__esModule=!0,t.exports.default=t.exports;var e={},n=Object.prototype,o=n.hasOwnProperty,a=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",u=s.asyncIterator||"@@asyncIterator",l=s.toStringTag||"@@toStringTag";function d(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{d({},"")}catch(t){d=function(t,e,n){return t[e]=n}}function p(t,e,n,r){var i=e&&e.prototype instanceof m?e:m,o=Object.create(i.prototype),s=new C(r||[]);return a(o,"_invoke",{value:w(t,n,s)}),o}function f(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=p;var h={};function m(){}function v(){}function g(){}var y={};d(y,c,(function(){return this}));var _=Object.getPrototypeOf,b=_&&_(_(R([])));b&&b!==n&&o.call(b,c)&&(y=b);var S=g.prototype=m.prototype=Object.create(y);function k(t){["next","throw","return"].forEach((function(e){d(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){function n(i,a,s,c){var u=f(t[i],t,a);if("throw"!==u.type){var l=u.arg,d=l.value;return d&&"object"==r(d)&&o.call(d,"__await")?e.resolve(d.__await).then((function(t){n("next",t,s,c)}),(function(t){n("throw",t,s,c)})):e.resolve(d).then((function(t){l.value=t,s(l)}),(function(t){return n("throw",t,s,c)}))}c(u.arg)}var i;a(this,"_invoke",{value:function(t,r){function o(){return new e((function(e,i){n(t,r,e,i)}))}return i=i?i.then(o,o):o()}})}function w(t,e,n){var r="suspendedStart";return function(i,o){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw o;return{value:void 0,done:!0}}for(n.method=i,n.arg=o;;){var a=n.delegate;if(a){var s=E(a,n);if(s){if(s===h)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var c=f(t,e,n);if("normal"===c.type){if(r=n.done?"completed":"suspendedYield",c.arg===h)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r="completed",n.method="throw",n.arg=c.arg)}}}function E(t,e){var n=e.method,r=t.iterator[n];if(void 0===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=void 0,E(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),h;var i=f(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function I(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function C(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function R(t){if(t){var e=t[c];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n=0;--r){var i=this.tryEntries[r],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=o.call(i,"catchLoc"),c=o.call(i,"finallyLoc");if(s&&c){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),I(n),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;I(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:R(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),h}},e}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports},288:t=>{function e(n){return t.exports=e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.__esModule=!0,t.exports.default=t.exports,e(n)}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports},357:(t,e,n)=>{var r=n(648)();t.exports=r;try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var o=e[r]={id:r,loaded:!1,exports:{}};return t[r](o,o.exports,n),o.loaded=!0,o.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.hmd=t=>((t=Object.create(t)).children||(t.children=[]),Object.defineProperty(t,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+t.id)}}),t),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r);const t=flarum.core.compat["forum/app"];var e=n.n(t),i=!1;function o(t){return t&&t.Math==Math?t:void 0}var a="object"==typeof globalThis&&o(globalThis)||"object"==typeof window&&o(window)||"object"==typeof self&&o(self)||"object"==typeof n.g&&o(n.g)||function(){return this}()||{};function s(){return a}function c(t,e,n){var r=n||a,i=r.__SENTRY__=r.__SENTRY__||{};return i[t]||(i[t]=e())}var u=["debug","info","warn","error","log","assert","trace"],l={};function d(t){if(!("console"in a))return t();var e=a.console,n={},r=Object.keys(l);r.forEach((function(t){var r=l[t];n[t]=e[t],e[t]=r}));try{return t()}finally{r.forEach((function(t){e[t]=n[t]}))}}var p,f,h=(p=!1,f={enable:function(){p=!0},disable:function(){p=!1},isEnabled:function(){return p}},i?u.forEach((function(t){f[t]=function(){for(var e=arguments.length,n=new Array(e),r=0;r";try{for(var n,r=t,i=[],o=0,a=0,s=Array.isArray(e)?e:e.keyAttrs,c=!Array.isArray(e)&&e.maxStringLength||M;r&&o++<5&&!("html"===(n=D(r,s))||o>1&&a+3*i.length+n.length>=c);)i.push(n),a+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function D(t,e){var n,r,i,o,a,s=t,c=[];if(!s||!s.tagName)return"";if(O.HTMLElement&&s instanceof HTMLElement&&s.dataset&&s.dataset.sentryComponent)return s.dataset.sentryComponent;c.push(s.tagName.toLowerCase());var u=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(u&&u.length)u.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&c.push("#"+s.id),(n=s.className)&&S(n))for(r=n.split(/\s+/),a=0;a"}}function W(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function Y(t){return J(t,new Map)}function J(t,e){if(function(t){if(!w(t))return!1;try{var e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,o=Object.keys(t);i>t/4).toString(16)}))}function K(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function G(t){var e=t.message,n=t.event_id;if(e)return e;var r=K(t);return r?r.type&&r.value?r.type+": "+r.value:r.type||r.value||n||"":n||""}function $(t,e,n){var r=t.exception=t.exception||{},i=r.values=r.values||[],o=i[0]=i[0]||{};o.value||(o.value=e||""),o.type||(o.type=n||"Error")}function X(t,e){var n=K(t);if(n){var r=n.mechanism;if(n.mechanism=m({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=m({},r&&r.data,e.data);n.mechanism.data=i}}}function Q(t){if(t&&t.__sentry_captured__)return!0;try{U(t,"__sentry_captured__",!0)}catch(t){}return!1}var Z,tt=!1;function et(t){return new rt((function(e){e(t)}))}function nt(t){return new rt((function(e,n){n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(Z||(Z={}));var rt=function(){function t(e){t.prototype.__init.call(this),t.prototype.__init2.call(this),t.prototype.__init3.call(this),t.prototype.__init4.call(this),this._state=Z.PENDING,this._handlers=[];try{e(this._resolve,this._reject)}catch(t){this._reject(t)}}var e=t.prototype;return e.then=function(e,n){var r=this;return new t((function(t,i){r._handlers.push([!1,function(n){if(e)try{t(e(n))}catch(t){i(t)}else t(n)},function(e){if(n)try{t(n(e))}catch(t){i(t)}else i(e)}]),r._executeHandlers()}))},e.catch=function(t){return this.then((function(t){return t}),t)},e.finally=function(e){var n=this;return new t((function(t,r){var i,o;return n.then((function(t){o=!1,i=t,e&&e()}),(function(t){o=!0,i=t,e&&e()})).then((function(){o?r(i):t(i)}))}))},e.__init=function(){var t=this;this._resolve=function(e){t._setResult(Z.RESOLVED,e)}},e.__init2=function(){var t=this;this._reject=function(e){t._setResult(Z.REJECTED,e)}},e.__init3=function(){var t=this;this._setResult=function(e,n){t._state===Z.PENDING&&(T(n)?n.then(t._resolve,t._reject):(t._state=e,t._value=n,t._executeHandlers()))}},e.__init4=function(){var t=this;this._executeHandlers=function(){if(t._state!==Z.PENDING){var e=t._handlers.slice();t._handlers=[],e.forEach((function(e){e[0]||(t._state===Z.RESOLVED&&e[1](t._value),t._state===Z.REJECTED&&e[2](t._value),e[0]=!0)}))}}},t}();function it(){return c("globalEventProcessors",(function(){return[]}))}function ot(t){it().push(t)}function at(t,e,n,r){return void 0===r&&(r=0),new rt((function(i,o){var a=t[r];if(null===e||"function"!=typeof a)i(e);else{var s=a(m({},e),n);tt&&a.id&&null===s&&h.log('Event processor "'+a.id+'" dropped event'),T(s)?s.then((function(e){return at(t,e,n,r+1).then(i)})).then(null,o):at(t,s,n,r+1).then(i).then(null,o)}}))}var st=1e3;function ct(){return Date.now()/st}var ut=function(){var t=a.performance;if(!t||!t.now)return ct;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/st}}(),lt=function(){var t=a.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}var ft=n(357),ht=n.n(ft);function mt(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return vt(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?vt(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function vt(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nn?kt(t,e-1,n):i}function xt(t,e,r,i,o){var a,s;void 0===r&&(r=1/0),void 0===i&&(i=1/0),void 0===o&&(a="function"==typeof WeakSet,s=a?new WeakSet:[],o=[function(t){if(a)return!!s.has(t)||(s.add(t),!1);for(var e=0;e=i){h[g]="[MaxProperties ~]";break}var y=v[g];h[g]=xt(g,y,p-1,i,o),m++}return l(e),h}var wt="baggage",Et="sentry-",Tt=/^sentry-/,It=8192;function Ct(t){if(t)return function(t){if(0!==Object.keys(t).length)return Object.entries(t).reduce((function(t,e,n){var r=e[0],o=e[1],a=encodeURIComponent(r)+"="+encodeURIComponent(o),s=0===n?a:t+","+a;return s.length>It?(i&&h.warn("Not adding key: "+r+" with val: "+o+" to baggage header due to exceeding baggage size limits."),t):s}),"")}(Object.entries(t).reduce((function(t,e){var n=e[0],r=e[1];return r&&(t[""+Et+n]=r),t}),{}))}function Rt(t){return t.split(",").map((function(t){return t.split("=").map((function(t){return decodeURIComponent(t.trim())}))})).reduce((function(t,e){var n=e[0],r=e[1];return t[n]=r,t}),{})}var Ot=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function Mt(t,e){var n=function(t){if(t){var e,n=t.match(Ot);if(n)return"1"===n[3]?e=!0:"0"===n[3]&&(e=!1),{traceId:n[1],parentSampled:e,parentSpanId:n[2]}}}(t),r=function(t){if(S(t)||Array.isArray(t)){var e={};if(Array.isArray(t))e=t.reduce((function(t,e){for(var n=Rt(e),r=0,i=Object.keys(n);r0?n:void 0}}(e),i=n||{},o=i.traceId,a=i.parentSpanId,s=i.parentSampled;return n?{traceId:o||V(),parentSpanId:a||V().substring(16),spanId:V().substring(16),sampled:s,dsc:r||{}}:{traceId:o||V(),spanId:V().substring(16)}}function At(t,e,n){void 0===t&&(t=V()),void 0===e&&(e=V().substring(16));var r="";return void 0!==n&&(r=n?"-1":"-0"),t+"-"+e+r}var Dt=1;function Nt(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=Ft(t);return Y({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function Lt(t){var e=t.spanContext();return At(e.traceId,e.spanId,Ut(t))}function Pt(t){return"number"==typeof t?jt(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?jt(t.getTime()):ut()}function jt(t){return t>9999999999?t/1e3:t}function Ft(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function Ut(t){var e=t.spanContext().traceFlags;return Boolean(e&Dt)}var Bt=new WeakMap;var Ht=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function zt(t,e){return ae().captureEvent(t,e)}function qt(t,e){ae().addBreadcrumb(t,e)}function Wt(){return ae().getClient()}function Yt(){return ae().getScope()}function Jt(t){return t.transaction}function Vt(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=Y({environment:r.environment||dt,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}function Kt(t){var e=Wt();if(!e)return{};var n=Vt(Ft(t).trace_id||"",e,Yt()),r=Jt(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=Ft(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(Ut(r)),e.emit&&e.emit("createDsc",n),n}function Gt(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=Y(n);c&&Object.keys(c).length&&(t.extra=m({},c,t.extra));var u=Y(r);u&&Object.keys(u).length&&(t.tags=m({},u,t.tags));var l=Y(i);l&&Object.keys(l).length&&(t.user=m({},l,t.user));var d=Y(o);d&&Object.keys(d).length&&(t.contexts=m({},d,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=m({trace:Nt(e)},t.contexts);var n=Jt(e);if(n){t.sdkProcessingMetadata=m({dynamicSamplingContext:Kt(e)},t.sdkProcessingMetadata);var r=Ft(n).description;r&&(t.tags=m({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=m({},t.sdkProcessingMetadata,e)}(t,o)}function $t(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.sdkProcessingMetadata,c=e.breadcrumbs,u=e.fingerprint,l=e.eventProcessors,d=e.attachments,p=e.propagationContext,f=e.transactionName,h=e.span;Xt(t,"extra",n),Xt(t,"tags",r),Xt(t,"user",i),Xt(t,"contexts",o),Xt(t,"sdkProcessingMetadata",s),a&&(t.level=a),f&&(t.transactionName=f),h&&(t.span=h),c.length&&(t.breadcrumbs=[].concat(t.breadcrumbs,c)),u.length&&(t.fingerprint=[].concat(t.fingerprint,u)),l.length&&(t.eventProcessors=[].concat(t.eventProcessors,l)),d.length&&(t.attachments=[].concat(t.attachments,d)),t.propagationContext=m({},t.propagationContext,p)}function Xt(t,e,n){if(n&&Object.keys(n).length)for(var r in t[e]=m({},t[e]),n)Object.prototype.hasOwnProperty.call(n,r)&&(t[e][r]=n[r])}var Qt,Zt=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=te()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=m({},this._tags),e._extra=m({},this._extra),e._contexts=m({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=m({},this._sdkProcessingMetadata),e._propagationContext=m({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&pt(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=m({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=m({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=m({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=m({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=m({},this._tags,r.tags),this._extra=m({},this._extra,r.extra),this._contexts=m({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(w(n)){var i=e;this._tags=m({},this._tags,i.tags),this._extra=m({},this._extra,i.extra),this._contexts=m({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=te(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=m({timestamp:ct()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),Gt(t,this.getScopeData()),at([].concat(n,it(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=m({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:V();if(!this._client)return h.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,m({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:V();if(!this._client)return h.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,m({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:V();return this._client?(this._client.captureEvent(t,m({},e,{event_id:n}),this),n):(h.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function te(){return{traceId:V(),spanId:V().substring(16)}}var ee="7.119.1",ne=parseFloat(ee),re=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=ne),this._version=r,e?i=e:(i=new Zt).setClient(t),n?o=n:(o=new Zt).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(n=r()).done;){var i=n.value;i&&i.afterAllSetup&&i.afterAllSetup(t)}}function fe(t,e,n){if(n[e.name])tt&&h.log("Integration skipped because it was already installed: "+e.name);else{if(n[e.name]=e,-1===de.indexOf(e.name)&&(e.setupOnce(ot,ae),de.push(e.name)),e.setup&&"function"==typeof e.setup&&e.setup(t),t.on&&"function"==typeof e.preprocessEvent){var r=e.preprocessEvent.bind(e);t.on("preprocessEvent",(function(e,n){return r(e,n,t)}))}if(t.addEventProcessor&&"function"==typeof e.processEvent){var i=e.processEvent.bind(e),o=Object.assign((function(e,n){return i(e,n,t)}),{id:e.name});t.addEventProcessor(o)}tt&&h.log("Integration installed: "+e.name)}}function he(t,e){return Object.assign((function(){return e.apply(void 0,arguments)}),{id:t})}var me,ve=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/],ge=[/^.*\/healthcheck$/,/^.*\/healthy$/,/^.*\/live$/,/^.*\/ready$/,/^.*\/heartbeat$/,/^.*\/health$/,/^.*\/healthz$/],ye="InboundFilters",_e=function(t){return void 0===t&&(t={}),{name:ye,setupOnce:function(){},processEvent:function(e,n,r){var i=r.getOptions(),o=function(t,e){return void 0===t&&(t={}),void 0===e&&(e={}),{allowUrls:[].concat(t.allowUrls||[],e.allowUrls||[]),denyUrls:[].concat(t.denyUrls||[],e.denyUrls||[]),ignoreErrors:[].concat(t.ignoreErrors||[],e.ignoreErrors||[],t.disableErrorDefaults?[]:ve),ignoreTransactions:[].concat(t.ignoreTransactions||[],e.ignoreTransactions||[],t.disableTransactionDefaults?[]:ge),ignoreInternal:void 0===t.ignoreInternal||t.ignoreInternal}}(t,i);return function(t,e){return e.ignoreInternal&&function(t){try{return"SentryError"===t.exception.values[0].type}catch(t){}return!1}(t)?(tt&&h.warn("Event dropped due to being internal Sentry Error.\nEvent: "+G(t)),!0):function(t,e){return!(t.type||!e||!e.length)&&function(t){var e,n=[];t.message&&n.push(t.message);try{e=t.exception.values[t.exception.values.length-1]}catch(t){}return e&&e.value&&(n.push(e.value),e.type&&n.push(e.type+": "+e.value)),tt&&0===n.length&&h.error("Could not extract message for event "+G(t)),n}(t).some((function(t){return j(t,e)}))}(t,e.ignoreErrors)?(tt&&h.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: "+G(t)),!0):function(t,e){if("transaction"!==t.type||!e||!e.length)return!1;var n=t.transaction;return!!n&&j(n,e)}(t,e.ignoreTransactions)?(tt&&h.warn("Event dropped due to being matched by `ignoreTransactions` option.\nEvent: "+G(t)),!0):function(t,e){if(!e||!e.length)return!1;var n=Se(t);return!!n&&j(n,e)}(t,e.denyUrls)?(tt&&h.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: "+G(t)+".\nUrl: "+Se(t)),!0):!function(t,e){if(!e||!e.length)return!0;var n=Se(t);return!n||j(n,e)}(t,e.allowUrls)&&(tt&&h.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: "+G(t)+".\nUrl: "+Se(t)),!0)}(e,o)?null:e}}},be=he(ye,_e);function Se(t){try{var e;try{e=t.exception.values[0].stacktrace.frames}catch(t){}return e?function(t){void 0===t&&(t=[]);for(var e=t.length-1;e>=0;e--){var n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(e){return tt&&h.error("Cannot extract url for event "+G(t)),null}}var ke="FunctionToString",xe=new WeakMap,we=function(){return{name:ke,setupOnce:function(){me=Function.prototype.toString;try{Function.prototype.toString=function(){for(var t=H(this),e=xe.has(Wt())&&void 0!==t?t:this,n=arguments.length,r=new Array(n),i=0;i0}function Re(t,e,n){if(void 0===e&&(e={}),"function"!=typeof t)return t;try{var r=t.__sentry_wrapped__;if(r)return"function"==typeof r?r:t;if(H(t))return t}catch(e){return t}var i=function(){var r=Array.prototype.slice.call(arguments);try{n&&"function"==typeof n&&n.apply(this,arguments);var i=r.map((function(t){return Re(t,e)}));return t.apply(this,i)}catch(t){throw Ie++,setTimeout((function(){Ie--})),function(){for(var t=ae(),e=arguments.length,n=new Array(e),r=0;rt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=o()).done;){var a=r.value;try{a(e)}catch(e){i&&h.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+bt(a)+"\nError:",e)}}}var We=null;function Ye(t){var e="error";He(e,t),ze(e,Je)}function Je(){We=a.onerror,a.onerror=function(t,e,n,r,i){return qe("error",{column:r,error:i,line:n,msg:t,url:e}),!(!We||We.__SENTRY_LOADER__)&&We.apply(this,arguments)},a.onerror.__SENTRY_INSTRUMENTED__=!0}var Ve=null;function Ke(t){var e="unhandledrejection";He(e,t),ze(e,Ge)}function Ge(){Ve=a.onunhandledrejection,a.onunhandledrejection=function(t){return qe("unhandledrejection",t),!(Ve&&!Ve.__SENTRY_LOADER__)||Ve.apply(this,arguments)},a.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function $e(t,e){var n=Qe(t,e),r={type:e&&e.name,value:tn(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Xe(t,e){return{exception:{values:[$e(t,e)]}}}function Qe(t,e){var n=e.stacktrace||e.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(Ze.test(t.message))return 1}return 0}(e);try{return t(n,r)}catch(t){}return[]}var Ze=/Minified React error #\d+;/i;function tn(t){var e=t&&t.message;return e?e.error&&"string"==typeof e.error.message?e.error.message:e:"No error message"}function en(t,e,n,r,i){var o;if(_(e)&&e.error)return Xe(t,e.error);if(b(e)||y(e,"DOMException")){var a=e;if("stack"in e)o=Xe(t,e);else{var s=a.name||(b(a)?"DOMError":"DOMException"),c=a.message?s+": "+a.message:s;$(o=nn(t,c,n,r),c)}return"code"in a&&(o.tags=m({},o.tags,{"DOMException.code":""+a.code})),o}return g(e)?Xe(t,e):w(e)||E(e)?(o=function(t,e,n,r){var i=Wt(),o=i&&i.getOptions().normalizeDepth,a={exception:{values:[{type:E(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:rn(e,{isUnhandledRejection:r})}]},extra:{__serialized__:kt(e,o)}};if(n){var s=Qe(t,n);s.length&&(a.exception.values[0].stacktrace={frames:s})}return a}(t,e,n,i),X(o,{synthetic:!0}),o):($(o=nn(t,e,n,r),""+e,void 0),X(o,{synthetic:!0}),o)}function nn(t,e,n,r){var i={};if(r&&n){var o=Qe(t,n);o.length&&(i.exception={values:[{value:e,stacktrace:{frames:o}}]})}if(k(e)){var a=e.__sentry_template_string__,s=e.__sentry_template_values__;return i.logentry={message:a,params:s},i}return i.message=e,i}function rn(t,e){var n=e.isUnhandledRejection,r=function(t,e){void 0===e&&(e=40);var n=Object.keys(z(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return L(n[0],e);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length?i:L(i,e)}return""}(t),i=n?"promise rejection":"exception";return _(t)?"Event `ErrorEvent` captured as "+i+" with message `"+t.message+"`":E(t)?"Event `"+function(t){try{var e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch(t){}}(t)+"` (type="+t.type+") captured as "+i:"Object captured as "+i+" with keys: "+r}var on="GlobalHandlers",an=function(t){void 0===t&&(t={});var e=m({onerror:!0,onunhandledrejection:!0},t);return{name:on,setupOnce:function(){Error.stackTraceLimit=50},setup:function(t){e.onerror&&(function(t){Ye((function(e){var n=ln(),r=n.stackParser,i=n.attachStacktrace;if(Wt()===t&&!Ce()){var o=e.msg,a=e.url,s=e.line,c=e.column,u=e.error,l=void 0===u&&S(o)?function(t,e,n,r){var i=_(t)?t.message:t,o="Error",a=i.match(/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i);return a&&(o=a[1],i=a[2]),cn({exception:{values:[{type:o,value:i}]}},e,n,r)}(o,a,s,c):cn(en(r,u||o,void 0,i,!1),a,s,c);l.level="error",zt(l,{originalException:u,mechanism:{handled:!1,type:"onerror"}})}}))}(t),un("onerror")),e.onunhandledrejection&&(function(t){Ke((function(e){var n=ln(),r=n.stackParser,i=n.attachStacktrace;if(Wt()===t&&!Ce()){var o=function(t){if(x(t))return t;var e=t;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch(t){}return t}(e),a=x(o)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(o)}]}}:en(r,o,void 0,i,!0);a.level="error",zt(a,{originalException:o,mechanism:{handled:!1,type:"onunhandledrejection"}})}}))}(t),un("onunhandledrejection"))}}},sn=he(on,an);function cn(t,e,n,r){var i=t.exception=t.exception||{},o=i.values=i.values||[],a=o[0]=o[0]||{},s=a.stacktrace=a.stacktrace||{},c=s.frames=s.frames||[],u=isNaN(parseInt(r,10))?void 0:r,l=isNaN(parseInt(n,10))?void 0:n,d=S(e)&&e.length>0?e:function(){try{return O.document.location.href}catch(t){return""}}();return 0===c.length&&c.push({colno:u,filename:d,function:"?",in_app:!0,lineno:l}),t}function un(t){}function ln(){var t=Wt();return t&&t.getOptions()||{stackParser:function(){return[]},attachStacktrace:!1}}function dn(){"console"in a&&u.forEach((function(t){t in a.console&&F(a.console,t,(function(e){return l[t]=e,function(){for(var e=arguments.length,n=new Array(e),r=0;r2?n[2]:void 0;if(i){var o=Rn,a=String(i);Rn=a,qe("history",{from:o,to:a})}return t.apply(this,n)}}}var Nn=["fatal","error","warning","log","info","debug"];function Ln(t){if(!t)return{};var e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}var Pn=1024,jn="Breadcrumbs",Fn=function(t){void 0===t&&(t={});var e=m({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},t);return{name:jn,setupOnce:function(){},setup:function(t){var n;e.console&&(n=function(t){return function(e){if(Wt()===t){var n={category:"console",data:{arguments:e.args,logger:"console"},level:(r=e.level,"warn"===r?"warning":Nn.includes(r)?r:"log"),message:P(e.args," ")};if("assert"===e.level){if(!1!==e.args[0])return;n.message="Assertion failed: "+(P(e.args.slice(1)," ")||"console.assert"),n.data.arguments=e.args.slice(1)}qt(n,{input:e.args,level:e.level})}var r}}(t),He("console",n),ze("console",dn)),e.dom&&function(t){He("dom",t),ze("dom",gn)}(function(t,e){return function(n){if(Wt()===t){var r,i,o="object"==typeof e?e.serializeAttribute:void 0,a="object"==typeof e&&"number"==typeof e.maxStringLength?e.maxStringLength:void 0;a&&a>Pn&&(a=Pn),"string"==typeof o&&(o=[o]);try{var s=n.event,c=function(t){return!!t&&!!t.target}(s)?s.target:s;r=A(c,{keyAttrs:o,maxStringLength:a}),i=N(c)}catch(t){r=""}if(0!==r.length){var u={category:"ui."+n.name,message:r};i&&(u.data={"ui.component_name":i}),qt(u,{event:n.event,name:n.name,global:n.global})}}}}(t,e.dom)),e.xhr&&Sn(function(t){return function(e){if(Wt()===t){var n=e.startTimestamp,r=e.endTimestamp,i=e.xhr[bn];if(n&&r&&i){var o=i.method,a=i.url,s=i.status_code,c=i.body;qt({category:"xhr",data:{method:o,url:a,status_code:s},type:"http"},{xhr:e.xhr,input:c,startTimestamp:n,endTimestamp:r})}}}}(t)),e.fetch&&En(function(t){return function(e){if(Wt()===t){var n=e.startTimestamp,r=e.endTimestamp;if(r&&(!e.fetchData.url.match(/sentry_key/)||"POST"!==e.fetchData.method))if(e.error)qt({category:"fetch",data:e.fetchData,level:"error",type:"http"},{data:e.error,input:e.args,startTimestamp:n,endTimestamp:r});else{var i=e.response;qt({category:"fetch",data:m({},e.fetchData,{status_code:i&&i.status}),type:"http"},{input:e.args,response:i,startTimestamp:n,endTimestamp:r})}}}}(t)),e.history&&An(function(t){return function(e){if(Wt()===t){var n=e.from,r=e.to,i=Ln(Te.location.href),o=n?Ln(n):void 0,a=Ln(r);o&&o.path||(o=i),i.protocol===a.protocol&&i.host===a.host&&(r=a.relative),i.protocol===o.protocol&&i.host===o.host&&(n=o.relative),qt({category:"navigation",data:{from:n,to:r}})}}}(t)),e.sentry&&t.on&&t.on("beforeSendEvent",function(t){return function(e){Wt()===t&&qt({category:"sentry."+("transaction"===e.type?"transaction":"event"),event_id:e.event_id,level:e.level,message:G(e)},{event:e})}}(t))}}},Un=he(jn,Fn);function Bn(t,e,n,r,i,o,a){if(void 0===n&&(n=250),o.exception&&o.exception.values&&a&&C(a.originalException,Error)){var s,c,u=o.exception.values.length>0?o.exception.values[o.exception.values.length-1]:void 0;u&&(o.exception.values=(s=Hn(t,e,i,a.originalException,r,o.exception.values,u,0),c=n,s.map((function(t){return t.value&&(t.value=L(t.value,c)),t}))))}}function Hn(t,e,n,r,i,o,a,s){if(o.length>=n+1)return o;var c=[].concat(o);if(C(r[i],Error)){zn(a,s);var u=t(e,r[i]),l=c.length;qn(u,i,l,s),c=Hn(t,e,n,r[i],i,[u].concat(c),u,l)}return Array.isArray(r.errors)&&r.errors.forEach((function(r,o){if(C(r,Error)){zn(a,s);var u=t(e,r),l=c.length;qn(u,"errors["+o+"]",l,s),c=Hn(t,e,n,r,i,[u].concat(c),u,l)}})),c}function zn(t,e){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=m({},t.mechanism,"AggregateError"===t.type&&{is_exception_group:!0},{exception_id:e})}function qn(t,e,n,r){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism=m({},t.mechanism,{type:"chained",source:e,exception_id:n,parent_id:r})}var Wn,Yn="LinkedErrors",Jn=function(t){void 0===t&&(t={});var e=t.limit||5,n=t.key||"cause";return{name:Yn,setupOnce:function(){},preprocessEvent:function(t,r,i){var o=i.getOptions();Bn($e,o.stackParser,o.maxValueLength,n,e,t,r)}}},Vn=he(Yn,Jn),Kn="HttpContext",Gn=function(){return{name:Kn,setupOnce:function(){},preprocessEvent:function(t){if(Te.navigator||Te.location||Te.document){var e=t.request&&t.request.url||Te.location&&Te.location.href,n=(Te.document||{}).referrer,r=(Te.navigator||{}).userAgent,i=m({},t.request&&t.request.headers,n&&{Referer:n},r&&{"User-Agent":r}),o=m({},t.request,e&&{url:e},{headers:i});t.request=o}}}},$n=he(Kn,Gn);function Xn(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Qn(t,e){return Qn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},Qn(t,e)}function Zn(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Qn(t,e)}function tr(t){return tr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tr(t)}function er(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(e);!(n=i()).done;){var o=n.value[1],a=o[0],s=o[1];r[a]||(r[a]=[]),r[a].push(Y(s))}return r}}var or,ar="sentry.source",sr="sentry.sample_rate",cr="sentry.op",ur="sentry.origin";function lr(t,e){t.setTag("http.status_code",String(e)),t.setData("http.response.status_code",e);var n=function(t){if(t<400&&t>=100)return"ok";if(t>=400&&t<500)switch(t){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(t>=500&&t<600)switch(t){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"}(e);"unknown_error"!==n&&t.setStatus(n)}!function(t){t.Ok="ok",t.DeadlineExceeded="deadline_exceeded",t.Unauthenticated="unauthenticated",t.PermissionDenied="permission_denied",t.NotFound="not_found",t.ResourceExhausted="resource_exhausted",t.InvalidArgument="invalid_argument",t.Unimplemented="unimplemented",t.Unavailable="unavailable",t.InternalError="internal_error",t.UnknownError="unknown_error",t.Cancelled="cancelled",t.AlreadyExists="already_exists",t.FailedPrecondition="failed_precondition",t.Aborted="aborted",t.OutOfRange="out_of_range",t.DataLoss="data_loss"}(or||(or={}));var dr=function(){function t(t){void 0===t&&(t=1e3),this._maxlen=t,this.spans=[]}return t.prototype.add=function(t){this.spans.length>this._maxlen?t.spanRecorder=void 0:this.spans.push(t)},t}(),pr=function(){function t(t){var e;void 0===t&&(t={}),this._traceId=t.traceId||V(),this._spanId=t.spanId||V().substring(16),this._startTime=t.startTimestamp||ut(),this.tags=t.tags?m({},t.tags):{},this.data=t.data?m({},t.data):{},this.instrumenter=t.instrumenter||"sentry",this._attributes={},this.setAttributes(m(((e={})[ur]=t.origin||"manual",e[cr]=t.op,e),t.attributes)),this._name=t.name||t.description,t.parentSpanId&&(this._parentSpanId=t.parentSpanId),"sampled"in t&&(this._sampled=t.sampled),t.status&&(this._status=t.status),t.endTimestamp&&(this._endTime=t.endTimestamp),void 0!==t.exclusiveTime&&(this._exclusiveTime=t.exclusiveTime),this._measurements=t.measurements?m({},t.measurements):{}}var e=t.prototype;return e.spanContext=function(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:this._sampled?Dt:0}},e.startChild=function(e){var n=new t(m({},e,{parentSpanId:this._spanId,sampled:this._sampled,traceId:this._traceId}));n.spanRecorder=this.spanRecorder,n.spanRecorder&&n.spanRecorder.add(n);var r=Jt(this);if(n.transaction=r,tt&&r){var i="[Tracing] Starting '"+(e&&e.op||"< unknown op >")+"' span on transaction '"+(Ft(n).description||"< unknown name >")+"' ("+r.spanContext().spanId+").";h.log(i),this._logMessage=i}return n},e.setTag=function(t,e){var n;return this.tags=m({},this.tags,((n={})[t]=e,n)),this},e.setData=function(t,e){var n;return this.data=m({},this.data,((n={})[t]=e,n)),this},e.setAttribute=function(t,e){void 0===e?delete this._attributes[t]:this._attributes[t]=e},e.setAttributes=function(t){var e=this;Object.keys(t).forEach((function(n){return e.setAttribute(n,t[n])}))},e.setStatus=function(t){return this._status=t,this},e.setHttpStatus=function(t){return lr(this,t),this},e.setName=function(t){this.updateName(t)},e.updateName=function(t){return this._name=t,this},e.isSuccess=function(){return"ok"===this._status},e.finish=function(t){return this.end(t)},e.end=function(t){if(!this._endTime){var e=Jt(this);if(tt&&e&&e.spanContext().spanId!==this._spanId){var n=this._logMessage;n&&h.log(n.replace("Starting","Finishing"))}this._endTime=Pt(t)}},e.toTraceparent=function(){return Lt(this)},e.toContext=function(){return Y({data:this._getData(),description:this._name,endTimestamp:this._endTime,op:this.op,parentSpanId:this._parentSpanId,sampled:this._sampled,spanId:this._spanId,startTimestamp:this._startTime,status:this._status,tags:this.tags,traceId:this._traceId})},e.updateWithContext=function(t){return this.data=t.data||{},this._name=t.name||t.description,this._endTime=t.endTimestamp,this.op=t.op,this._parentSpanId=t.parentSpanId,this._sampled=t.sampled,this._spanId=t.spanId||this._spanId,this._startTime=t.startTimestamp||this._startTime,this._status=t.status,this.tags=t.tags||{},this._traceId=t.traceId||this._traceId,this},e.getTraceContext=function(){return Nt(this)},e.getSpanJSON=function(){return Y({data:this._getData(),description:this._name,op:this._attributes[cr],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:this._status,tags:Object.keys(this.tags).length>0?this.tags:void 0,timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[ur],_metrics_summary:ir(this),profile_id:this._attributes.profile_id,exclusive_time:this._exclusiveTime,measurements:Object.keys(this._measurements).length>0?this._measurements:void 0})},e.isRecording=function(){return!this._endTime&&!!this._sampled},e.toJSON=function(){return this.getSpanJSON()},e._getData=function(){var t=this.data,e=this._attributes,n=Object.keys(t).length>0,r=Object.keys(e).length>0;if(n||r)return n&&r?m({},t,e):n?t:e},nr(t,[{key:"name",get:function(){return this._name||""},set:function(t){this.updateName(t)}},{key:"description",get:function(){return this._name},set:function(t){this._name=t}},{key:"traceId",get:function(){return this._traceId},set:function(t){this._traceId=t}},{key:"spanId",get:function(){return this._spanId},set:function(t){this._spanId=t}},{key:"parentSpanId",get:function(){return this._parentSpanId},set:function(t){this._parentSpanId=t}},{key:"sampled",get:function(){return this._sampled},set:function(t){this._sampled=t}},{key:"attributes",get:function(){return this._attributes},set:function(t){this._attributes=t}},{key:"startTimestamp",get:function(){return this._startTime},set:function(t){this._startTime=t}},{key:"endTimestamp",get:function(){return this._endTime},set:function(t){this._endTime=t}},{key:"status",get:function(){return this._status},set:function(t){this._status=t}},{key:"op",get:function(){return this._attributes[cr]},set:function(t){this.setAttribute(cr,t)}},{key:"origin",get:function(){return this._attributes[ur]},set:function(t){this.setAttribute(ur,t)}}]),t}();function fr(t){var e=Wt(),n=t||e&&e.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}function hr(t){if(fr()){var e=function(t){if(t.startTime){var e=m({},t);return e.startTimestamp=Pt(t.startTime),delete e.startTime,e}return t}(t),n=ae(),r=t.scope?t.scope.getSpan():Yt().getSpan();if(!t.onlyIfParent||r){var i=(t.scope||Yt()).clone();return function(t,e){var n=e.parentSpan,r=e.spanContext,i=e.forceTransaction,o=e.scope;if(fr()){var a,s=se();if(n&&!i)a=n.startChild(r);else if(n){var c=Kt(n),u=n.spanContext(),l=u.traceId,d=u.spanId,p=Ut(n);a=t.startTransaction(m({traceId:l,parentSpanId:d,parentSampled:p},r,{metadata:m({dynamicSamplingContext:c},r.metadata)}))}else{var f=m({},s.getPropagationContext(),o.getPropagationContext()),h=f.traceId,v=f.dsc,g=f.parentSpanId,y=f.sampled;a=t.startTransaction(m({traceId:h,parentSpanId:g,parentSampled:y},r,{metadata:m({dynamicSamplingContext:v},r.metadata)}))}return o.setSpan(a),function(t,e,n){t&&(U(t,vr,n),U(t,mr,e))}(a,o,s),a}}(n,{parentSpan:r,spanContext:e,forceTransaction:t.forceTransaction,scope:i})}}}var mr="_sentryScope",vr="_sentryIsolationScope",gr=function(t){function e(e,n){var r;(r=t.call(this,e)||this)._contexts={},r._hub=n||ae(),r._name=e.name||"",r._metadata=m({},e.metadata),r._trimEnd=e.trimEnd,r.transaction=Xn(r);var i=r._metadata.dynamicSamplingContext;return i&&(r._frozenDynamicSamplingContext=m({},i)),r}Zn(e,t);var n=e.prototype;return n.setName=function(t,e){void 0===e&&(e="custom"),this._name=t,this.setAttribute(ar,e)},n.updateName=function(t){return this._name=t,this},n.initSpanRecorder=function(t){void 0===t&&(t=1e3),this.spanRecorder||(this.spanRecorder=new dr(t)),this.spanRecorder.add(this)},n.setContext=function(t,e){null===e?delete this._contexts[t]:this._contexts[t]=e},n.setMeasurement=function(t,e,n){void 0===n&&(n=""),this._measurements[t]={value:e,unit:n}},n.setMetadata=function(t){this._metadata=m({},this._metadata,t)},n.end=function(t){var e=Pt(t),n=this._finishTransaction(e);if(n)return this._hub.captureEvent(n)},n.toContext=function(){return Y(m({},t.prototype.toContext.call(this),{name:this._name,trimEnd:this._trimEnd}))},n.updateWithContext=function(e){return t.prototype.updateWithContext.call(this,e),this._name=e.name||"",this._trimEnd=e.trimEnd,this},n.getDynamicSamplingContext=function(){return Kt(this)},n.setHub=function(t){this._hub=t},n.getProfileId=function(){if(void 0!==this._contexts&&void 0!==this._contexts.profile)return this._contexts.profile.profile_id},n._finishTransaction=function(e){var n=this;if(void 0===this._endTime){this._name||(tt&&h.warn("Transaction has no name, falling back to ``."),this._name=""),t.prototype.end.call(this,e);var r=this._hub.getClient();if(r&&r.emit&&r.emit("finishTransaction",this),!0!==this._sampled)return tt&&h.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled."),void(r&&r.recordDroppedEvent("sample_rate","transaction"));var i=this.spanRecorder?this.spanRecorder.spans.filter((function(t){return t!==n&&Ft(t).timestamp})):[];if(this._trimEnd&&i.length>0){var o=i.map((function(t){return Ft(t).timestamp})).filter(Boolean);this._endTime=o.reduce((function(t,e){return t>e?t:e}))}var a={scope:this[mr],isolationScope:this[vr]},s=a.scope,c=a.isolationScope,u=this.metadata,l=u.source,d=m({contexts:m({},this._contexts,{trace:Nt(this)}),spans:i,start_timestamp:this._startTime,tags:this.tags,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:m({},u,{capturedSpanScope:s,capturedSpanIsolationScope:c},Y({dynamicSamplingContext:Kt(this)})),_metrics_summary:ir(this)},l&&{transaction_info:{source:l}});return Object.keys(this._measurements).length>0&&(tt&&h.log("[Measurements] Adding measurements to transaction",JSON.stringify(this._measurements,void 0,2)),d.measurements=this._measurements),tt&&h.log("[Tracing] Finishing "+this.op+" transaction: "+this._name+"."),d}},nr(e,[{key:"name",get:function(){return this._name},set:function(t){this.setName(t)}},{key:"metadata",get:function(){return m({source:"custom",spanMetadata:{}},this._metadata,this._attributes[ar]&&{source:this._attributes[ar]},this._attributes[sr]&&{sampleRate:this._attributes[sr]})},set:function(t){this._metadata=t}}]),e}(pr);function yr(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._beforeFinishCallbacks);!(i=o()).done;)(0,i.value)(this,r);this.spanRecorder.spans=this.spanRecorder.spans.filter((function(t){if(t.spanContext().spanId===n.spanContext().spanId)return!0;Ft(t).timestamp||(t.setStatus("cancelled"),t.end(r),tt&&h.log("[Tracing] cancelling span since transaction ended early",JSON.stringify(t,void 0,2)));var e=Ft(t),i=e.start_timestamp,o=e.timestamp,a=i&&i=3?this._autoFinishAllowed&&(tt&&h.log("[Tracing] Transaction finished because of no change for 3 heart beats"),this.setStatus("deadline_exceeded"),this._finishReason=br[0],this.end()):this._pingHeartbeat()}},n._pingHeartbeat=function(){var t=this;tt&&h.log("pinging Heartbeat -> current counter: "+this._heartbeatCounter),setTimeout((function(){t._beat()}),this._heartbeatInterval)},e}(gr);function xr(t){return(t||ae()).getScope().getTransaction()}var wr=!1;function Er(){var t=xr();if(t){var e="internal_error";tt&&h.log("[Tracing] Transaction: "+e+" -> Global error occured"),t.setStatus(e)}}function Tr(t,e,n){return fr(e)?void 0!==t.sampled?(t.setAttribute(sr,Number(t.sampled)),t):("function"==typeof e.tracesSampler?(r=e.tracesSampler(n),t.setAttribute(sr,Number(r))):void 0!==n.parentSampled?r=n.parentSampled:void 0!==e.tracesSampleRate?(r=e.tracesSampleRate,t.setAttribute(sr,Number(r))):(r=1,t.setAttribute(sr,r)),Ir(r)?r?(t.sampled=Math.random()1)||(tt&&h.warn("[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got "+t+"."),!1)}function Cr(){var t=this.getScope().getSpan();return t?{"sentry-trace":Lt(t)}:{}}function Rr(t,e){var n=this.getClient(),r=n&&n.getOptions()||{},i=r.instrumenter||"sentry",o=t.instrumenter||"sentry";i!==o&&(tt&&h.error("A transaction was started with instrumenter=`"+o+"`, but the SDK is configured with the `"+i+"` instrumenter.\nThe transaction will not be sampled. Please use the "+i+" instrumentation to start transactions."),t.sampled=!1);var a=new gr(t,this);return(a=Tr(a,r,m({name:t.name,parentSampled:t.parentSampled,transactionContext:t,attributes:m({},t.data,t.attributes)},e))).isRecording()&&a.initSpanRecorder(r._experiments&&r._experiments.maxSpans),n&&n.emit&&n.emit("startTransaction",a),a}function Or(t,e,n,r,i,o,a,s){void 0===s&&(s=!1);var c=t.getClient(),u=c&&c.getOptions()||{},l=new kr(e,t,n,r,a,i,s);return(l=Tr(l,u,m({name:e.name,parentSampled:e.parentSampled,transactionContext:e,attributes:m({},e.data,e.attributes)},o))).isRecording()&&l.initSpanRecorder(u._experiments&&u._experiments.maxSpans),c&&c.emit&&c.emit("startTransaction",l),l}Er.tag="sentry_tracingErrorCallback";var Mr,Ar=!1,Dr=a,Nr=function(t,e,n){var r,i;return function(o){e.value>=0&&(o||n)&&((i=e.value-(r||0))||void 0===r)&&(r=e.value,e.delta=i,t(e))}},Lr=function(){return Dr.__WEB_VITALS_POLYFILL__?Dr.performance&&(performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]||function(){var t=Dr.performance.timing,e=Dr.performance.navigation.type,n={entryType:"navigation",startTime:0,type:2==e?"back_forward":1===e?"reload":"navigate"};for(var r in t)"navigationStart"!==r&&"toJSON"!==r&&(n[r]=Math.max(t[r]-t.navigationStart,0));return n}()):Dr.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},Pr=function(){var t=Lr();return t&&t.activationStart||0},jr=function(t,e){var n=Lr(),r="navigate";return n&&(r=Dr.document&&Dr.document.prerendering||Pr()>0?"prerender":n.type.replace(/_/g,"-")),{name:t,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-"+Date.now()+"-"+(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},Fr=function(t,e,n){try{if(PerformanceObserver.supportedEntryTypes.includes(t)){var r=new PerformanceObserver((function(t){e(t.getEntries())}));return r.observe(Object.assign({type:t,buffered:!0},n||{})),r}}catch(t){}},Ur=function(t,e){var n=function n(r){"pagehide"!==r.type&&"hidden"!==Dr.document.visibilityState||(t(r),e&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};Dr.document&&(addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0))},Br=function(t,e){void 0===e&&(e={});var n,r=jr("CLS",0),i=0,o=[],a=function(t){t.forEach((function(t){if(!t.hadRecentInput){var e=o[0],a=o[o.length-1];i&&0!==o.length&&t.startTime-a.startTime<1e3&&t.startTime-e.startTime<5e3?(i+=t.value,o.push(t)):(i=t.value,o=[t]),i>r.value&&(r.value=i,r.entries=o,n&&n())}}))},s=Fr("layout-shift",a);if(s){n=Nr(t,r,e.reportAllChanges);var c=function(){a(s.takeRecords()),n(!0)};return Ur(c),c}},Hr=-1,zr=function(){return Hr<0&&(Dr.document&&Dr.document.visibilityState&&(Hr="hidden"!==Dr.document.visibilityState||Dr.document.prerendering?1/0:0),Ur((function(t){var e=t.timeStamp;Hr=e}),!0)),{get firstHiddenTime(){return Hr}}},qr=function(t){var e,n=zr(),r=jr("FID"),i=function(t){t.startTimee.latency){if(n)n.entries.push(t),n.latency=Math.max(n.latency,t.duration);else{var r={id:t.interactionId,latency:t.duration,entries:[t]};Xr[r.id]=r,$r.push(r)}$r.sort((function(t,e){return e.latency-t.latency})),$r.splice(10).forEach((function(t){delete Xr[t.id]}))}},Zr=function(t,e){e=e||{},Kr();var n,r=jr("INP"),i=function(t){t.forEach((function(t){t.interactionId&&Qr(t),"first-input"===t.entryType&&!$r.some((function(e){return e.entries.some((function(e){return t.duration===e.duration&&t.startTime===e.startTime}))}))&&Qr(t)}));var e,i=(e=Math.min($r.length-1,Math.floor(Gr()/50)),$r[e]);i&&i.latency!==r.value&&(r.value=i.latency,r.entries=i.entries,n())},o=Fr("event",i,{durationThreshold:e.durationThreshold||40});n=Nr(t,r,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),Ur((function(){i(o.takeRecords()),r.value<0&&Gr()>0&&(r.value=0,r.entries=[]),n(!0)})))},ti={},ei=function(t){var e,n=zr(),r=jr("LCP"),i=function(t){var i=t[t.length-1];if(i){var o=Math.max(i.startTime-Pr(),0);operformance.now())return;n.entries=[t],r(!0)}}))};function ii(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){Ar&&h.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+bt(o)+"\nError:",e)}}}function hi(){return Br((function(t){fi("cls",{metric:t}),oi=t}),{reportAllChanges:!0})}function mi(){return qr((function(t){fi("fid",{metric:t}),ai=t}))}function vi(){return ei((function(t){fi("lcp",{metric:t}),si=t}))}function gi(){return ri((function(t){fi("ttfb",{metric:t}),ci=t}))}function yi(){return Zr((function(t){fi("inp",{metric:t}),ui=t}))}function _i(t,e,n,r,i){var o;return void 0===i&&(i=!1),bi(t,e),di[t]||(o=n(),di[t]=!0),r&&e({metric:r}),Si(t,e,i?o:void 0)}function bi(t,e){li[t]=li[t]||[],li[t].push(e)}function Si(t,e,n){return function(){n&&n();var r=li[t];if(r){var i=r.indexOf(e);-1!==i&&r.splice(i,1)}}}var ki=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function xi(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,o=t.port,a=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(o?":"+o:"")+"/"+(r?r+"/":r)+a}function wi(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function Ei(t){var e="string"==typeof t?function(t){var e=ki.exec(t);if(e){var n=e.slice(1),r=n[0],i=n[1],o=n[2],a=void 0===o?"":o,s=n[3],c=n[4],u=void 0===c?"":c,l="",p=n[5],f=p.split("/");if(f.length>1&&(l=f.slice(0,-1).join("/"),p=f.pop()),p){var h=p.match(/^\d+/);h&&(p=h[0])}return wi({host:s,pass:a,path:l,projectId:p,port:u,protocol:r,publicKey:i})}d((function(){console.error("Invalid Sentry Dsn: "+t)}))}(t):wi(t);if(e&&function(t){if(!i)return!0;var e=t.port,n=t.projectId,r=t.protocol;return!(["protocol","publicKey","host","projectId"].find((function(e){return!t[e]&&(h.error("Invalid Sentry Dsn: "+e+" missing"),!0)}))||(n.match(/^\d+$/)?function(t){return"http"===t||"https"===t}(r)?e&&isNaN(parseInt(e,10))&&(h.error("Invalid Sentry Dsn: Invalid port "+e),1):(h.error("Invalid Sentry Dsn: Invalid protocol "+r),1):(h.error("Invalid Sentry Dsn: Invalid projectId "+n),1)))}(e))return e}function Ti(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Ii(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ii(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Ii(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=0||(i[n]=t[n]);return i}(e,ji);return n&&t.startTimestamp>n&&(t.startTimestamp=n),t.startChild(m({startTimestamp:n},r))}function Bi(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Hi(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Hi(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Hi(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n0?y.join(","):void 0})}return{"sentry-trace":d,baggage:p}}(v,c,s,g,h)}return h}var y=t.fetchData.__span;if(!y)return;var _=r[y];_&&(function(t,e){if(e.response){lr(t,e.response.status);var n=e.response&&e.response.headers&&e.response.headers.get("content-length");if(n){var r=parseInt(n);r>0&&t.setAttribute("http.response_content_length",r)}}else e.error&&t.setStatus("internal_error");t.end()}(_,t),delete r[y])}}(t,c,u,l);if(e){var n=oo(t.fetchData.url),r=n?Ln(n).host:void 0;e.setAttributes({"http.url":n,"server.address":r})}s&&e&&ro(e)})),r&&Sn((function(t){var e=function(t,e,n,r){var i,o=t.xhr,a=o&&o[bn];if(fr()&&o&&!o.__sentry_own_request__&&a){var s=e(a.url);if(!t.endTimestamp||!s){var c=Yt(),u=se(),l=oo(a.url),d=l?Ln(l).host:void 0,p=s?hr({name:a.method+" "+a.url,onlyIfParent:!0,attributes:(i={type:"xhr","http.method":a.method,"http.url":l,url:a.url,"server.address":d},i[ur]="auto.http.browser",i),op:"http.client"}):void 0;p&&(o.__sentry_xhr_span_id__=p.spanContext().spanId,r[o.__sentry_xhr_span_id__]=p);var f=Wt();if(o.setRequestHeader&&n(a.url)&&f){var h=m({},u.getPropagationContext(),c.getPropagationContext()),v=h.traceId,g=h.spanId,y=h.sampled,_=h.dsc;!function(t,e,n){try{t.setRequestHeader("sentry-trace",e),n&&t.setRequestHeader(wt,n)}catch(t){}}(o,p?Lt(p):At(v,g,y),Ct(_||(p?Kt(p):Vt(v,f,c))))}return p}var b=o.__sentry_xhr_span_id__;if(!b)return;var S=r[b];S&&void 0!==a.status_code&&(lr(S,a.status_code),S.end(),delete r[b])}}(t,c,u,l);s&&e&&ro(e)}))}function ro(t){var e=(Ft(t).data||{}).url;if(e&&"string"==typeof e)var n=pi("resource",(function(r){r.entries.forEach((function(r){(function(t){return"resource"===t.entryType&&"initiatorType"in t&&"string"==typeof t.nextHopProtocol&&("fetch"===t.initiatorType||"xmlhttprequest"===t.initiatorType)})(r)&&r.name.endsWith(e)&&(function(t){var e=function(t){for(var e,n="unknown",r="unknown",i="",o=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Zi(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Zi(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(t);!(e=o()).done;){var a=e.value;if("/"===a){var s=t.split("/");n=s[0],r=s[1];break}if(!isNaN(Number(a))){n="h"===i?"http":i,r=t.split(i)[1];break}i+=a}return i===t&&(n=i),{name:n,version:r}}(t.nextHopProtocol),n=e.name,r=e.version,i=[];return i.push(["network.protocol.version",r],["network.protocol.name",n]),lt?[].concat(i,[["http.request.redirect_start",io(t.redirectStart)],["http.request.fetch_start",io(t.fetchStart)],["http.request.domain_lookup_start",io(t.domainLookupStart)],["http.request.domain_lookup_end",io(t.domainLookupEnd)],["http.request.connect_start",io(t.connectStart)],["http.request.secure_connection_start",io(t.secureConnectionStart)],["http.request.connection_end",io(t.connectEnd)],["http.request.request_start",io(t.requestStart)],["http.request.response_start",io(t.responseStart)],["http.request.response_end",io(t.responseEnd)]]):i}(r).forEach((function(e){return t.setAttribute.apply(t,e)})),setTimeout(n))}))}))}function io(t){return void 0===t&&(t=0),((lt||performance.timeOrigin)+t)/1e3}function oo(t){try{return new URL(t,Dr.location.origin).href}catch(t){return}}var ao=m({},_r,{markBackgroundTransactions:!0,routingInstrumentation:function(t,e,n){if(void 0===e&&(e=!0),void 0===n&&(n=!0),Dr&&Dr.location){var r,i=Dr.location.href;e&&(r=t({name:Dr.location.pathname,startTimestamp:lt?lt/1e3:void 0,op:"pageload",origin:"auto.pageload.browser",metadata:{source:"url"}})),n&&An((function(e){var n=e.to,o=e.from;void 0===o&&i&&-1!==i.indexOf(n)?i=void 0:o!==n&&(i=void 0,r&&(Ar&&h.log("[Tracing] Finishing current transaction with op: "+r.op),r.end()),r=t({name:Dr.location.pathname,op:"navigation",origin:"auto.navigation.browser",metadata:{source:"url"}}))}))}else Ar&&h.warn("Could not initialize routing instrumentation due to invalid location")},startTransactionOnLocationChange:!0,startTransactionOnPageLoad:!0,enableLongTask:!0,enableInp:!1,interactionsSampleRate:1,_experiments:{}},eo),so=function(){function t(t){var e;this.name="BrowserTracing",this._hasSetTracePropagationTargets=!1,(e=ie()).__SENTRY__&&(e.__SENTRY__.extensions=e.__SENTRY__.extensions||{},e.__SENTRY__.extensions.startTransaction||(e.__SENTRY__.extensions.startTransaction=Rr),e.__SENTRY__.extensions.traceHeaders||(e.__SENTRY__.extensions.traceHeaders=Cr),wr||(wr=!0,Ye(Er),Ke(Er))),Ar&&(this._hasSetTracePropagationTargets=!(!t||!t.tracePropagationTargets&&!t.tracingOrigins)),this.options=m({},ao,t),void 0!==this.options._experiments.enableLongTask&&(this.options.enableLongTask=this.options._experiments.enableLongTask),t&&!t.tracePropagationTargets&&t.tracingOrigins&&(this.options.tracePropagationTargets=t.tracingOrigins),this._collectWebVitals=Gi(),this._interactionIdToRouteNameMapping={},this.options.enableInp&&function(t,e){if(Wi()&<){var n=function(t,e){return n=function(n){var r=n.metric;if(void 0!==r.value){var i=r.entries.find((function(t){return t.duration===r.value&&void 0!==$i[t.name]})),o=Wt();if(i&&o){var a=$i[i.name],s=o.getOptions(),c=qi(lt+i.startTime),u=qi(r.value),l=void 0!==i.interactionId?t[i.interactionId]:void 0;if(void 0!==l){var d=l.routeName,p=l.parentContext,f=l.activeTransaction,v=l.user,g=l.replayId,y=void 0!==v?v.email||v.id||v.ip_address:void 0,_=void 0!==f?f.getProfileId():void 0,b=new pr({startTimestamp:c,endTimestamp:c+u,op:"ui.interaction."+a,name:A(i.target),attributes:m({release:s.release,environment:s.environment,transaction:d},void 0!==y&&""!==y?{user:y}:{},void 0!==_?{profile_id:_}:{},void 0!==g?{replay_id:g}:{}),exclusiveTime:r.value,measurements:{inp:{value:r.value,unit:"millisecond"}}}),S=function(t,e,n){return!!fr(e)&&(Ir(r=void 0!==t&&"function"==typeof e.tracesSampler?e.tracesSampler({transactionContext:t,name:t.name,parentSampled:t.parentSampled,attributes:m({},t.data,t.attributes),location:Dr.location}):void 0!==t&&void 0!==t.sampled?t.sampled:void 0!==e.tracesSampleRate?e.tracesSampleRate:1)?!0===r?n:!1===r?0:r*n:(Ar&&h.warn("[Tracing] Discarding interaction span because of invalid sample rate."),!1));var r}(p,s,e);if(S)if(Math.random() since tab moved to the background, op: "+r),i||t.setStatus(e),t.setTag("visibilitychange","document.hidden"),t.end()}})):Ar&&h.warn("[Tracing] Could not set up background tab detection due to lack of global document")),m.enableInteractions&&this._registerInteractionListener(),this.options.enableInp&&this._registerInpInteractionListener(),no({traceFetch:l,traceXHR:d,tracePropagationTargets:g,shouldCreateSpanForRequest:p,enableHTTPTimings:f})},e._createRouteTransaction=function(t){var e=this;if(this._getCurrentHub){var n,r=this._getCurrentHub(),i=this.options,o=i.beforeNavigate,a=i.idleTimeout,s=i.finalTimeout,c=i.heartbeatInterval,u="pageload"===t.op;if(u){var l=Mt(u?co("sentry-trace"):"",u?co("baggage"):void 0),d=l.traceId,p=l.dsc;n=m({traceId:d,parentSpanId:l.parentSpanId,parentSampled:l.sampled},t,{metadata:m({},t.metadata,{dynamicSamplingContext:p}),trimEnd:!0})}else n=m({trimEnd:!0},t);var f="function"==typeof o?o(n):n,v=void 0===f?m({},n,{sampled:!1}):f;v.metadata=v.name!==n.name?m({},v.metadata,{source:"custom"}):v.metadata,this._latestRoute.name=v.name,this._latestRoute.context=v,!1===v.sampled&&Ar&&h.log("[Tracing] Will not send "+v.op+" transaction because of beforeNavigate."),Ar&&h.log("[Tracing] Starting "+v.op+" transaction on scope");var g=Or(r,v,a,s,!0,{location:Dr.location},c,u);return u&&Dr.document&&(Dr.document.addEventListener("readystatechange",(function(){["interactive","complete"].includes(Dr.document.readyState)&&g.sendAutoFinishSignal()})),["interactive","complete"].includes(Dr.document.readyState)&&g.sendAutoFinishSignal()),g.registerBeforeFinishCallback((function(t){e._collectWebVitals(),function(t){var e=Wi();if(e&&Dr.performance.getEntries&<){Ar&&h.log("[Tracing] Adding & adjusting spans using Performance API");var n=qi(lt),r=e.getEntries(),i=Ft(t),o=i.op,a=i.start_timestamp;if(r.slice(Vi).forEach((function(e){var r=qi(e.startTime),i=qi(e.duration);if(!("navigation"===t.op&&a&&n+r=a)){var e=Ki[t].value,r=n+qi(e),i=Math.abs(1e3*(r-a)),o=i-e;Ar&&h.log("[Measurements] Normalized "+t+" from "+e+" to "+i+" ("+o+")"),Ki[t].value=i}}));var s=Ki["mark.fid"];s&&Ki.fid&&(Ui(t,{description:"first input delay",endTimestamp:s.value+qi(Ki.fid.value),op:"ui.action",origin:"auto.ui.browser.metrics",startTimestamp:s.value}),delete Ki["mark.fid"]),"fcp"in Ki||delete Ki.cls,Object.keys(Ki).forEach((function(t){!function(t,e,n){var r=xr();r&&r.setMeasurement(t,e,n)}(t,Ki[t].value,Ki[t].unit)})),function(t){Yi&&(Ar&&h.log("[Measurements] Adding LCP Data"),Yi.element&&t.setTag("lcp.element",A(Yi.element)),Yi.id&&t.setTag("lcp.id",Yi.id),Yi.url&&t.setTag("lcp.url",Yi.url.trim().slice(0,200)),t.setTag("lcp.size",Yi.size)),Ji&&Ji.sources&&(Ar&&h.log("[Measurements] Adding CLS Data"),Ji.sources.forEach((function(e,n){return t.setTag("cls.source."+(n+1),A(e.node))})))}(t)}Yi=void 0,Ji=void 0,Ki={}}}(t)})),g}Ar&&h.warn("[Tracing] Did not create "+t.op+" transaction because _getCurrentHub is invalid.")},e._registerInteractionListener=function(){var t,e=this,n=function(){var n,r=e.options,i=r.idleTimeout,o=r.finalTimeout,a=r.heartbeatInterval,s="ui.action.click",c=xr();if(c&&c.op&&["navigation","pageload"].includes(c.op))Ar&&h.warn("[Tracing] Did not create "+s+" transaction because a pageload or navigation transaction is in progress.");else if(t&&(t.setFinishReason("interactionInterrupted"),t.end(),t=void 0),e._getCurrentHub)if(e._latestRoute.name){var u=e._getCurrentHub(),l=Dr.location,d={name:e._latestRoute.name,op:s,trimEnd:!0,data:(n={},n[ar]=e._latestRoute.context?uo(e._latestRoute.context):"url",n)};t=Or(u,d,i,o,!0,{location:l},a)}else Ar&&h.warn("[Tracing] Did not create "+s+" transaction because _latestRouteName is missing.");else Ar&&h.warn("[Tracing] Did not create "+s+" transaction because _getCurrentHub is invalid.")};["click"].forEach((function(t){Dr.document&&addEventListener(t,n,{once:!1,capture:!0})}))},e._registerInpInteractionListener=function(){var t=this,e=function(e){var n=e.entries,r=Wt(),i=void 0!==r&&void 0!==r.getIntegrationByName?r.getIntegrationByName("Replay"):void 0,o=void 0!==i?i.getReplayId():void 0,a=xr(),s=Yt(),c=void 0!==s?s.getUser():void 0;n.forEach((function(e){if(function(t){return"duration"in t}(e)){var n=e.interactionId;if(void 0===n)return;var r=t._interactionIdToRouteNameMapping[n],i=e.duration,s=e.startTime,u=Object.keys(t._interactionIdToRouteNameMapping),l=u.length>0?u.reduce((function(e,n){return t._interactionIdToRouteNameMapping[e].durationt._interactionIdToRouteNameMapping[l].duration){var d=t._latestRoute.name,p=t._latestRoute.context;d&&p&&(l&&Object.keys(t._interactionIdToRouteNameMapping).length>=10&&delete t._interactionIdToRouteNameMapping[l],t._interactionIdToRouteNameMapping[n]={routeName:d,duration:i,parentContext:p,user:c,activeTransaction:a,replayId:o,startTime:s})}}}))};pi("event",e),pi("first-input",e)},t}();function co(t){var e,n=(e="meta[name="+t+"]",O.document&&O.document.querySelector?O.document.querySelector(e):null);return n?n.getAttribute("content"):void 0}function uo(t){var e=t.attributes&&t.attributes[ar],n=t.data&&t.data[ar],r=t.metadata&&t.metadata.source;return e||n||r}function lo(t,e,n,r,i,o,a){try{var s=t[o](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(r,i)}function po(t){return function(){var e=this,n=arguments;return new Promise((function(r,i){var o=t.apply(e,n);function a(t){lo(o,r,i,a,s,"next",t)}function s(t){lo(o,r,i,a,s,"throw",t)}a(void 0)}))}}function fo(t){return fo=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},fo(t)}function ho(t,e,n){return ho=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}()?Reflect.construct.bind():function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&Qn(i,n.prototype),i},ho.apply(null,arguments)}function mo(t){var e="function"==typeof Map?new Map:void 0;return mo=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return ho(t,arguments,fo(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),Qn(r,t)},mo(t)}function vo(t){for(var e=void 0,n=t[0],r=1;r>t/4).toString(16)}))}var Co=1e3;function Ro(){return Date.now()/Co}var Oo=function(){var t=wo.performance;if(!t||!t.now)return Ro;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/Co}}(),Mo=function(){var t=wo.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i";try{for(var n,r=t,i=[],o=0,a=0,s=Array.isArray(e)?e:e.keyAttrs,c=!Array.isArray(e)&&e.maxStringLength||Wo;r&&o++<5&&!("html"===(n=Jo(r,s))||o>1&&a+3*i.length+n.length>=c);)i.push(n),a+=n.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return""}}function Jo(t,e){var n,r,i,o,a,s=t,c=[];if(!s||!s.tagName)return"";if(qo.HTMLElement&&s instanceof HTMLElement&&s.dataset&&s.dataset.sentryComponent)return s.dataset.sentryComponent;c.push(s.tagName.toLowerCase());var u=e&&e.length?e.filter((function(t){return s.getAttribute(t)})).map((function(t){return[t,s.getAttribute(t)]})):null;if(u&&u.length)u.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(s.id&&c.push("#"+s.id),(n=s.className)&&_o(n))for(r=n.split(/\s+/),a=0;a"}}function $o(t){if("object"==typeof t&&null!==t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function Xo(t){return Qo(t,new Map)}function Qo(t,e){if(function(t){if(!bo(t))return!1;try{var e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){var n=e.get(t);if(void 0!==n)return n;var r={};e.set(t,r);for(var i=0,o=Object.keys(t);i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function ta(t){return t.transaction}var ea=1;function na(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=ra(t);return Xo({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function ra(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function ia(t){var e=Ia();if(!e)return{};var n=function(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=Xo({environment:r.environment||Fo,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}(ra(t).trace_id||"",e,Ca()),r=ta(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=ra(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&ea)}(r)),e.emit&&e.emit("createDsc",n),n}function oa(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=Xo(n);c&&Object.keys(c).length&&(t.extra=m({},c,t.extra));var u=Xo(r);u&&Object.keys(u).length&&(t.tags=m({},u,t.tags));var l=Xo(i);l&&Object.keys(l).length&&(t.user=m({},l,t.user));var d=Xo(o);d&&Object.keys(d).length&&(t.contexts=m({},d,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=m({trace:na(e)},t.contexts);var n=ta(e);if(n){t.sdkProcessingMetadata=m({dynamicSamplingContext:ia(e)},t.sdkProcessingMetadata);var r=ra(n).description;r&&(t.tags=m({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=m({},t.sdkProcessingMetadata,e)}(t,o)}function aa(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.sdkProcessingMetadata,c=e.breadcrumbs,u=e.fingerprint,l=e.eventProcessors,d=e.attachments,p=e.propagationContext,f=e.transactionName,h=e.span;sa(t,"extra",n),sa(t,"tags",r),sa(t,"user",i),sa(t,"contexts",o),sa(t,"sdkProcessingMetadata",s),a&&(t.level=a),f&&(t.transactionName=f),h&&(t.span=h),c.length&&(t.breadcrumbs=[].concat(t.breadcrumbs,c)),u.length&&(t.fingerprint=[].concat(t.fingerprint,u)),l.length&&(t.eventProcessors=[].concat(t.eventProcessors,l)),d.length&&(t.attachments=[].concat(t.attachments,d)),t.propagationContext=m({},t.propagationContext,p)}function sa(t,e,n){if(n&&Object.keys(n).length)for(var r in t[e]=m({},t[e]),n)Object.prototype.hasOwnProperty.call(n,r)&&(t[e][r]=n[r])}var ca,ua=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=la()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=m({},this._tags),e._extra=m({},this._extra),e._contexts=m({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=m({},this._sdkProcessingMetadata),e._propagationContext=m({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&Zo(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=m({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=m({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=m({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=m({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=m({},this._tags,r.tags),this._extra=m({},this._extra,r.extra),this._contexts=m({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(bo(n)){var i=e;this._tags=m({},this._tags,i.tags),this._extra=m({},this._extra,i.extra),this._contexts=m({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=la(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=m({timestamp:Ro()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),oa(t,this.getScopeData()),zo([].concat(n,Ho(),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=m({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:Io();if(!this._client)return jo.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,m({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:Io();if(!this._client)return jo.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,m({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:Io();return this._client?(this._client.captureEvent(t,m({},e,{event_id:n}),this),n):(jo.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function la(){return{traceId:Io(),spanId:Io().substring(16)}}var da=parseFloat("7.119.1"),pa=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=da),this._version=r,e?i=e:(i=new ua).setClient(t),n?o=n:(o=new ua).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;i=i){v[_]="[MaxProperties ~]";break}var b=y[_];v[_]=ka(_,b,f-1,i,o),g++}return d(e),v}function xa(t,e,n,r,i,o){var a=t.normalizeDepth,s=void 0===a?3:a,c=t.normalizeMaxBreadth,u=void 0===c?1e3:c,l=m({},e,{event_id:e.event_id||n.event_id||Io(),timestamp:e.timestamp||Ro()}),d=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,o=e.maxValueLength,a=void 0===o?250:o;"environment"in t||(t.environment="environment"in e?n:Fo),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=ya(t.message,a));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=ya(s.value,a));var c=t.request;c&&c.url&&(c.url=ya(c.url,a))}(l,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(l,d),void 0===e.type&&function(t,e){var n,r=wo._sentryDebugIds;if(r){var i=wa.get(e);i?n=i:(n=new Map,wa.set(e,n));var o=Object.keys(r).reduce((function(t,i){var o,a=n.get(i);a?o=a:(o=e(i),n.set(i,o));for(var s=o.length-1;s>=0;s--){var c=o[s];if(c.filename){t[c.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=o[t.filename])}))}))}catch(t){}}}(l,t.stackParser);var p=function(t,e){if(!e)return t;var n=t?t.clone():new ua;return n.update(e),n}(r,n.captureContext);n.mechanism&&function(t,e){var n=function(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}(t);if(n){var r=n.mechanism;if(n.mechanism=m({},{type:"generic",handled:!0},r,e),e&&"data"in e){var i=m({},r&&r.data,e.data);n.mechanism.data=i}}}(l,n.mechanism);var f=i&&i.getEventProcessors?i.getEventProcessors():[],h=(ca||(ca=new ua),ca).getScopeData();o&&aa(h,o.getScopeData()),p&&aa(h,p.getScopeData());var v=[].concat(n.attachments||[],h.attachments);return v.length&&(n.attachments=v),oa(l,h),zo([].concat(f,Ho(),h.eventProcessors),l,n).then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof s&&s>0?function(t,e,n){if(!t)return null;var r=m({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return m({},t,t.data&&{data:Sa(t.data,e,n)})}))},t.user&&{user:Sa(t.user,e,n)},t.contexts&&{contexts:Sa(t.contexts,e,n)},t.extra&&{extra:Sa(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=Sa(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){var r=ra(t).data;return r&&(t.data=Sa(r,e,n)),t}))),r}(t,s,u):t}))}var wa=new WeakMap;var Ea=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function Ta(t,e){return ma().captureException(t,function(t){if(t)return function(t){return t instanceof ua||"function"==typeof t}(t)||function(t){return Object.keys(t).some((function(t){return Ea.includes(t)}))}(t)?{captureContext:t}:t}(e))}function Ia(){return ma().getClient()}function Ca(){return ma().getScope()}function Ra(t){return"/"===t[t.length-1]?t.slice(0,-1):t}function Oa(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){Ao&&jo.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+ba(o)+"\nError:",e)}}}var Pa=wo,ja="__sentry_xhr_v3__";function Fa(){if(Pa.XMLHttpRequest){var t=XMLHttpRequest.prototype;Vo(t,"open",(function(t){return function(){for(var e=this,n=Date.now(),r=arguments.length,i=new Array(r),o=0;o2?n[2]:void 0;if(i){var o=Xa,a=String(i);Xa=a,La("history",{from:o,to:a})}return t.apply(this,n)}}}function es(t,e){void 0===e&&(e=!1);var n=t.host,r=t.path,i=t.pass,o=t.port,a=t.projectId;return t.protocol+"://"+t.publicKey+(e&&i?":"+i:"")+"@"+n+(o?":"+o:"")+"/"+(r?r+"/":r)+a}function ns(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return rs(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?rs(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function rs(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0?"prerender":e.type.replace(/_/g,"-")),{name:"LCP",value:-1,rating:"good",delta:0,entries:[],id:"v3-"+Date.now()+"-"+(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}),a=function(t){var e=t[t.length-1];if(e){var n=Math.max(e.startTime-ds(),0);n=0&&n&&((i=e.value-(r||0))||void 0===r)&&(r=e.value,e.delta=i,t(e))}}(t,o);var c=function(){ms[o.id]||(a(s.takeRecords()),s.disconnect(),ms[o.id]=!0,r(!0))};return["keydown","click"].forEach((function(t){us.document&&addEventListener(t,c,{once:!0,capture:!0})})),ps(c,!0),c}};function gs(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){cs&&jo.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+ba(o)+"\nError:",e)}}}function ks(){return vs((function(t){Ss("lcp",{metric:t}),ys=t}))}function xs(t,e){_s[t]=_s[t]||[],_s[t].push(e)}function ws(t,e,n){return function(){n&&n();var r=_s[t];if(r){var i=r.indexOf(e);-1!==i&&r.splice(i,1)}}}function Es(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Ts(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ts(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Ts(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n-1?s.split("/").slice(0,3).join("/"):s.split("/")[0]).split("?")[0]+c)+u+")";var l=e.split("/"),d=c.split("/");l.pop();for(var p,f=Es(d);!(p=f()).done;){var h=p.value;"."!==h&&(".."===h?l.pop():l.push(h))}return"url("+u+l.join("/")+u+")"}))}var cc=/^[^ \t\n\r\u000c]+/,uc=/^[, \t\n\r\u000c]+/;function lc(t,e){if(!e||""===e.trim())return e;var n=t.createElement("a");return n.href=e,n.href}function dc(t){return Boolean("svg"===t.tagName||t.ownerSVGElement)}function pc(){var t=document.createElement("a");return t.href="",t.href}function fc(t,e,n,r,i,o){return r?"src"===n||"href"===n&&("use"!==e||"#"!==r[0])||"xlink:href"===n&&"#"!==r[0]?lc(t,r):"background"!==n||"table"!==e&&"td"!==e&&"th"!==e?"srcset"===n?function(t,e){if(""===e.trim())return e;var n=0;function r(t){var r,i=t.exec(e.substring(n));return i?(r=i[0],n+=r.length,r):""}for(var i=[];r(uc),!(n>=e.length);){var o=r(cc);if(","===o.slice(-1))o=lc(t,o.substring(0,o.length-1)),i.push(o);else{var a="";o=lc(t,o);for(var s=!1;;){var c=e.charAt(n);if(""===c){i.push((o+a).trim());break}if(s)")"===c&&(s=!1);else{if(","===c){n+=1,i.push((o+a).trim());break}"("===c&&(s=!0)}a+=c,n+=1}}}return i.join(", ")}(t,r):"style"===n?sc(r,pc()):"object"===e&&"data"===n?lc(t,r):"function"==typeof o?o(n,r,i):r:lc(t,r):r}function hc(t,e,n){return("video"===t||"audio"===t)&&"autoplay"===e}function mc(t,e,n,r){return void 0===n&&(n=1/0),void 0===r&&(r=0),t?t.nodeType!==t.ELEMENT_NODE||r>n?-1:e(t)?r:mc(t.parentNode,e,n,r+1):-1}function vc(t,e){return function(n){var r=n;if(null===r)return!1;try{if(t)if("string"==typeof t){if(r.matches("."+t))return!0}else if(function(t,e){for(var n=t.classList.length;n--;){var r=t.classList[n];if(e.test(r))return!0}return!1}(r,t))return!0;return!(!e||!r.matches(e))}catch(t){return!1}}}function gc(t,e,n,r,i,o){try{var a=t.nodeType===t.ELEMENT_NODE?t:t.parentElement;if(null===a)return!1;if("INPUT"===a.tagName){var s=a.getAttribute("autocomplete");if(["current-password","new-password","cc-number","cc-exp","cc-exp-month","cc-exp-year","cc-csc"].includes(s))return!0}var c=-1,u=-1;if(o){if((u=mc(a,vc(r,i)))<0)return!0;c=mc(a,vc(e,n),u>=0?u:1/0)}else{if((c=mc(a,vc(e,n)))<0)return!1;u=mc(a,vc(r,i),c>=0?c:1/0)}return c>=0?!(u>=0)||c<=u:!(u>=0||!o)}catch(t){}return!!o}function yc(t){return null==t?"":t.toLowerCase()}function _c(t,e){var n,r=e.doc,i=e.mirror,o=e.blockClass,a=e.blockSelector,s=e.unblockSelector,c=e.maskAllText,u=e.maskTextClass,l=e.unmaskTextClass,d=e.maskTextSelector,p=e.unmaskTextSelector,f=e.skipChild,h=void 0!==f&&f,m=e.inlineStylesheet,v=void 0===m||m,g=e.maskInputOptions,y=void 0===g?{}:g,_=e.maskAttributeFn,b=e.maskTextFn,S=e.maskInputFn,k=e.slimDOMOptions,x=e.dataURLOptions,w=void 0===x?{}:x,E=e.inlineImages,T=void 0!==E&&E,I=e.recordCanvas,C=void 0!==I&&I,R=e.onSerialize,O=e.onIframeLoad,M=e.iframeLoadTimeout,A=void 0===M?5e3:M,D=e.onStylesheetLoad,N=e.stylesheetLoadTimeout,L=void 0===N?5e3:N,P=e.keepIframeSrcFn,j=void 0===P?function(){return!1}:P,F=e.newlyAddedElement,U=void 0!==F&&F,B=e.preserveWhiteSpace,H=void 0===B||B,z=function(t,e){var n=e.doc,r=e.mirror,i=e.blockClass,o=e.blockSelector,a=e.unblockSelector,s=e.maskAllText,c=e.maskAttributeFn,u=e.maskTextClass,l=e.unmaskTextClass,d=e.maskTextSelector,p=e.unmaskTextSelector,f=e.inlineStylesheet,h=e.maskInputOptions,m=void 0===h?{}:h,v=e.maskTextFn,g=e.maskInputFn,y=e.dataURLOptions,_=void 0===y?{}:y,b=e.inlineImages,S=e.recordCanvas,k=e.keepIframeSrcFn,x=e.newlyAddedElement,w=void 0!==x&&x,E=function(t,e){if(e.hasNode(t)){var n=e.getId(t);return 1===n?void 0:n}}(n,r);switch(t.nodeType){case t.DOCUMENT_NODE:return"CSS1Compat"!==t.compatMode?{type:Is.Document,childNodes:[],compatMode:t.compatMode}:{type:Is.Document,childNodes:[]};case t.DOCUMENT_TYPE_NODE:return{type:Is.DocumentType,name:t.name,publicId:t.publicId,systemId:t.systemId,rootId:E};case t.ELEMENT_NODE:return function(t,e){for(var n,r=e.doc,i=e.inlineStylesheet,o=e.maskInputOptions,a=void 0===o?{}:o,s=e.maskAttributeFn,c=e.maskInputFn,u=e.dataURLOptions,l=void 0===u?{}:u,d=e.inlineImages,p=e.recordCanvas,f=e.keepIframeSrcFn,h=e.newlyAddedElement,m=void 0!==h&&h,v=e.rootId,g=e.maskTextClass,y=e.unmaskTextClass,_=e.maskTextSelector,b=e.unmaskTextSelector,S=function(t,e,n,r){try{if(r&&t.matches(r))return!1;if("string"==typeof e){if(t.classList.contains(e))return!0}else for(var i=t.classList.length;i--;){var o=t.classList[i];if(e.test(o))return!0}if(n)return t.matches(n)}catch(t){}return!1}(t,e.blockClass,e.blockSelector,e.unblockSelector),k=function(t){if(t instanceof HTMLFormElement)return"form";var e=Js(t.tagName);return tc.test(e)?"div":e}(t),x={},w=t.attributes.length,E=0;Ee?(r&&(function(){qc("clearTimeout").apply(void 0,arguments)}(r),r=null),i=c,t.apply(l,a)):r||!1===n.trailing||(r=Wc((function(){i=!1===n.leading?0:Date.now(),r=null,t.apply(l,a)}),u))}}function Ec(t,e,n,r,i){void 0===i&&(i=window);var o=i.Object.getOwnPropertyDescriptor(t,e);return i.Object.defineProperty(t,e,r?n:{set:function(t){var e=this;Wc((function(){n.set.call(e,t)}),0),o&&o.set&&o.set.call(this,t)}}),function(){return Ec(t,e,o||{},!0)}}function Tc(t,e,n){try{if(!(e in t))return function(){};var r=t[e],i=n(r);return"function"==typeof i&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:r}})),t[e]=i,function(){t[e]=r}}catch(t){return function(){}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(xc=new Proxy(xc,{get:function(t,e,n){return"map"===e&&console.error(kc),Reflect.get(t,e,n)}}));var Ic=Date.now;function Cc(t){var e=t.document;return{left:e.scrollingElement?e.scrollingElement.scrollLeft:void 0!==t.pageXOffset?t.pageXOffset:bc([e,"optionalAccess",function(t){return t.documentElement},"access",function(t){return t.scrollLeft}])||bc([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.parentElement},"optionalAccess",function(t){return t.scrollLeft}])||bc([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.scrollLeft}])||0,top:e.scrollingElement?e.scrollingElement.scrollTop:void 0!==t.pageYOffset?t.pageYOffset:bc([e,"optionalAccess",function(t){return t.documentElement},"access",function(t){return t.scrollTop}])||bc([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.parentElement},"optionalAccess",function(t){return t.scrollTop}])||bc([e,"optionalAccess",function(t){return t.body},"optionalAccess",function(t){return t.scrollTop}])||0}}function Rc(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Oc(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Mc(t){return t?t.nodeType===t.ELEMENT_NODE?t:t.parentElement:null}function Ac(t,e,n,r,i){if(!t)return!1;var o=Mc(t);if(!o)return!1;var a=vc(e,n);if(!i){var s=r&&o.matches(r);return a(o)&&!s}var c=mc(o,a),u=-1;return!(c<0)&&(r&&(u=mc(o,vc(null,r))),c>-1&&u<0||c=this.length)throw new Error("Position outside of list range");for(var e=this.head,n=0;n0&&this.stylesheetManager.adoptStyleSheets(t.contentDocument.adoptedStyleSheets,this.mirror.getId(t.contentDocument))},e.handleMessage=function(t){var e=t;if("rrweb"===e.data.type&&e.origin===e.data.origin&&t.source){var n=this.crossOriginIframeMap.get(t.source);if(n){var r=this.transformCrossOriginEvent(n,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}},e.transformCrossOriginEvent=function(t,e){var n=this;switch(e.type){case Yc.FullSnapshot:this.crossOriginIframeMirror.reset(t),this.crossOriginIframeStyleMirror.reset(t),this.replaceIdOnNode(e.data.node,t);var r=e.data.node.id;return this.crossOriginIframeRootIdMap.set(t,r),this.patchRootIdOnNode(e.data.node,r),{timestamp:e.timestamp,type:Yc.IncrementalSnapshot,data:{source:Jc.Mutation,adds:[{parentId:this.mirror.getId(t),nextId:null,node:e.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case Yc.Meta:case Yc.Load:case Yc.DomContentLoaded:return!1;case Yc.Plugin:return e;case Yc.Custom:return this.replaceIds(e.data.payload,t,["id","parentId","previousId","nextId"]),e;case Yc.IncrementalSnapshot:switch(e.data.source){case Jc.Mutation:return e.data.adds.forEach((function(e){n.replaceIds(e,t,["parentId","nextId","previousId"]),n.replaceIdOnNode(e.node,t);var r=n.crossOriginIframeRootIdMap.get(t);r&&n.patchRootIdOnNode(e.node,r)})),e.data.removes.forEach((function(e){n.replaceIds(e,t,["parentId","id"])})),e.data.attributes.forEach((function(e){n.replaceIds(e,t,["id"])})),e.data.texts.forEach((function(e){n.replaceIds(e,t,["id"])})),e;case Jc.Drag:case Jc.TouchMove:case Jc.MouseMove:return e.data.positions.forEach((function(e){n.replaceIds(e,t,["id"])})),e;case Jc.ViewportResize:return!1;case Jc.MediaInteraction:case Jc.MouseInteraction:case Jc.Scroll:case Jc.CanvasMutation:case Jc.Input:return this.replaceIds(e.data,t,["id"]),e;case Jc.StyleSheetRule:case Jc.StyleDeclaration:return this.replaceIds(e.data,t,["id"]),this.replaceStyleIds(e.data,t,["styleId"]),e;case Jc.Font:return e;case Jc.Selection:return e.data.ranges.forEach((function(e){n.replaceIds(e,t,["start","end"])})),e;case Jc.AdoptedStyleSheet:return this.replaceIds(e.data,t,["id"]),this.replaceStyleIds(e.data,t,["styleIds"]),wu([e,"access",function(t){return t.data},"access",function(t){return t.styles},"optionalAccess",function(t){return t.forEach},"call",function(e){return e((function(e){n.replaceStyleIds(e,t,["styleId"])}))}]),e}}return!1},e.replace=function(t,e,n,r){for(var i,o=Es(r);!(i=o()).done;){var a=i.value;(Array.isArray(e[a])||"number"==typeof e[a])&&(Array.isArray(e[a])?e[a]=t.getIds(n,e[a]):e[a]=t.getId(n,e[a]))}return e},e.replaceIds=function(t,e,n){return this.replace(this.crossOriginIframeMirror,t,e,n)},e.replaceStyleIds=function(t,e,n){return this.replace(this.crossOriginIframeStyleMirror,t,e,n)},e.replaceIdOnNode=function(t,e){var n=this;this.replaceIds(t,e,["id","rootId"]),"childNodes"in t&&t.childNodes.forEach((function(t){n.replaceIdOnNode(t,e)}))},e.patchRootIdOnNode=function(t,e){var n=this;t.type===Is.Document||t.rootId||(t.rootId=e),"childNodes"in t&&t.childNodes.forEach((function(t){n.patchRootIdOnNode(t,e)}))},t}(),Ru=function(){function t(){}var e=t.prototype;return e.init=function(){},e.addShadowRoot=function(){},e.observeAttachShadow=function(){},e.reset=function(){},t}(),Ou=function(){function t(t){this.shadowDoms=new WeakSet,this.restoreHandlers=[],this.mutationCb=t.mutationCb,this.scrollCb=t.scrollCb,this.bypassOptions=t.bypassOptions,this.mirror=t.mirror,this.init()}var e=t.prototype;return e.init=function(){this.reset(),this.patchAttachShadow(Element,document)},e.addShadowRoot=function(t,e){var n=this;if(Bs(t)&&!this.shadowDoms.has(t)){this.shadowDoms.add(t);var r=pu(m({},this.bypassOptions,{doc:e,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),t);this.restoreHandlers.push((function(){return r.disconnect()})),this.restoreHandlers.push(fu(m({},this.bypassOptions,{scrollCb:this.scrollCb,doc:t,mirror:this.mirror}))),Wc((function(){t.adoptedStyleSheets&&t.adoptedStyleSheets.length>0&&n.bypassOptions.stylesheetManager.adoptStyleSheets(t.adoptedStyleSheets,n.mirror.getId(t.host)),n.restoreHandlers.push(_u({mirror:n.mirror,stylesheetManager:n.bypassOptions.stylesheetManager},t))}),0)}},e.observeAttachShadow=function(t){t.contentWindow&&t.contentDocument&&this.patchAttachShadow(t.contentWindow.Element,t.contentDocument)},e.patchAttachShadow=function(t,e){var n=this;this.restoreHandlers.push(Tc(t.prototype,"attachShadow",(function(t){return function(r){var i=t.call(this,r);return this.shadowRoot&&Hc(this)&&n.addShadowRoot(this.shadowRoot,e),i}})))},e.reset=function(){this.restoreHandlers.forEach((function(t){try{t()}catch(t){}})),this.restoreHandlers=[],this.shadowDoms=new WeakSet},t}(),Mu=function(){function t(){}var e=t.prototype;return e.reset=function(){},e.freeze=function(){},e.unfreeze=function(){},e.lock=function(){},e.unlock=function(){},e.snapshot=function(){},t}(),Au=function(){function t(t){this.trackedLinkElements=new WeakSet,this.styleMirror=new Uc,this.mutationCb=t.mutationCb,this.adoptedStyleSheetCb=t.adoptedStyleSheetCb}var e=t.prototype;return e.attachLinkElement=function(t,e){"_cssText"in e.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:e.id,attributes:e.attributes}]}),this.trackLinkElement(t)},e.trackLinkElement=function(t){this.trackedLinkElements.has(t)||(this.trackedLinkElements.add(t),this.trackStylesheetInLinkElement(t))},e.adoptStyleSheets=function(t,e){if(0!==t.length){for(var n,r={id:e,styleIds:[]},i=[],o=Es(t);!(n=o()).done;){var a=n.value,s=void 0;this.styleMirror.has(a)?s=this.styleMirror.getId(a):(s=this.styleMirror.add(a),i.push({styleId:s,rules:Array.from(a.rules||CSSRule,(function(t,e){return{rule:zs(t),index:e}}))})),r.styleIds.push(s)}i.length>0&&(r.styles=i),this.adoptedStyleSheetCb(r)}},e.reset=function(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet},e.trackStylesheetInLinkElement=function(t){},t}(),Du=function(){function t(){this.nodeMap=new WeakMap,this.loop=!0,this.periodicallyClear()}var e=t.prototype;return e.periodicallyClear=function(){var t=this;!function(){qc("requestAnimationFrame").apply(void 0,arguments)}((function(){t.clear(),t.loop&&t.periodicallyClear()}))},e.inOtherBuffer=function(t,e){var n=this.nodeMap.get(t);return n&&Array.from(n).some((function(t){return t!==e}))},e.add=function(t,e){this.nodeMap.set(t,(this.nodeMap.get(t)||new Set).add(e))},e.clear=function(){this.nodeMap=new WeakMap},e.destroy=function(){this.loop=!1},t}(),Nu=new qs;function Lu(t){void 0===t&&(t={});var e=t,n=e.emit,r=e.checkoutEveryNms,i=e.checkoutEveryNth,o=e.blockClass,a=void 0===o?"rr-block":o,s=e.blockSelector,c=void 0===s?null:s,u=e.unblockSelector,l=void 0===u?null:u,d=e.ignoreClass,p=void 0===d?"rr-ignore":d,f=e.ignoreSelector,h=void 0===f?null:f,v=e.maskAllText,g=void 0!==v&&v,y=e.maskTextClass,_=void 0===y?"rr-mask":y,b=e.unmaskTextClass,S=void 0===b?null:b,k=e.maskTextSelector,x=void 0===k?null:k,w=e.unmaskTextSelector,E=void 0===w?null:w,T=e.inlineStylesheet,I=void 0===T||T,C=e.maskAllInputs,R=e.maskInputOptions,O=e.slimDOMOptions,M=e.maskAttributeFn,A=e.maskInputFn,D=e.maskTextFn,N=e.maxCanvasSize,L=void 0===N?null:N,P=e.packFn,j=e.sampling,F=void 0===j?{}:j,U=e.dataURLOptions,B=void 0===U?{}:U,H=e.mousemoveWait,z=e.recordCanvas,q=void 0!==z&&z,W=e.recordCrossOriginIframes,Y=void 0!==W&&W,J=e.recordAfter,V=void 0===J?"DOMContentLoaded"===t.recordAfter?t.recordAfter:"load":J,K=e.userTriggeredOnInput,G=void 0!==K&&K,$=e.collectFonts,X=void 0!==$&&$,Q=e.inlineImages,Z=void 0!==Q&&Q,tt=e.plugins,et=e.keepIframeSrcFn,nt=void 0===et?function(){return!1}:et,rt=e.ignoreCSSAttributes,it=void 0===rt?new Set([]):rt,ot=e.errorHandler,at=e.onMutation,st=e.getCanvasManager;au(ot);var ct=!Y||window.parent===window,ut=!1;if(!ct)try{window.parent.document&&(ut=!1)}catch(t){ut=!0}if(ct&&!n)throw new Error("emit function is required");void 0!==H&&void 0===F.mousemove&&(F.mousemove=H),Nu.reset();var lt,dt=!0===C?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,radio:!0,checkbox:!0}:void 0!==R?R:{},pt=!0===O||"all"===O?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===O,headMetaDescKeywords:"all"===O}:O||{};!function(t){var e=this;void 0===t&&(t=window),"NodeList"in t&&!t.NodeList.prototype.forEach&&(t.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in t&&!t.DOMTokenList.prototype.forEach&&(t.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=function(){for(var t=arguments.length,n=new Array(t),r=0;r=i,c=r&<&&o.timestamp-lt.timestamp>r;(s||c)&&Tt(!0)}};for(var mt,vt=function(t){Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.Mutation},t)})},gt=function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.Scroll},t)})},yt=function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.CanvasMutation},t)})},_t=new Au({mutationCb:vt,adoptedStyleSheetCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.AdoptedStyleSheet},t)})}}),bt="boolean"==typeof __RRWEB_EXCLUDE_IFRAME__&&__RRWEB_EXCLUDE_IFRAME__?new Iu:new Cu({mirror:Nu,mutationCb:vt,stylesheetManager:_t,recordCrossOriginIframes:Y,wrappedEmit:Eu}),St=Es(tt||[]);!(mt=St()).done;){var kt=mt.value;kt.getMirror&&kt.getMirror({nodeMirror:Nu,crossOriginIframeMirror:bt.crossOriginIframeMirror,crossOriginIframeStyleMirror:bt.crossOriginIframeStyleMirror})}var xt=new Du,wt=function(t,e){try{return t?t(e):new Mu}catch(t){return console.warn("Unable to initialize CanvasManager"),new Mu}}(st,{mirror:Nu,win:window,mutationCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.CanvasMutation},t)})},recordCanvas:q,blockClass:a,blockSelector:c,unblockSelector:l,maxCanvasSize:L,sampling:F.canvas,dataURLOptions:B,errorHandler:ot}),Et="boolean"==typeof __RRWEB_EXCLUDE_SHADOW_DOM__&&__RRWEB_EXCLUDE_SHADOW_DOM__?new Ru:new Ou({mutationCb:vt,scrollCb:gt,bypassOptions:{onMutation:at,blockClass:a,blockSelector:c,unblockSelector:l,maskAllText:g,maskTextClass:_,unmaskTextClass:S,maskTextSelector:x,unmaskTextSelector:E,inlineStylesheet:I,maskInputOptions:dt,dataURLOptions:B,maskAttributeFn:M,maskTextFn:D,maskInputFn:A,recordCanvas:q,inlineImages:Z,sampling:F,slimDOMOptions:pt,iframeManager:bt,stylesheetManager:_t,canvasManager:wt,keepIframeSrcFn:nt,processedNodeManager:xt},mirror:Nu}),Tt=function(t){void 0===t&&(t=!1),Eu({type:Yc.Meta,data:{href:window.location.href,width:Oc(),height:Rc()}},t),_t.reset(),Et.init(),lu.forEach((function(t){return t.lock()}));var e=function(t,e){var n=e||{},r=n.mirror,i=void 0===r?new qs:r,o=n.blockClass,a=n.blockSelector,s=n.unblockSelector,c=n.maskAllText,u=n.maskTextClass,l=n.unmaskTextClass,d=n.maskTextSelector,p=n.unmaskTextSelector,f=n.inlineStylesheet,h=n.inlineImages,m=n.recordCanvas,v=n.maskAllInputs,g=void 0!==v&&v,y=n.slimDOM,_=void 0!==y&&y,b=n.keepIframeSrcFn;return _c(t,{doc:t,mirror:i,blockClass:void 0===o?"rr-block":o,blockSelector:void 0===a?null:a,unblockSelector:void 0===s?null:s,maskAllText:void 0!==c&&c,maskTextClass:void 0===u?"rr-mask":u,unmaskTextClass:void 0===l?null:l,maskTextSelector:void 0===d?null:d,unmaskTextSelector:void 0===p?null:p,skipChild:!1,inlineStylesheet:void 0===f||f,maskInputOptions:!0===g?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0}:!1===g?{}:g,maskAttributeFn:n.maskAttributeFn,maskTextFn:n.maskTextFn,maskInputFn:n.maskInputFn,slimDOMOptions:!0===_||"all"===_?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===_,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===_?{}:_,dataURLOptions:n.dataURLOptions,inlineImages:void 0!==h&&h,recordCanvas:void 0!==m&&m,preserveWhiteSpace:n.preserveWhiteSpace,onSerialize:n.onSerialize,onIframeLoad:n.onIframeLoad,iframeLoadTimeout:n.iframeLoadTimeout,onStylesheetLoad:n.onStylesheetLoad,stylesheetLoadTimeout:n.stylesheetLoadTimeout,keepIframeSrcFn:void 0===b?function(){return!1}:b,newlyAddedElement:!1})}(document,{mirror:Nu,blockClass:a,blockSelector:c,unblockSelector:l,maskAllText:g,maskTextClass:_,unmaskTextClass:S,maskTextSelector:x,unmaskTextSelector:E,inlineStylesheet:I,maskAllInputs:dt,maskAttributeFn:M,maskInputFn:A,maskTextFn:D,slimDOM:pt,dataURLOptions:B,recordCanvas:q,inlineImages:Z,onSerialize:function(t){Pc(t,Nu)&&bt.addIframe(t),jc(t,Nu)&&_t.trackLinkElement(t),Fc(t)&&Et.addShadowRoot(t.shadowRoot,document)},onIframeLoad:function(t,e){bt.attachIframe(t,e),Et.observeAttachShadow(t)},onStylesheetLoad:function(t,e){_t.attachLinkElement(t,e)},keepIframeSrcFn:nt});if(!e)return console.warn("Failed to snapshot the document");Eu({type:Yc.FullSnapshot,data:{node:e,initialOffset:Cc(window)}}),lu.forEach((function(t){return t.unlock()})),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&_t.adoptStyleSheets(document.adoptedStyleSheets,Nu.getId(document))};Tu=Tt;try{var It=[],Ct=function(t){return cu(bu)({onMutation:at,mutationCb:vt,mousemoveCb:function(t,e){return Eu({type:Yc.IncrementalSnapshot,data:{source:e,positions:t}})},mouseInteractionCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.MouseInteraction},t)})},scrollCb:gt,viewportResizeCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.ViewportResize},t)})},inputCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.Input},t)})},mediaInteractionCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.MediaInteraction},t)})},styleSheetRuleCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.StyleSheetRule},t)})},styleDeclarationCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.StyleDeclaration},t)})},canvasMutationCb:yt,fontCb:function(t){return Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.Font},t)})},selectionCb:function(t){Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.Selection},t)})},customElementCb:function(t){Eu({type:Yc.IncrementalSnapshot,data:m({source:Jc.CustomElement},t)})},blockClass:a,ignoreClass:p,ignoreSelector:h,maskAllText:g,maskTextClass:_,unmaskTextClass:S,maskTextSelector:x,unmaskTextSelector:E,maskInputOptions:dt,inlineStylesheet:I,sampling:F,recordCanvas:q,inlineImages:Z,userTriggeredOnInput:G,collectFonts:X,doc:t,maskAttributeFn:M,maskInputFn:A,maskTextFn:D,keepIframeSrcFn:nt,blockSelector:c,unblockSelector:l,slimDOMOptions:pt,dataURLOptions:B,mirror:Nu,iframeManager:bt,stylesheetManager:_t,shadowDomManager:Et,processedNodeManager:xt,canvasManager:wt,ignoreCSSAttributes:it,plugins:vo([tt,"optionalAccess",function(t){return t.filter},"call",function(t){return t((function(t){return t.observer}))},"optionalAccess",function(t){return t.map},"call",function(t){return t((function(t){return{observer:t.observer,options:t.options,callback:function(e){return Eu({type:Yc.Plugin,data:{plugin:t.name,payload:e}})}}}))}])||[]},{})};bt.addLoadListener((function(t){try{It.push(Ct(t.contentDocument))}catch(t){console.warn(t)}}));var Rt=function(){Tt(),It.push(Ct(document))};return"interactive"===document.readyState||"complete"===document.readyState?Rt():(It.push(Sc("DOMContentLoaded",(function(){Eu({type:Yc.DomContentLoaded,data:{}}),"DOMContentLoaded"===V&&Rt()}))),It.push(Sc("load",(function(){Eu({type:Yc.Load,data:{}}),"load"===V&&Rt()}),window))),function(){It.forEach((function(t){return t()})),xt.destroy(),Tu=void 0,su()}}catch(t){console.warn(t)}}Lu.mirror=Nu,Lu.takeFullSnapshot=function(t){if(!Tu)throw new Error("please take full snapshot after start recording");Tu(t)};var Pu=3;function ju(t){return t>9999999999?t:1e3*t}function Fu(t){return t>9999999999?t/1e3:t}function Uu(t,e){"sentry.transaction"!==e.category&&(["ui.click","ui.input"].includes(e.category)?t.triggerUserActivity():t.checkAndHandleExpiredSession(),t.addUpdate((function(){return t.throttledAddEvent({type:Yc.Custom,timestamp:1e3*(e.timestamp||0),data:{tag:"breadcrumb",payload:Sa(e,10,1e3)}}),"console"===e.category})))}var Bu,Hu="button,a";function zu(t){return t.closest(Hu)||t}function qu(t){var e=Wu(t);return e&&e instanceof Element?zu(e):e}function Wu(t){return function(t){return"object"==typeof t&&!!t&&"target"in t}(t)?t.target:t}var Yu,Ju=function(){function t(t,e,n){void 0===n&&(n=Uu),this._lastMutation=0,this._lastScroll=0,this._clicks=[],this._timeout=e.timeout/1e3,this._threshold=e.threshold/1e3,this._scollTimeout=e.scrollTimeout/1e3,this._replay=t,this._ignoreSelector=e.ignoreSelector,this._addBreadcrumbEvent=n}var e=t.prototype;return e.addListeners=function(){var t,e=this,n=(t=function(){e._lastMutation=Ku()},Bu||(Bu=[],Vo(Cs,"open",(function(t){return function(){if(Bu)try{Bu.forEach((function(t){return t()}))}catch(t){}for(var e=arguments.length,n=new Array(e),r=0;r-1&&Bu.splice(e,1)});this._teardown=function(){n(),e._clicks=[],e._lastMutation=0,e._lastScroll=0}},e.removeListeners=function(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)},e.handleClick=function(t,e){if(!function(t,e){return!Vu.includes(t.tagName)||("INPUT"===t.tagName&&!["submit","button"].includes(t.getAttribute("type")||"")||(!("A"!==t.tagName||!(t.hasAttribute("download")||t.hasAttribute("target")&&"_self"!==t.getAttribute("target")))||!(!e||!t.matches(e))))}(e,this._ignoreSelector)&&function(t){return!(!t.data||"number"!=typeof t.data.nodeId||!t.timestamp)}(t)){var n={timestamp:Fu(t.timestamp),clickBreadcrumb:t,clickCount:0,node:e};this._clicks.some((function(t){return t.node===n.node&&Math.abs(t.timestamp-n.timestamp)<1}))||(this._clicks.push(n),1===this._clicks.length&&this._scheduleCheckClicks())}},e.registerMutation=function(t){void 0===t&&(t=Date.now()),this._lastMutation=Fu(t)},e.registerScroll=function(t){void 0===t&&(t=Date.now()),this._lastScroll=Fu(t)},e.registerClick=function(t){var e=zu(t);this._handleMultiClick(e)},e._handleMultiClick=function(t){this._getClicks(t).forEach((function(t){t.clickCount++}))},e._getClicks=function(t){return this._clicks.filter((function(e){return e.node===t}))},e._checkClicks=function(){var t=this,e=[],n=Ku();this._clicks.forEach((function(r){!r.mutationAfter&&t._lastMutation&&(r.mutationAfter=r.timestamp<=t._lastMutation?t._lastMutation-r.timestamp:void 0),!r.scrollAfter&&t._lastScroll&&(r.scrollAfter=r.timestamp<=t._lastScroll?t._lastScroll-r.timestamp:void 0),r.timestamp+t._timeout<=n&&e.push(r)}));for(var r=0,i=e;r-1&&(this._generateBreadcrumbs(o),this._clicks.splice(a,1))}this._clicks.length&&this._scheduleCheckClicks()},e._generateBreadcrumbs=function(t){var e=this._replay,n=t.scrollAfter&&t.scrollAfter<=this._scollTimeout,r=t.mutationAfter&&t.mutationAfter<=this._threshold,i=!n&&!r,o=t.clickCount,a=t.clickBreadcrumb;if(i){var s=1e3*Math.min(t.mutationAfter||this._timeout,this._timeout),c=s<1e3*this._timeout?"mutation":"timeout",u={type:"default",message:a.message,timestamp:a.timestamp,category:"ui.slowClickDetected",data:m({},a.data,{url:Cs.location.href,route:e.getCurrentRoute(),timeAfterClickMs:s,endReason:c,clickCount:o||1})};this._addBreadcrumbEvent(e,u)}else if(o>1){var l={type:"default",message:a.message,timestamp:a.timestamp,category:"ui.multiClick",data:m({},a.data,{url:Cs.location.href,route:e.getCurrentRoute(),clickCount:o,metric:!0})};this._addBreadcrumbEvent(e,l)}},e._scheduleCheckClicks=function(){var t=this;this._checkClickTimeout&&clearTimeout(this._checkClickTimeout),this._checkClickTimeout=setTimeout((function(){return t._checkClicks()}),1e3)},t}(),Vu=["A","BUTTON","INPUT"];function Ku(){return Date.now()/1e3}function Gu(t){return m({timestamp:Date.now()/1e3,type:"default"},t)}!function(t){t[t.Document=0]="Document",t[t.DocumentType=1]="DocumentType",t[t.Element=2]="Element",t[t.Text=3]="Text",t[t.CDATA=4]="CDATA",t[t.Comment=5]="Comment"}(Yu||(Yu={}));var $u=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled","data-sentry-component"]);function Xu(t){var e={};for(var n in t)if($u.has(n)){var r=n;"data-testid"!==n&&"data-test-id"!==n||(r="testId"),e[r]=t[n]}return e}function Qu(t,e){var n=Lu.mirror.getId(t),r=n&&Lu.mirror.getNode(n),i=r&&Lu.mirror.getMeta(r),o=i&&function(t){return t.type===Yu.Element}(i)?i:null;return{message:e,data:o?{nodeId:n,node:{id:n,tagName:o.tagName,textContent:Array.from(o.childNodes).map((function(t){return t.type===Yu.Text&&t.textContent})).filter(Boolean).map((function(t){return t.trim()})).join(""),attributes:Xu(o.attributes)}}:{}}}var Zu={resource:function(t){var e=t.entryType,n=t.initiatorType,r=t.name,i=t.responseEnd,o=t.startTime,a=t.decodedBodySize,s=t.encodedBodySize,c=t.responseStatus,u=t.transferSize;return["fetch","xmlhttprequest"].includes(n)?null:{type:e+"."+n,start:el(o),end:el(i),name:r,data:{size:u,statusCode:c,decodedBodySize:a,encodedBodySize:s}}},paint:function(t){var e=t.duration,n=t.entryType,r=t.name,i=el(t.startTime);return{type:n,name:r,start:i,end:i+e,data:void 0}},navigation:function(t){var e=t.entryType,n=t.name,r=t.decodedBodySize,i=t.duration,o=t.domComplete,a=t.encodedBodySize,s=t.domContentLoadedEventStart,c=t.domContentLoadedEventEnd,u=t.domInteractive,l=t.loadEventStart,d=t.loadEventEnd,p=t.redirectCount,f=t.startTime,h=t.transferSize,m=t.type;return 0===i?null:{type:e+"."+m,start:el(f),end:el(o),name:n,data:{size:h,decodedBodySize:r,encodedBodySize:a,duration:i,domInteractive:u,domContentLoadedEventStart:s,domContentLoadedEventEnd:c,loadEventStart:l,loadEventEnd:d,domComplete:o,redirectCount:p}}}};function tl(t){return Zu[t.entryType]?Zu[t.entryType](t):null}function el(t){return((Mo||Cs.performance.timeOrigin)+t)/1e3}function nl(t){function e(e){t.performanceEntries.includes(e)||t.performanceEntries.push(e)}function n(t){t.entries.forEach(e)}var r,i=[];return["navigation","paint","resource"].forEach((function(t){i.push(function(t,e){return xs(t,e),bs[t]||(function(t){var e={};"event"===t&&(e.durationThreshold=0),hs(t,(function(e){Ss(t,{entries:e})}),e)}(t),bs[t]=!0),ws(t,e)}(t,n))})),i.push((void 0===r&&(r=!1),function(t,e,n,r,i){var o;return void 0===i&&(i=!1),xs(t,e),bs[t]||(o=n(),bs[t]=!0),r&&e({metric:r}),ws(t,e,i?o:void 0)}("lcp",(function(e){var n=e.metric;t.replayPerformanceEntries.push(function(t){var e=t.entries,n=e[e.length-1],r=n?n.element:void 0,i=t.value,o=el(i);return{type:"largest-contentful-paint",name:"largest-contentful-paint",start:o,end:o,data:{value:i,size:i,nodeId:r?Lu.mirror.getId(r):void 0}}}(n))}),ks,ys,r))),function(){i.forEach((function(t){return t()}))}}var rl=!1;function il(t,e){rl&&(jo.info(t),e&&al(t))}function ol(t,e){rl&&(jo.info(t),e&&setTimeout((function(){al(t)}),0))}function al(t){var e,n;e={category:"console",data:{logger:"replay"},level:"info",message:t},n={level:"info"},ma().addBreadcrumb(e,n)}var sl=function(t){function e(){return t.call(this,"Event buffer exceeded maximum size of "+Ps+".")||this}return Zn(e,t),e}(mo(Error)),cl=function(){function t(){this.events=[],this._totalSize=0,this.hasCheckout=!1}var e=t.prototype;return e.destroy=function(){this.events=[]},e.addEvent=function(){var t=po(ht().mark((function t(e){var n;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=JSON.stringify(e).length,this._totalSize+=n,!(this._totalSize>Ps)){t.next=4;break}throw new sl;case 4:this.events.push(e);case 5:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e.finish=function(){var t=this;return new Promise((function(e){var n=t.events;t.clear(),e(JSON.stringify(n))}))},e.clear=function(){this.events=[],this._totalSize=0,this.hasCheckout=!1},e.getEarliestTimestamp=function(){var t=this.events.map((function(t){return t.timestamp})).sort()[0];return t?ju(t):null},nr(t,[{key:"hasEvents",get:function(){return this.events.length>0}},{key:"type",get:function(){return"sync"}}]),t}(),ul=function(){function t(t){this._worker=t,this._id=0}var e=t.prototype;return e.ensureReady=function(){var t=this;return this._ensureReadyPromise||(this._ensureReadyPromise=new Promise((function(e,n){t._worker.addEventListener("message",(function(t){t.data.success?e():n()}),{once:!0}),t._worker.addEventListener("error",(function(t){n(t)}),{once:!0})}))),this._ensureReadyPromise},e.destroy=function(){il("[Replay] Destroying compression worker"),this._worker.terminate()},e.postMessage=function(t,e){var n=this,r=this._getAndIncrementId();return new Promise((function(i,o){n._worker.addEventListener("message",(function e(a){var s=a.data;if(s.method===t&&s.id===r){if(n._worker.removeEventListener("message",e),!s.success)return rl&&jo.error("[Replay]",s.response),void o(new Error("Error in compression worker"));i(s.response)}})),n._worker.postMessage({id:r,method:t,arg:e})}))},e._getAndIncrementId=function(){return this._id++},t}(),ll=function(){function t(t){this._worker=new ul(t),this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1}var e=t.prototype;return e.ensureReady=function(){return this._worker.ensureReady()},e.destroy=function(){this._worker.destroy()},e.addEvent=function(t){var e=ju(t.timestamp);(!this._earliestTimestamp||ePs?Promise.reject(new sl):this._sendEventToWorker(n)},e.finish=function(){return this._finishRequest()},e.clear=function(){this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this._worker.postMessage("clear").then(null,(function(t){rl&&jo.warn('[Replay] Sending "clear" message to worker failed',t)}))},e.getEarliestTimestamp=function(){return this._earliestTimestamp},e._sendEventToWorker=function(t){return this._worker.postMessage("addEvent",t)},e._finishRequest=function(){var t=po(ht().mark((function t(){var e;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this._worker.postMessage("finish");case 2:return e=t.sent,this._earliestTimestamp=null,this._totalSize=0,t.abrupt("return",e);case 6:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),nr(t,[{key:"hasEvents",get:function(){return!!this._earliestTimestamp}},{key:"type",get:function(){return"worker"}}]),t}(),dl=function(){function t(t){this._fallback=new cl,this._compression=new ll(t),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}var e=t.prototype;return e.destroy=function(){this._fallback.destroy(),this._compression.destroy()},e.clear=function(){return this._used.clear()},e.getEarliestTimestamp=function(){return this._used.getEarliestTimestamp()},e.addEvent=function(t){return this._used.addEvent(t)},e.finish=function(){var t=po(ht().mark((function t(){return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.ensureWorkerIsLoaded();case 2:return t.abrupt("return",this._used.finish());case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),e.ensureWorkerIsLoaded=function(){return this._ensureWorkerIsLoadedPromise},e._ensureWorkerIsLoaded=function(){var t=po(ht().mark((function t(){return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this._compression.ensureReady();case 3:t.next=9;break;case 5:return t.prev=5,t.t0=t.catch(0),il("[Replay] Failed to load the compression worker, falling back to simple buffer"),t.abrupt("return");case 9:return t.next=11,this._switchToCompressionWorker();case 11:case"end":return t.stop()}}),t,this,[[0,5]])})));return function(){return t.apply(this,arguments)}}(),e._switchToCompressionWorker=function(){var t=po(ht().mark((function t(){var e,n,r,i,o,a,s;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:for(e=this._fallback,n=e.events,r=e.hasCheckout,i=[],o=Es(n);!(a=o()).done;)s=a.value,i.push(this._compression.addEvent(s));return this._compression.hasCheckout=r,this._used=this._compression,t.prev=5,t.next=8,Promise.all(i);case 8:t.next=13;break;case 10:t.prev=10,t.t0=t.catch(5),rl&&jo.warn("[Replay] Failed to add events when switching buffers.",t.t0);case 13:case"end":return t.stop()}}),t,this,[[5,10]])})));return function(){return t.apply(this,arguments)}}(),nr(t,[{key:"type",get:function(){return this._used.type}},{key:"hasEvents",get:function(){return this._used.hasEvents}},{key:"hasCheckout",get:function(){return this._used.hasCheckout},set:function(t){this._used.hasCheckout=t}}]),t}();function pl(){try{return"sessionStorage"in Cs&&!!Cs.sessionStorage}catch(t){return!1}}function fl(t){return void 0!==t&&Math.random()t.getContext().initialTimestamp+t.getOptions().maxReplayDuration&&(il("[Replay] Skipping event with timestamp "+n+" because it is after maxReplayDuration",t.getOptions()._experiments.traceInternals),1))}function El(t,e){try{if("function"==typeof e&&function(t){return t.type===Yc.Custom}(t))return e(t)}catch(t){return rl&&jo.error("[Replay] An error occured in the `beforeAddRecordingEvent` callback, skipping the event...",t),null}return t}function Tl(t){return!t.type}function Il(t){return"transaction"===t.type}function Cl(t){return"feedback"===t.type}function Rl(t){var e=function(){var t=Ia();if(!t)return!1;var e=t.getTransport();return e&&e.send.__sentry__baseTransport__||!1}();return function(n,r){if(t.isEnabled()&&(Tl(n)||Il(n))){var i=r&&r.statusCode;e&&(!i||i<200||i>=300)||(Il(n)?function(t,e){var n=t.getContext();e.contexts&&e.contexts.trace&&e.contexts.trace.trace_id&&n.traceIds.size<100&&n.traceIds.add(e.contexts.trace.trace_id)}(t,n):function(t,e){var n=t.getContext();if(e.event_id&&n.errorIds.size<100&&n.errorIds.add(e.event_id),"buffer"===t.recordingMode&&e.tags&&e.tags.replayId){var r=t.getOptions().beforeErrorSampling;("function"!=typeof r||r(e))&&setTimeout((function(){t.sendBufferedReplayOrFlush()}))}}(t,n))}}}function Ol(t,e){return e.map((function(e){var n=e.type,r=e.start,i=e.end,o=e.name,a=e.data,s=t.throttledAddEvent({type:Yc.Custom,timestamp:r,data:{tag:"performanceSpan",payload:{op:n,description:o,startTimestamp:r,endTimestamp:i,data:a}}});return"string"==typeof s?Promise.resolve(null):s}))}function Ml(t,e){t.isEnabled()&&null!==e&&(function(t,e){return(!rl||!t.getOptions()._experiments.traceInternals)&&function(t,e){var n=e&&function(t){return void 0!==t.getClient}(e)?e.getClient():e,r=n&&n.getDsn(),i=n&&n.getOptions().tunnel;return function(t,e){return!!e&&t.includes(e.host)}(t,r)||function(t,e){return!!e&&Ra(t)===Ra(e)}(t,i)}(e,Ia())}(t,e.name)||t.addUpdate((function(){return Ol(t,[e]),!0})))}function Al(t,e){if(t)try{if("string"==typeof t)return e.encode(t).length;if(t instanceof URLSearchParams)return e.encode(t.toString()).length;if(t instanceof FormData){var n=Bl(t);return e.encode(n).length}if(t instanceof Blob)return t.size;if(t instanceof ArrayBuffer)return t.byteLength}catch(t){}}function Dl(t){if(t){var e=parseInt(t,10);return isNaN(e)?void 0:e}}function Nl(t){try{if("string"==typeof t)return[t];if(t instanceof URLSearchParams)return[t.toString()];if(t instanceof FormData)return[Bl(t)];if(!t)return[void 0]}catch(e){return rl&&jo.warn("[Replay] Failed to serialize body",t),[void 0,"BODY_PARSE_ERROR"]}return rl&&jo.info("[Replay] Skipping network body because of body type",t),[void 0,"UNPARSEABLE_BODY_TYPE"]}function Ll(t,e){if(!t)return{headers:{},size:void 0,_meta:{warnings:[e]}};var n=m({},t._meta),r=n.warnings||[];return n.warnings=[].concat(r,[e]),t._meta=n,t}function Pl(t,e){return e?{type:t,start:e.startTimestamp/1e3,end:e.endTimestamp/1e3,name:e.url,data:Xo({method:e.method,statusCode:e.statusCode,request:e.request,response:e.response})}:null}function jl(t){return{headers:{},size:t,_meta:{warnings:["URL_SKIPPED"]}}}function Fl(t,e,n){if(e||0!==Object.keys(t).length){if(!e)return{headers:t};if(!n)return{headers:t,size:e};var r={headers:t,size:e},i=function(t){if(!t||"string"!=typeof t)return{body:t};var e,n,r,i=t.length>Ns,o=(n=(e=t)[0],r=e[e.length-1],"["===n&&"]"===r||"{"===n&&"}"===r);if(i){var a=t.slice(0,Ns);return o?{body:a,warnings:["MAYBE_JSON_TRUNCATED"]}:{body:a+"…",warnings:["TEXT_TRUNCATED"]}}if(o)try{return{body:JSON.parse(t)}}catch(t){}return{body:t}}(n),o=i.body,a=i.warnings;return r.body=o,a&&a.length>0&&(r._meta={warnings:a}),r}}function Ul(t,e){return Object.keys(t).reduce((function(n,r){var i=r.toLowerCase();return e.includes(i)&&t[r]&&(n[i]=t[r]),n}),{})}function Bl(t){return new URLSearchParams(t).toString()}function Hl(t,e){var n,r,i,o=function(t,e){if(void 0===e&&(e=Cs.document.baseURI),t.startsWith("http://")||t.startsWith("https://")||t.startsWith(Cs.location.origin))return t;var n=new URL(t,e);if(n.origin!==new URL(e).origin)return t;var r=n.href;return!t.endsWith("/")&&r.endsWith("/")?r.slice(0,-1):r}(t);return n=o,void 0===(r=e)&&(r=[]),void 0===i&&(i=!1),r.some((function(t){return function(t,e,n){return void 0===n&&(n=!1),!!_o(t)&&(yo(e,"RegExp")?e.test(t):!!_o(e)&&(n?t===e:t.includes(e)))}(n,t,i)}))}function zl(){return(zl=po(ht().mark((function t(e,n,r){var i,o;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,ql(e,n,r);case 3:i=t.sent,o=Pl("resource.fetch",i),Ml(r.replay,o),t.next=11;break;case 8:t.prev=8,t.t0=t.catch(0),rl&&jo.error("[Replay] Failed to capture fetch breadcrumb",t.t0);case 11:case"end":return t.stop()}}),t,null,[[0,8]])})))).apply(this,arguments)}function ql(t,e,n){return Wl.apply(this,arguments)}function Wl(){return(Wl=po(ht().mark((function t(e,n,r){var i,o,a,s,c,u,l,d,p,f,h,m,v,g,y;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=Date.now(),o=n.startTimestamp,a=void 0===o?i:o,s=n.endTimestamp,c=void 0===s?i:s,u=e.data,l=u.url,d=u.method,p=u.status_code,f=void 0===p?0:p,h=u.request_body_size,m=u.response_body_size,v=Hl(l,r.networkDetailAllowUrls)&&!Hl(l,r.networkDetailDenyUrls),g=v?Yl(r,n.input,h):jl(h),t.next=7,Jl(v,r,n.response,m);case 7:return y=t.sent,t.abrupt("return",{startTimestamp:a,endTimestamp:c,url:l,method:d,statusCode:f,request:g,response:y});case 9:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function Yl(t,e,n){var r,i,o=t.networkCaptureBodies,a=t.networkRequestHeaders,s=e?(i=a,1===(r=e).length&&"string"!=typeof r[0]?Zl(r[0],i):2===r.length?Zl(r[1],i):{}):{};if(!o)return Fl(s,n,void 0);var c=Nl(Xl(e)),u=c[0],l=c[1],d=Fl(s,n,u);return l?Ll(d,l):d}function Jl(t,e,n,r){return Vl.apply(this,arguments)}function Vl(){return(Vl=po(ht().mark((function t(e,n,r,i){var o,a,s,c,u,l,d,p;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=n.networkCaptureBodies,a=n.textEncoder,s=n.networkResponseHeaders,e||void 0===i){t.next=3;break}return t.abrupt("return",jl(i));case 3:if(c=r?Ql(r.headers,s):{},r&&(o||void 0===i)){t.next=6;break}return t.abrupt("return",Fl(c,i,void 0));case 6:return t.next=8,Gl(r);case 8:if(u=t.sent,l=u[0],d=u[1],p=Kl(l,{networkCaptureBodies:o,textEncoder:a,responseBodySize:i,captureDetails:e,headers:c}),!d){t.next=14;break}return t.abrupt("return",Ll(p,d));case 14:return t.abrupt("return",p);case 15:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function Kl(t,e){var n=e.networkCaptureBodies,r=e.textEncoder,i=e.responseBodySize,o=e.captureDetails,a=e.headers;try{var s=t&&t.length&&void 0===i?Al(t,r):i;return o?Fl(a,s,n?t:void 0):jl(s)}catch(t){return rl&&jo.warn("[Replay] Failed to serialize response body",t),Fl(a,i,void 0)}}function Gl(t){return $l.apply(this,arguments)}function $l(){return($l=po(ht().mark((function t(e){var n,r;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=td(e)){t.next=3;break}return t.abrupt("return",[void 0,"BODY_PARSE_ERROR"]);case 3:return t.prev=3,t.next=6,ed(n);case 6:return r=t.sent,t.abrupt("return",[r]);case 10:return t.prev=10,t.t0=t.catch(3),rl&&jo.warn("[Replay] Failed to get text body from response",t.t0),t.abrupt("return",[void 0,"BODY_PARSE_ERROR"]);case 14:case"end":return t.stop()}}),t,null,[[3,10]])})))).apply(this,arguments)}function Xl(t){if(void 0===t&&(t=[]),2===t.length&&"object"==typeof t[1])return t[1].body}function Ql(t,e){var n={};return e.forEach((function(e){t.get(e)&&(n[e]=t.get(e))})),n}function Zl(t,e){if(!t)return{};var n=t.headers;return n?n instanceof Headers?Ql(n,e):Array.isArray(n)?{}:Ul(n,e):{}}function td(t){try{return t.clone()}catch(t){rl&&jo.warn("[Replay] Failed to clone response body",t)}}function ed(t){return new Promise((function(e,n){var r=setTimeout((function(){return n(new Error("Timeout while trying to read response body"))}),500);(function(t){return nd.apply(this,arguments)})(t).then((function(t){return e(t)}),(function(t){return n(t)})).finally((function(){return clearTimeout(r)}))}))}function nd(){return(nd=po(ht().mark((function t(e){return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.text();case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function rd(){return(rd=po(ht().mark((function t(e,n,r){var i,o;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:try{i=id(e,n,r),o=Pl("resource.xhr",i),Ml(r.replay,o)}catch(t){rl&&jo.error("[Replay] Failed to capture xhr breadcrumb",t)}case 1:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function id(t,e,n){var r=Date.now(),i=e.startTimestamp,o=void 0===i?r:i,a=e.endTimestamp,s=void 0===a?r:a,c=e.input,u=e.xhr,l=t.data,d=l.url,p=l.method,f=l.status_code,h=void 0===f?0:f,m=l.request_body_size,v=l.response_body_size;if(!d)return null;if(!u||!Hl(d,n.networkDetailAllowUrls)||Hl(d,n.networkDetailDenyUrls))return{startTimestamp:o,endTimestamp:s,url:d,method:p,statusCode:h,request:jl(m),response:jl(v)};var g=u[ja],y=g?Ul(g.request_headers,n.networkRequestHeaders):{},_=Ul(function(t){var e=t.getAllResponseHeaders();return e?e.split("\r\n").reduce((function(t,e){var n=e.split(": "),r=n[0],i=n[1];return t[r.toLowerCase()]=i,t}),{}):{}}(u),n.networkResponseHeaders),b=n.networkCaptureBodies?Nl(c):[void 0],S=b[0],k=b[1],x=n.networkCaptureBodies?function(t){var e=[];try{return[t.responseText]}catch(t){e.push(t)}try{return function(t,e){try{if("string"==typeof t)return[t];if(t instanceof Document)return[t.body.outerHTML];if("json"===e&&t&&"object"==typeof t)return[JSON.stringify(t)];if(!t)return[void 0]}catch(e){return rl&&jo.warn("[Replay] Failed to serialize body",t),[void 0,"BODY_PARSE_ERROR"]}return rl&&jo.info("[Replay] Skipping network body because of body type",t),[void 0,"UNPARSEABLE_BODY_TYPE"]}(t.response,t.responseType)}catch(t){e.push(t)}return rl&&jo.warn.apply(jo,["[Replay] Failed to get xhr response body"].concat(e)),[void 0]}(u):[void 0],w=x[0],E=x[1],T=Fl(y,m,S),I=Fl(_,v,w);return{startTimestamp:o,endTimestamp:s,url:d,method:p,statusCode:h,request:k?Ll(T,k):T,response:E?Ll(I,E):I}}function od(t){var e,n=Ia();try{var r=new TextEncoder,i=t.getOptions(),o={replay:t,textEncoder:r,networkDetailAllowUrls:i.networkDetailAllowUrls,networkDetailDenyUrls:i.networkDetailDenyUrls,networkCaptureBodies:i.networkCaptureBodies,networkRequestHeaders:i.networkRequestHeaders,networkResponseHeaders:i.networkResponseHeaders};n&&n.on?n.on("beforeAddBreadcrumb",(function(t,e){return function(t,e,n){if(e.data)try{(function(t){return"xhr"===t.category})(e)&&function(t){return t&&t.xhr}(n)&&(function(t,e,n){var r=e.xhr,i=e.input;if(r){var o=Al(i,n.textEncoder),a=r.getResponseHeader("content-length")?Dl(r.getResponseHeader("content-length")):function(t,e,n){try{return Al("json"===e&&t&&"object"==typeof t?JSON.stringify(t):t,n)}catch(t){return}}(r.response,r.responseType,n.textEncoder);void 0!==o&&(t.data.request_body_size=o),void 0!==a&&(t.data.response_body_size=a)}}(e,n,t),function(t,e,n){rd.apply(this,arguments)}(e,n,t)),function(t){return"fetch"===t.category}(e)&&function(t){return t&&t.response}(n)&&(function(t,e,n){var r=e.input,i=e.response,o=Al(r?Xl(r):void 0,n.textEncoder),a=i?Dl(i.headers.get("content-length")):void 0;void 0!==o&&(t.data.request_body_size=o),void 0!==a&&(t.data.response_body_size=a)}(e,n,t),function(t,e,n){zl.apply(this,arguments)}(e,n,t))}catch(t){rl&&jo.warn("Error when enriching network breadcrumb")}}(o,t,e)})):(e=function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.fetchData,i=t.response;if(!n)return null;var o=r.method;return{type:"resource.fetch",start:e/1e3,end:n/1e3,name:r.url,data:{method:o,statusCode:i?i.status:void 0}}}(e);Ml(t,n)}}}(t),Da("fetch",e),Na("fetch",Ha),function(t){Da("xhr",t),Na("xhr",Fa)}(function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.startTimestamp,n=t.endTimestamp,r=t.xhr[ja];if(!e||!n||!r)return null;var i=r.method,o=r.url,a=r.status_code;return void 0===o?null:{type:"resource.xhr",name:o,start:e/1e3,end:n/1e3,data:{method:i,statusCode:a}}}(e);Ml(t,n)}}}(t)))}catch(t){}}var ad=null;function sd(t){var e,n,r=Ca(),i=Ia();r.addScopeListener(function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.getLastBreadcrumb&&t.getLastBreadcrumb();return ad!==e&&e?(ad=e,!e.category||["fetch","xhr","sentry.event","sentry.transaction"].includes(e.category)||e.category.startsWith("ui.")?null:"console"===e.category?function(t){var e=t.data&&t.data.arguments;if(!Array.isArray(e)||0===e.length)return Gu(t);var n=!1,r=e.map((function(t){if(!t)return t;if("string"==typeof t)return t.length>Ls?(n=!0,t.slice(0,Ls)+"…"):t;if("object"==typeof t)try{var e=Sa(t,7);return JSON.stringify(e).length>Ls?(n=!0,JSON.stringify(e,null,2).slice(0,Ls)+"…"):e}catch(t){}return t}));return Gu(m({},t,{data:m({},t.data,{arguments:r},n?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{})}))}(e):Gu(e)):null}(e);n&&Uu(t,n)}}}(t)),Da("dom",function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=function(t){var e,n="click"===t.name,r=null;try{e=Yo(r=n?qu(t.event):Wu(t.event),{maxStringLength:200})||""}catch(t){e=""}return{target:r,message:e}}(t),n=e.target,r=e.message;return Gu(m({category:"ui."+t.name},Qu(n,r)))}(e);if(n){var r="click"===e.name,i=r?e.event:void 0;!(r&&t.clickDetector&&i&&i.target)||i.altKey||i.metaKey||i.ctrlKey||i.shiftKey||(o=t.clickDetector,a=n,s=qu(e.event),o.handleClick(a,s)),Uu(t,n)}}var o,a,s}}(t)),Na("dom",Ga),e=function(t){return function(e){if(t.isEnabled()){var n=function(t){var e=t.from,n=t.to,r=Date.now()/1e3;return{type:"navigation.push",start:r,end:r,name:n,data:{previous:e}}}(e);null!==n&&(t.getContext().urls.push(n.name),t.triggerUserActivity(),t.addUpdate((function(){return Ol(t,[n]),!1})))}}}(t),Da(n="history",e),Na(n,ts),od(t);var o=function(t,e){void 0===e&&(e=!1);var n=e?Rl(t):void 0;return Object.assign((function(e,r){if(!t.isEnabled())return e;if(function(t){return"replay_event"===t.type}(e))return delete e.breadcrumbs,e;if(!Tl(e)&&!Il(e)&&!Cl(e))return e;if(!t.checkAndHandleExpiredSession())return e;if(Cl(e))return t.flush(),e.contexts.feedback.replay_id=t.getSessionId(),function(t,e){t.triggerUserActivity(),t.addUpdate((function(){return!e.timestamp||(t.throttledAddEvent({type:Yc.Custom,timestamp:1e3*e.timestamp,data:{tag:"breadcrumb",payload:{timestamp:e.timestamp,type:"default",category:"sentry.feedback",data:{feedbackId:e.event_id}}}}),!1)}))}(t,e),e;if(function(t,e){return!(t.type||!t.exception||!t.exception.values||!t.exception.values.length||!e.originalException||!e.originalException.__rrweb__)}(e,r)&&!t.getOptions()._experiments.captureExceptions)return rl&&jo.log("[Replay] Ignoring error from rrweb internals",e),null;var i=function(t,e){return"buffer"===t.recordingMode&&e.message!==Ms&&!(!e.exception||e.type)&&fl(t.getOptions().errorSampleRate)}(t,e);return(i||"session"===t.recordingMode)&&(e.tags=m({},e.tags,{replayId:t.getSessionId()})),n&&n(e,{statusCode:200}),e}),{id:"Replay"})}(t,!cd(i));i&&i.addEventProcessor?i.addEventProcessor(o):function(t){var e=Ia();e&&e.addEventProcessor&&e.addEventProcessor(t)}(o),cd(i)&&(i.on("beforeSendEvent",function(t){return function(e){t.isEnabled()&&Tl(e)&&function(t,e){var n=e.exception&&e.exception.values&&e.exception.values[0].value;"string"==typeof n&&(n.match(/reactjs\.org\/docs\/error-decoder\.html\?invariant=(418|419|422|423|425)/)||n.match(/(does not match server-rendered HTML|Hydration failed because)/i))&&Uu(t,Gu({category:"replay.hydrate-error"}))}(t,e)}}(t)),i.on("afterSendEvent",Rl(t)),i.on("createDsc",(function(e){var n=t.getSessionId();n&&t.isEnabled()&&"session"===t.recordingMode&&t.checkAndHandleExpiredSession()&&(e.replay_id=n)})),i.on("startTransaction",(function(e){t.lastTransaction=e})),i.on("finishTransaction",(function(e){t.lastTransaction=e})),i.on("beforeSendFeedback",(function(e,n){var r=t.getSessionId();n&&n.includeReplay&&t.isEnabled()&&r&&e.contexts&&e.contexts.feedback&&(e.contexts.feedback.replay_id=r)})))}function cd(t){return!(!t||!t.on)}function ud(t){return ld.apply(this,arguments)}function ld(){return(ld=po(ht().mark((function t(e){return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.abrupt("return",Promise.all(Ol(e,[(n=Cs.performance.memory,void 0,void 0,void 0,void 0,r=n.jsHeapSizeLimit,i=n.totalJSHeapSize,o=n.usedJSHeapSize,a=Date.now()/1e3,{type:"memory",name:"memory",start:a,end:a,data:{memory:{jsHeapSizeLimit:r,totalJSHeapSize:i,usedJSHeapSize:o}}})])));case 4:return t.prev=4,t.t0=t.catch(0),t.abrupt("return",[]);case 7:case"end":return t.stop()}var n,r,i,o,a}),t,null,[[0,4]])})))).apply(this,arguments)}function dd(t){var e=!1;return function(n,r){if(t.checkAndHandleExpiredSession()){var i=r||!e;e=!0,t.clickDetector&&function(t,e){try{if(!function(t){return t.type===Pu}(e))return;var n=e.data.source;if(n===Jc.Mutation&&t.registerMutation(e.timestamp),n===Jc.Scroll&&t.registerScroll(e.timestamp),function(t){return t.data.source===Jc.MouseInteraction}(e)){var r=e.data,i=r.type,o=r.id,a=Lu.mirror.getNode(o);a instanceof HTMLElement&&i===Vc.Click&&t.registerClick(a)}}catch(t){}}(t.clickDetector,n),t.addUpdate((function(){if("buffer"===t.recordingMode&&i&&t.setInitialState(),!Sl(t,n,i))return!0;if(!i)return!1;if(function(t,e){e&&t.session&&0===t.session.segmentId&&Sl(t,function(t){var e=t.getOptions();return{type:Yc.Custom,timestamp:Date.now(),data:{tag:"options",payload:{shouldRecordCanvas:t.isRecordingCanvas(),sessionSampleRate:e.sessionSampleRate,errorSampleRate:e.errorSampleRate,useCompressionOption:e.useCompression,blockAllMedia:e.blockAllMedia,maskAllText:e.maskAllText,maskAllInputs:e.maskAllInputs,useCompression:!!t.eventBuffer&&"worker"===t.eventBuffer.type,networkDetailHasUrls:e.networkDetailAllowUrls.length>0,networkCaptureBodies:e.networkCaptureBodies,networkRequestHasHeaders:e.networkRequestHeaders.length>0,networkResponseHasHeaders:e.networkResponseHeaders.length>0}}}}(t),!1)}(t,i),t.session&&t.session.previousSessionId)return!0;if("buffer"===t.recordingMode&&t.session&&t.eventBuffer){var e=t.eventBuffer.getEarliestTimestamp();e&&(il("[Replay] Updating session start time to earliest event in buffer to "+new Date(e),t.getOptions()._experiments.traceInternals),t.session.started=e,t.getOptions().stickySession&&ml(t.session))}return"session"===t.recordingMode&&t.flush(),!0}))}else rl&&jo.warn("[Replay] Received replay event after session expired.")}}function pd(t,e,n,r){return i=function(t,e,n,r){var i=t.sdkProcessingMetadata&&t.sdkProcessingMetadata.dynamicSamplingContext;return m({event_id:t.event_id,sent_at:(new Date).toISOString()},e&&{sdk:e},!!n&&r&&{dsn:es(r)},i&&{trace:Xo(m({},i))})}(t,function(t){if(t&&t.sdk){var e=t.sdk;return{name:e.name,version:e.version}}}(t),r,n),void 0===(o=[[{type:"replay_event"},t],[{type:"replay_recording",length:"string"==typeof e?(new TextEncoder).encode(e).length:e.length},e]])&&(o=[]),[i,o];var i,o}function fd(t){var e,n=t.recordingData,r=t.headers,i=JSON.stringify(r)+"\n";if("string"==typeof n)e=""+i+n;else{var o=(new TextEncoder).encode(i);(e=new Uint8Array(o.length+n.length)).set(o),e.set(n,o.length)}return e}function hd(t){return md.apply(this,arguments)}function md(){return md=po(ht().mark((function t(e){var n,r,i,o,a,s,c,u,l,d,p;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=e.client,r=e.scope,i=e.replayId,o=e.event,a="object"!=typeof n._integrations||null===n._integrations||Array.isArray(n._integrations)?void 0:Object.keys(n._integrations),s={event_id:i,integrations:a},n.emit&&n.emit("preprocessEvent",o,s),t.next=6,xa(n.getOptions(),o,s,r,n,ma().getIsolationScope());case 6:if(c=t.sent){t.next=9;break}return t.abrupt("return",null);case 9:return c.platform=c.platform||"javascript",u=n.getSdkMetadata&&n.getSdkMetadata(),l=u&&u.sdk||{},d=l.name,p=l.version,c.sdk=m({},c.sdk,{name:d||"sentry.javascript.unknown",version:p||"0.0.0"}),t.abrupt("return",c);case 14:case"end":return t.stop()}}),t)}))),md.apply(this,arguments)}function vd(t){return gd.apply(this,arguments)}function gd(){return(gd=po(ht().mark((function t(e){var n,r,i,o,a,s,c,u,l,d,p,f,h,m,v,g,y,_,b,S,k;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.recordingData,r=e.replayId,i=e.segmentId,o=e.eventContext,a=e.timestamp,s=e.session,c=fd({recordingData:n,headers:{segment_id:i}}),u=o.urls,l=o.errorIds,d=o.traceIds,p=o.initialTimestamp,f=Ia(),h=Ca(),m=f&&f.getTransport(),v=f&&f.getDsn(),f&&m&&v&&s.sampled){t.next=9;break}return t.abrupt("return");case 9:return g={type:Os,replay_start_timestamp:p/1e3,timestamp:a/1e3,error_ids:l,trace_ids:d,urls:u,replay_id:r,segment_id:i,replay_type:s.sampled},t.next=12,hd({scope:h,client:f,replayId:r,event:g});case 12:if(y=t.sent){t.next=17;break}return f.recordDroppedEvent("event_processor","replay",g),il("An event processor returned `null`, will not send event."),t.abrupt("return");case 17:return delete y.sdkProcessingMetadata,_=pd(y,c,v,f.getOptions().tunnel),t.prev=19,t.next=22,m.send(_);case 22:b=t.sent,t.next=30;break;case 25:t.prev=25,t.t0=t.catch(19),S=new Error(Ms);try{S.cause=t.t0}catch(t){}throw S;case 30:if(b){t.next=32;break}return t.abrupt("return",b);case 32:if("number"!=typeof b.statusCode||!(b.statusCode<200||b.statusCode>=300)){t.next=34;break}throw new yd(b.statusCode);case 34:if(x=k=os({},b),"replay",void 0===(w=void 0)&&(w=Date.now()),!(function(t,e){return t[e]||t.all||0}(x,"replay")>w)){t.next=37;break}throw new _d(k);case 37:return t.abrupt("return",b);case 38:case"end":return t.stop()}var x,w}),t,null,[[19,25]])})))).apply(this,arguments)}var yd=function(t){function e(e){return t.call(this,"Transport returned status code "+e)||this}return Zn(e,t),e}(mo(Error)),_d=function(t){function e(e){var n;return(n=t.call(this,"Rate limit hit")||this).rateLimits=e,n}return Zn(e,t),e}(mo(Error));function bd(t,e){return Sd.apply(this,arguments)}function Sd(){return(Sd=po(ht().mark((function t(e,n){var r,i,o;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(void 0===n&&(n={count:0,interval:As}),r=e.recordingData,i=e.options,r.length){t.next=4;break}return t.abrupt("return");case 4:return t.prev=4,t.next=7,vd(e);case 7:return t.abrupt("return",!0);case 10:if(t.prev=10,t.t0=t.catch(4),!(t.t0 instanceof yd||t.t0 instanceof _d)){t.next=14;break}throw t.t0;case 14:if("Replays",a={_retryCount:n.count},ma().setContext("Replays",a),rl&&i._experiments&&i._experiments.captureExceptions&&Ta(t.t0),!(n.count>=Ds)){t.next=20;break}o=new Error(Ms+" - max retries exceeded");try{o.cause=t.t0}catch(t){}throw o;case 20:return n.interval*=++n.count,t.abrupt("return",new Promise((function(t,r){setTimeout(po(ht().mark((function i(){return ht().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return i.prev=0,i.next=3,bd(e,n);case 3:t(!0),i.next=9;break;case 6:i.prev=6,i.t0=i.catch(0),r(i.t0);case 9:case"end":return i.stop()}}),i,null,[[0,6]])}))),n.interval)})));case 22:case"end":return t.stop()}var a}),t,null,[[4,10]])})))).apply(this,arguments)}var kd="__THROTTLED";var xd=function(){function t(e){var n=this,r=e.options,i=e.recordingOptions;t.prototype.__init.call(this),t.prototype.__init2.call(this),t.prototype.__init3.call(this),t.prototype.__init4.call(this),t.prototype.__init5.call(this),t.prototype.__init6.call(this),this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:3e5,sessionIdleExpire:9e5},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=i,this._options=r,this._debouncedFlush=function(t,e,n){var r,i,o,a=n&&n.maxWait?Math.max(n.maxWait,e):0;function s(){return c(),r=t()}function c(){void 0!==i&&clearTimeout(i),void 0!==o&&clearTimeout(o),i=o=void 0}function u(){return i&&clearTimeout(i),i=setTimeout(s,e),a&&void 0===o&&(o=setTimeout(s,a)),r}return u.cancel=c,u.flush=function(){return void 0!==i||void 0!==o?s():r},u}((function(){return n._flush()}),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=function(t,e,n){var r=new Map,i=!1;return function(){var o=Math.floor(Date.now()/1e3);if(function(t){var e=t-n;r.forEach((function(t,n){n=e){var a=i;return i=!0,a?"__SKIPPED":kd}i=!1;var s=r.get(o)||0;return r.set(o,s+1),t.apply(void 0,arguments)}}((function(t,e){return function(t,e,n){return wl(t,e)?kl(t,e,n):Promise.resolve(null)}(n,t,e)}),300,5);var o=this.getOptions(),a=o.slowClickTimeout,s=o.slowClickIgnoreSelectors,c=a?{threshold:Math.min(3e3,a),timeout:a,scrollTimeout:300,ignoreSelector:s?s.join(","):""}:void 0;c&&(this.clickDetector=new Ju(this,c))}var e=t.prototype;return e.getContext=function(){return this._context},e.isEnabled=function(){return this._isEnabled},e.isPaused=function(){return this._isPaused},e.isRecordingCanvas=function(){return Boolean(this._canvas)},e.getOptions=function(){return this._options},e.initializeSampling=function(t){var e=this._options,n=e.errorSampleRate,r=e.sessionSampleRate;n<=0&&r<=0||(this._initializeSessionForSampling(t),this.session?!1!==this.session.sampled&&(this.recordingMode="buffer"===this.session.sampled&&0===this.session.segmentId?"buffer":"session",ol("[Replay] Starting replay in "+this.recordingMode+" mode",this._options._experiments.traceInternals),this._initializeRecording()):this._handleException(new Error("Unable to initialize and create session")))},e.start=function(){if(this._isEnabled&&"session"===this.recordingMode)throw new Error("Replay recording is already in progress");if(this._isEnabled&&"buffer"===this.recordingMode)throw new Error("Replay buffering is in progress, call `flush()` to save the replay");ol("[Replay] Starting replay in session mode",this._options._experiments.traceInternals),this._updateUserActivity();var t=bl({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire,traceInternals:this._options._experiments.traceInternals},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=t,this._initializeRecording()},e.startBuffering=function(){if(this._isEnabled)throw new Error("Replay recording is already in progress");ol("[Replay] Starting replay in buffer mode",this._options._experiments.traceInternals);var t=bl({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,traceInternals:this._options._experiments.traceInternals},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=t,this.recordingMode="buffer",this._initializeRecording()},e.startRecording=function(){try{var t=this._canvas;this._stopRecording=Lu(m({},this._recordingOptions,"buffer"===this.recordingMode&&{checkoutEveryNms:6e4},{emit:dd(this),onMutation:this._onMutationHandler},t?{recordCanvas:t.recordCanvas,getCanvasManager:t.getCanvasManager,sampling:t.sampling,dataURLOptions:t.dataURLOptions}:{}))}catch(t){this._handleException(t)}},e.stopRecording=function(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(t){return this._handleException(t),!1}},e.stop=function(){var t=po(ht().mark((function t(e){var n,r,i,o;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r=(n=void 0===e?{}:e).forceFlush,i=void 0!==r&&r,o=n.reason,this._isEnabled){t.next=3;break}return t.abrupt("return");case 3:if(this._isEnabled=!1,t.prev=4,il("[Replay] Stopping Replay"+(o?" triggered by "+o:""),this._options._experiments.traceInternals),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),!i){t.next=12;break}return t.next=12,this._flush({force:!0});case 12:this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,a=this,function(){if(pl())try{Cs.sessionStorage.removeItem(Rs)}catch(t){}}(),a.session=void 0,t.next=20;break;case 17:t.prev=17,t.t0=t.catch(4),this._handleException(t.t0);case 20:case"end":return t.stop()}var a}),t,this,[[4,17]])})));return function(e){return t.apply(this,arguments)}}(),e.pause=function(){this._isPaused||(this._isPaused=!0,this.stopRecording(),il("[Replay] Pausing replay",this._options._experiments.traceInternals))},e.resume=function(){this._isPaused&&this._checkSession()&&(this._isPaused=!1,this.startRecording(),il("[Replay] Resuming replay",this._options._experiments.traceInternals))},e.sendBufferedReplayOrFlush=function(){var t=po(ht().mark((function t(e){var n,r,i,o;return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=(void 0===e?{}:e).continueRecording,r=void 0===n||n,"session"!==this.recordingMode){t.next=3;break}return t.abrupt("return",this.flushImmediate());case 3:return i=Date.now(),il("[Replay] Converting buffer to session",this._options._experiments.traceInternals),t.next=7,this.flushImmediate();case 7:if(o=this.stopRecording(),r&&o){t.next=10;break}return t.abrupt("return");case 10:if("session"!==this.recordingMode){t.next=12;break}return t.abrupt("return");case 12:this.recordingMode="session",this.session&&(this._updateUserActivity(i),this._updateSessionActivity(i),this._maybeSaveSession()),this.startRecording();case 15:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e.addUpdate=function(t){var e=t();"buffer"!==this.recordingMode&&!0!==e&&this._debouncedFlush()},e.triggerUserActivity=function(){if(this._updateUserActivity(),this._stopRecording)this.checkAndHandleExpiredSession(),this._updateSessionActivity();else{if(!this._checkSession())return;this.resume()}},e.updateUserActivity=function(){this._updateUserActivity(),this._updateSessionActivity()},e.conditionalFlush=function(){return"buffer"===this.recordingMode?Promise.resolve():this.flushImmediate()},e.flush=function(){return this._debouncedFlush()},e.flushImmediate=function(){return this._debouncedFlush(),this._debouncedFlush.flush()},e.cancelFlush=function(){this._debouncedFlush.cancel()},e.getSessionId=function(){return this.session&&this.session.id},e.checkAndHandleExpiredSession=function(){if(!(this._lastActivity&&gl(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&"session"===this.session.sampled))return!!this._checkSession();this.pause()},e.setInitialState=function(){var t=""+Cs.location.pathname+Cs.location.hash+Cs.location.search,e=""+Cs.location.origin+t;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=e,this._context.initialTimestamp=Date.now(),this._context.urls.push(e)},e.throttledAddEvent=function(t,e){var n=this,r=this._throttledAddEvent(t,e);if(r===kd){var i=Gu({category:"replay.throttled"});this.addUpdate((function(){return!Sl(n,{type:5,timestamp:i.timestamp||0,data:{tag:"breadcrumb",payload:i,metric:!0}})}))}return r},e.getCurrentRoute=function(){var t=this.lastTransaction||Ca().getTransaction(),e=(t&&ra(t).data||{})["sentry.source"];if(t&&e&&["route","custom"].includes(e))return ra(t).description},e._initializeRecording=function(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=function(t){var e=t.useCompression,n=t.workerUrl;if(e&&window.Worker){var r=function(t){try{var e=t||("undefined"!=typeof __SENTRY_EXCLUDE_REPLAY_WORKER__&&__SENTRY_EXCLUDE_REPLAY_WORKER__?"":(r=new Blob(['var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==r||r<0)&&(r=0),(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},A=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},_=function(r,e){for(var i=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=x(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},x=function(t,n,r){return-1==t.s?Math.max(x(t.l,n,r+1),x(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,C)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B255){A(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;A(r,m,Q[et]),m+=R[et],et>3&&(A(r,m,rt>>5&8191),m+=i[et])}else A(r,m,N[rt]),m+=P[rt]}return A(r,m,N[256]),m+P[256]},U=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=U[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=C(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=A[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,a=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),s=a.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(a,n),O(a,s-8,r.d()),O(a,s-4,e),a}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),G="undefined"!=typeof TextEncoder&&new TextEncoder,H="undefined"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(r){for(var e=new t(n.length),i=0;i>1)),o=0,f=function(t){s[o++]=t};for(i=0;is.length){var h=new t(o+8+(a-i<<1));h.set(s),s=h}var l=n.charCodeAt(i);l<128||r?f(l):l<2048?(f(192|l>>6),f(128|63&l)):l>55295&&l<57344?(f(240|(l=65536+(1047552&l)|1023&n.charCodeAt(++i))>>18),f(128|l>>12&63),f(128|l>>6&63),f(128|63&l)):(f(224|l>>12),f(128|l>>6&63),f(128|63&l))}return b(s,0,o)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(let r=0,e=t.length;r{this._deflatedData.push(t)},this.stream=new J(((t,n)=>{this.deflate.push(t,n)})),this.stream.push("[")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener("message",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&"function"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});']),URL.createObjectURL(r)));if(!e)return;il("[Replay] Using compression worker"+(t?" from "+t:""));var n=new Worker(e);return new dl(n)}catch(t){il("[Replay] Failed to create compression worker")}var r}(n);if(r)return r}return il("[Replay] Using simple buffer"),new cl}({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.startRecording()},e._handleException=function(t){rl&&jo.error("[Replay]",t),rl&&this._options._experiments&&this._options._experiments.captureExceptions&&Ta(t)},e._initializeSessionForSampling=function(t){var e=this._options.errorSampleRate>0,n=bl({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,traceInternals:this._options._experiments.traceInternals,previousSessionId:t},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:e});this.session=n},e._checkSession=function(){if(!this.session)return!1;var t=this.session;return!_l(t,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})||(this._refreshSession(t),!1)},e._refreshSession=function(){var t=po(ht().mark((function t(e){return ht().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._isEnabled){t.next=2;break}return t.abrupt("return");case 2:return t.next=4,this.stop({reason:"refresh session"});case 4:this.initializeSampling(e.id);case 5:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e._addListeners=function(){try{Cs.document.addEventListener("visibilitychange",this._handleVisibilityChange),Cs.addEventListener("blur",this._handleWindowBlur),Cs.addEventListener("focus",this._handleWindowFocus),Cs.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(sd(this),this._hasInitializedCoreListeners=!0)}catch(t){this._handleException(t)}this._performanceCleanupCallback=nl(this)},e._removeListeners=function(){try{Cs.document.removeEventListener("visibilitychange",this._handleVisibilityChange),Cs.removeEventListener("blur",this._handleWindowBlur),Cs.removeEventListener("focus",this._handleWindowFocus),Cs.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(t){this._handleException(t)}},e.__init=function(){var t=this;this._handleVisibilityChange=function(){"visible"===Cs.document.visibilityState?t._doChangeToForegroundTasks():t._doChangeToBackgroundTasks()}},e.__init2=function(){var t=this;this._handleWindowBlur=function(){var e=Gu({category:"ui.blur"});t._doChangeToBackgroundTasks(e)}},e.__init3=function(){var t=this;this._handleWindowFocus=function(){var e=Gu({category:"ui.focus"});t._doChangeToForegroundTasks(e)}},e.__init4=function(){var t=this;this._handleKeyboardEvent=function(e){!function(t,e){if(t.isEnabled()){t.updateUserActivity();var n=function(t){var e=t.metaKey,n=t.shiftKey,r=t.ctrlKey,i=t.altKey,o=t.key,a=t.target;if(!a||function(t){return"INPUT"===t.tagName||"TEXTAREA"===t.tagName||t.isContentEditable}(a)||!o)return null;var s=e||r||i,c=1===o.length;if(!s&&c)return null;var u=Yo(a,{maxStringLength:200})||"";return Gu({category:"ui.keyDown",message:u,data:m({},Qu(a,u).data,{metaKey:e,shiftKey:n,ctrlKey:r,altKey:i,key:o})})}(e);n&&Uu(t,n)}}(t,e)}},e._doChangeToBackgroundTasks=function(t){this.session&&(yl(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})||(t&&this._createCustomBreadcrumb(t),this.conditionalFlush()))},e._doChangeToForegroundTasks=function(t){this.session&&(this.checkAndHandleExpiredSession()?t&&this._createCustomBreadcrumb(t):il("[Replay] Document has become active, but session has expired"))},e._updateUserActivity=function(t){void 0===t&&(t=Date.now()),this._lastActivity=t},e._updateSessionActivity=function(t){void 0===t&&(t=Date.now()),this.session&&(this.session.lastActivity=t,this._maybeSaveSession())},e._createCustomBreadcrumb=function(t){var e=this;this.addUpdate((function(){e.throttledAddEvent({type:Yc.Custom,timestamp:t.timestamp||0,data:{tag:"breadcrumb",payload:t}})}))},e._addPerformanceEntries=function(){var t,e=(t=this.performanceEntries,t.map(tl).filter(Boolean)).concat(this.replayPerformanceEntries);return this.performanceEntries=[],this.replayPerformanceEntries=[],Promise.all(Ol(this,e))},e._clearContext=function(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]},e._updateInitialTimestampFromEventBuffer=function(){var t=this.session,e=this.eventBuffer;if(t&&e&&!t.segmentId){var n=e.getEarliestTimestamp();n&&nthis._options.maxReplayDuration+3e4)){t.next=19;break}throw new Error("Session is too long, not sending replay");case 19:return r=this._popEventContext(),i=this.session.segmentId++,this._maybeSaveSession(),t.next=24,this.eventBuffer.finish();case 24:return o=t.sent,t.next=27,bd({replayId:e,recordingData:o,segmentId:i,eventContext:r,session:this.session,options:this.getOptions(),timestamp:n});case 27:t.next=35;break;case 29:t.prev=29,t.t0=t.catch(14),this._handleException(t.t0),this.stop({reason:"sendReplay"}),(a=Ia())&&a.recordDroppedEvent("send_error","replay");case 35:case"end":return t.stop()}}),t,this,[[14,29]])})));return function(){return t.apply(this,arguments)}}(),e.__init5=function(){var t=this;this._flush=function(){var e=po(ht().mark((function e(n){var r,i,o,a,s,c,u,l;return ht().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=(void 0===n?{}:n).force,i=void 0!==r&&r,t._isEnabled||i){e.next=3;break}return e.abrupt("return");case 3:if(t.checkAndHandleExpiredSession()){e.next=6;break}return rl&&jo.error("[Replay] Attempting to finish replay event after session expired."),e.abrupt("return");case 6:if(t.session){e.next=8;break}return e.abrupt("return");case 8:if(o=t.session.started,a=Date.now(),s=a-o,t._debouncedFlush.cancel(),c=st._options.maxReplayDuration+5e3,!c&&!u){e.next=18;break}return il("[Replay] Session duration ("+Math.floor(s/1e3)+"s) is too "+(c?"short":"long")+", not sending replay.",t._options._experiments.traceInternals),c&&t._debouncedFlush(),e.abrupt("return");case 18:if((l=t.eventBuffer)&&0===t.session.segmentId&&!l.hasCheckout&&il("[Replay] Flushing initial segment without checkout.",t._options._experiments.traceInternals),t._flushLock){e.next=26;break}return t._flushLock=t._runFlush(),e.next=24,t._flushLock;case 24:return t._flushLock=void 0,e.abrupt("return");case 26:return e.prev=26,e.next=29,t._flushLock;case 29:e.next=34;break;case 31:e.prev=31,e.t0=e.catch(26),rl&&jo.error(e.t0);case 34:return e.prev=34,t._debouncedFlush(),e.finish(34);case 37:case"end":return e.stop()}}),e,null,[[26,31,34,37]])})));return function(t){return e.apply(this,arguments)}}()},e._maybeSaveSession=function(){this.session&&this._options.stickySession&&ml(this.session)},e.__init6=function(){var t=this;this._onMutationHandler=function(e){var n=e.length,r=t._options.mutationLimit,i=r&&n>r;if(n>t._options.mutationBreadcrumbLimit||i){var o=Gu({category:"replay.mutations",data:{count:n,limit:i}});t._createCustomBreadcrumb(o)}return!i||(t.stop({reason:"mutationLimit",forceFlush:"session"===t.recordingMode}),!1)}},t}();function wd(t,e,n,r){var i="string"==typeof r?r.split(","):[],o=[].concat(t,i,e);return void 0!==n&&("string"==typeof n&&o.push("."+n),Lo((function(){console.warn("[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.")}))),o.join(",")}var Ed='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',Td=["content-length","content-type","accept"],Id=!1,Cd=function(){function t(e){var n=void 0===e?{}:e,r=n.flushMinDelay,i=void 0===r?5e3:r,o=n.flushMaxDelay,a=void 0===o?5500:o,s=n.minReplayDuration,c=void 0===s?4999:s,u=n.maxReplayDuration,l=void 0===u?js:u,d=n.stickySession,p=void 0===d||d,f=n.useCompression,h=void 0===f||f,v=n.workerUrl,g=n._experiments,y=void 0===g?{}:g,_=n.sessionSampleRate,b=n.errorSampleRate,S=n.maskAllText,k=void 0===S||S,x=n.maskAllInputs,w=void 0===x||x,E=n.blockAllMedia,T=void 0===E||E,I=n.mutationBreadcrumbLimit,C=void 0===I?750:I,R=n.mutationLimit,O=void 0===R?1e4:R,M=n.slowClickTimeout,A=void 0===M?7e3:M,D=n.slowClickIgnoreSelectors,N=void 0===D?[]:D,L=n.networkDetailAllowUrls,P=void 0===L?[]:L,j=n.networkDetailDenyUrls,F=void 0===j?[]:j,U=n.networkCaptureBodies,B=void 0===U||U,H=n.networkRequestHeaders,z=void 0===H?[]:H,q=n.networkResponseHeaders,W=void 0===q?[]:q,Y=n.mask,J=void 0===Y?[]:Y,V=n.maskAttributes,K=void 0===V?["title","placeholder"]:V,G=n.unmask,$=void 0===G?[]:G,X=n.block,Q=void 0===X?[]:X,Z=n.unblock,tt=void 0===Z?[]:Z,et=n.ignore,nt=void 0===et?[]:et,rt=n.maskFn,it=n.beforeAddRecordingEvent,ot=n.beforeErrorSampling,at=n.blockClass,st=n.blockSelector,ct=n.maskInputOptions,ut=n.maskTextClass,lt=n.maskTextSelector,dt=n.ignoreClass;this.name=t.id;var pt=function(t){var e=t.unmask,n=t.block,r=t.unblock,i=t.ignore,o=t.blockClass,a=t.blockSelector,s=t.maskTextClass,c=t.ignoreClass,u={maskTextSelector:wd(t.mask,[".sentry-mask","[data-sentry-mask]"],s,t.maskTextSelector),unmaskTextSelector:wd(e,[".sentry-unmask","[data-sentry-unmask]"]),blockSelector:wd(n,[".sentry-block","[data-sentry-block]"].concat(['base[href="/"]']),o,a),unblockSelector:wd(r,[".sentry-unblock","[data-sentry-unblock]"]),ignoreSelector:wd(i,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'],c)};return o instanceof RegExp&&(u.blockClass=o),s instanceof RegExp&&(u.maskTextClass=s),u}({mask:J,unmask:$,block:Q,unblock:tt,ignore:nt,blockClass:at,blockSelector:st,maskTextClass:ut,maskTextSelector:lt,ignoreClass:dt});if(this._recordingOptions=m({maskAllInputs:w,maskAllText:k,maskInputOptions:m({},ct||{},{password:!0}),maskTextFn:rt,maskInputFn:rt,maskAttributeFn:function(t,e,n){return function(t){var e=t.el,n=t.key,r=t.maskAttributes,i=t.privacyOptions,o=t.value;return t.maskAllText?i.unmaskTextSelector&&e.matches(i.unmaskTextSelector)?o:r.includes(n)||"value"===n&&"INPUT"===e.tagName&&["submit","button"].includes(e.getAttribute("type")||"")?o.replace(/[\S]/g,"*"):o:o}({maskAttributes:K,maskAllText:k,privacyOptions:pt,key:t,value:e,el:n})}},pt,{slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:function(t){try{t.__rrweb__=!0}catch(t){}}}),this._initialOptions={flushMinDelay:i,flushMaxDelay:a,minReplayDuration:Math.min(c,15e3),maxReplayDuration:Math.min(l,js),stickySession:p,sessionSampleRate:_,errorSampleRate:b,useCompression:h,workerUrl:v,blockAllMedia:T,maskAllInputs:w,maskAllText:k,mutationBreadcrumbLimit:C,mutationLimit:O,slowClickTimeout:A,slowClickIgnoreSelectors:N,networkDetailAllowUrls:P,networkDetailDenyUrls:F,networkCaptureBodies:B,networkRequestHeaders:Rd(z),networkResponseHeaders:Rd(W),beforeAddRecordingEvent:it,beforeErrorSampling:ot,_experiments:y},"number"==typeof _&&(console.warn("[Replay] You are passing `sessionSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysSessionSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: "+_+" })"),this._initialOptions.sessionSampleRate=_),"number"==typeof b&&(console.warn("[Replay] You are passing `errorSampleRate` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure `replaysOnErrorSampleRate` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: "+b+" })"),this._initialOptions.errorSampleRate=b),this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?this._recordingOptions.blockSelector+","+Ed:Ed),this._isInitialized&&ss())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}t.__initStatic=function(){this.id="Replay"};var e=t.prototype;return e.setupOnce=function(){var t=this;ss()&&(this._setup(),setTimeout((function(){return t._initialize()})))},e.start=function(){this._replay&&this._replay.start()},e.startBuffering=function(){this._replay&&this._replay.startBuffering()},e.stop=function(){return this._replay?this._replay.stop({forceFlush:"session"===this._replay.recordingMode}):Promise.resolve()},e.flush=function(t){return this._replay&&this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(t):Promise.resolve()},e.getReplayId=function(){if(this._replay&&this._replay.isEnabled())return this._replay.getSessionId()},e._initialize=function(){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(),this._replay.initializeSampling())},e._setup=function(){var t=function(t){var e=Ia(),n=e&&e.getOptions(),r=m({sessionSampleRate:0,errorSampleRate:0},Xo(t));return n?(null==t.sessionSampleRate&&null==t.errorSampleRate&&null==n.replaysSessionSampleRate&&null==n.replaysOnErrorSampleRate&&Lo((function(){console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")})),"number"==typeof n.replaysSessionSampleRate&&(r.sessionSampleRate=n.replaysSessionSampleRate),"number"==typeof n.replaysOnErrorSampleRate&&(r.errorSampleRate=n.replaysOnErrorSampleRate),r):(Lo((function(){console.warn("SDK client is not available.")})),r)}(this._initialOptions);this._replay=new xd({options:t,recordingOptions:this._recordingOptions})},e._maybeLoadFromReplayCanvasIntegration=function(){try{var t=Ia().getIntegrationByName("ReplayCanvas");if(!t)return;this._replay._canvas=t.getOptions()}catch(t){}},nr(t,[{key:"_isInitialized",get:function(){return Id},set:function(t){Id=t}}]),t}();function Rd(t){return[].concat(Td,t.map((function(t){return t.toLowerCase()})))}Cd.__initStatic();var Od=function(t){function e(n,r){var i;return void 0===r&&(r="warn"),(i=t.call(this,n)||this).message=n,i.name=(this instanceof e?this.constructor:void 0).prototype.constructor.name,Object.setPrototypeOf(Xn(i),(this instanceof e?this.constructor:void 0).prototype),i.logLevel=r,i}return Zn(e,t),e}(mo(Error)),Md="7";function Ad(t){var e=t.protocol?t.protocol+":":"",n=t.port?":"+t.port:"";return e+"//"+t.host+n+(t.path?"/"+t.path:"")+"/api/"}function Dd(t,e){void 0===e&&(e={});var n="string"==typeof e?e:e.tunnel,r="string"!=typeof e&&e._metadata?e._metadata.sdk:void 0;return n||function(t){return""+Ad(t)+t.projectId+"/envelope/"}(t)+"?"+function(t,e){return n=m({sentry_key:t.publicKey,sentry_version:Md},e&&{sentry_client:e.name+"/"+e.version}),Object.keys(n).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])})).join("&");var n}(t,r)}function Nd(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(t);!(e=r()).done;){var i=e.value,o=Object.entries(i.tags),a=o.length>0?"|#"+o.map((function(t){return t[0]+":"+t[1]})).join(","):"";n+=i.name+"@"+i.unit+":"+i.metric+"|"+i.metricType+a+"|T"+i.timestamp+"\n"}return n}(t);return[{type:"statsd",length:e.length},e]}(t);return Ci(i,[o])}function Pd(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return jd(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jd(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function jd(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?" ("+r+" times)":"")),this._outcomes[i]=(this._outcomes[i]||0)+r}},e.captureAggregateMetrics=function(t){tt&&h.log("Flushing aggregated metrics, number of metrics: "+t.length);var e=Ld(t,this._dsn,this._options._metadata,this._options.tunnel);this._sendEnvelope(e)},e.on=function(t,e){this._hooks[t]||(this._hooks[t]=[]),this._hooks[t].push(e)},e.emit=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r=t&&(clearInterval(i),n(!1)))}),1)}))},e._isEnabled=function(){return!1!==this.getOptions().enabled&&void 0!==this._transport},e._prepareEvent=function(t,e,n,r){var i=this;void 0===r&&(r=se());var o=this.getOptions(),s=Object.keys(this._integrations);return!e.integrations&&s.length>0&&(e.integrations=s),this.emit("preprocessEvent",t,e),function(t,e,n,r,i,o){var s=t.normalizeDepth,c=void 0===s?3:s,u=t.normalizeMaxBreadth,l=void 0===u?1e3:u,d=m({},e,{event_id:e.event_id||n.event_id||V(),timestamp:e.timestamp||ct()}),p=n.integrations||t.integrations.map((function(t){return t.name}));!function(t,e){var n=e.environment,r=e.release,i=e.dist,o=e.maxValueLength,a=void 0===o?250:o;"environment"in t||(t.environment="environment"in e?n:dt),void 0===t.release&&void 0!==r&&(t.release=r),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=L(t.message,a));var s=t.exception&&t.exception.values&&t.exception.values[0];s&&s.value&&(s.value=L(s.value,a));var c=t.request;c&&c.url&&(c.url=L(c.url,a))}(d,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[].concat(t.sdk.integrations||[],e))}(d,p),void 0===e.type&&function(t,e){var n,r=a._sentryDebugIds;if(r){var i=Bt.get(e);i?n=i:(n=new Map,Bt.set(e,n));var o=Object.keys(r).reduce((function(t,i){var o,a=n.get(i);a?o=a:(o=e(i),n.set(i,o));for(var s=o.length-1;s>=0;s--){var c=o[s];if(c.filename){t[c.filename]=r[i];break}}return t}),{});try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.filename&&(t.debug_id=o[t.filename])}))}))}catch(t){}}}(d,t.stackParser);var f=function(t,e){if(!e)return t;var n=t?t.clone():new Zt;return n.update(e),n}(r,n.captureContext);n.mechanism&&X(d,n.mechanism);var h=i&&i.getEventProcessors?i.getEventProcessors():[],v=(Qt||(Qt=new Zt),Qt).getScopeData();o&&$t(v,o.getScopeData()),f&&$t(v,f.getScopeData());var g=[].concat(n.attachments||[],v.attachments);return g.length&&(n.attachments=g),Gt(d,v),at([].concat(h,it(),v.eventProcessors),d,n).then((function(t){return t&&function(t){var e={};try{t.exception.values.forEach((function(t){t.stacktrace.frames.forEach((function(t){t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0!==Object.keys(e).length){t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];var n=t.debug_meta.images;Object.keys(e).forEach((function(t){n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}}(t),"number"==typeof c&&c>0?function(t,e,n){if(!t)return null;var r=m({},t,t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return m({},t,t.data&&{data:St(t.data,e,n)})}))},t.user&&{user:St(t.user,e,n)},t.contexts&&{contexts:St(t.contexts,e,n)},t.extra&&{extra:St(t.extra,e,n)});return t.contexts&&t.contexts.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=St(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map((function(t){var r=Ft(t).data;return r&&(t.data=St(r,e,n)),t}))),r}(t,c,l):t}))}(o,t,e,n,this,r).then((function(t){if(null===t)return t;var e=m({},r.getPropagationContext(),n?n.getPropagationContext():void 0);if((!t.contexts||!t.contexts.trace)&&e){var o=e.traceId,a=e.spanId,s=e.parentSpanId,c=e.dsc;t.contexts=m({trace:{trace_id:o,span_id:a,parent_span_id:s}},t.contexts);var u=c||Vt(o,i,n);t.sdkProcessingMetadata=m({dynamicSamplingContext:u},t.sdkProcessingMetadata)}return t}))},e._captureEvent=function(t,e,n){return void 0===e&&(e={}),this._processEvent(t,e,n).then((function(t){return t.event_id}),(function(t){if(tt){var e=t;"log"===e.logLevel?h.log(e.message):h.warn(e)}}))},e._processEvent=function(t,e,n){var r=this,i=this.getOptions(),o=i.sampleRate,a=Hd(t),s=Bd(t),c=t.type||"error",u="before send for type `"+c+"`";if(s&&"number"==typeof o&&Math.random()>o)return this.recordDroppedEvent("sample_rate","error",t),nt(new Od("Discarding event because it's not included in the random sample (sampling rate = "+o+")","log"));var l="replay_event"===c?"replay":c,d=(t.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(t,e,n,d).then((function(n){if(null===n)throw r.recordDroppedEvent("event_processor",l,t),new Od("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;var o=function(t,e,n){var r=t.beforeSend,i=t.beforeSendTransaction;if(Bd(e)&&r)return r(e,n);if(Hd(e)&&i){if(e.spans){var o=e.spans.length;e.sdkProcessingMetadata=m({},e.sdkProcessingMetadata,{spanCountBeforeProcessing:o})}return i(e,n)}return e}(i,n,e);return function(t,e){var n=e+" must return `null` or a valid event.";if(T(t))return t.then((function(t){if(!w(t)&&null!==t)throw new Od(n);return t}),(function(t){throw new Od(e+" rejected with "+t)}));if(!w(t)&&null!==t)throw new Od(n);return t}(o,u)})).then((function(i){if(null===i){if(r.recordDroppedEvent("before_send",l,t),a){var o=1+(t.spans||[]).length;r.recordDroppedEvent("before_send","span",o)}throw new Od(u+" returned `null`, will not send event.","log")}var s=n&&n.getSession();if(!a&&s&&r._updateSessionFromEvent(s,i),a){var c=(i.sdkProcessingMetadata&&i.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);c>0&&r.recordDroppedEvent("before_send","span",c)}var d=i.transaction_info;return a&&d&&i.transaction!==t.transaction&&(i.transaction_info=m({},d,{source:"custom"})),r.sendEvent(i,e),i})).then(null,(function(t){if(t instanceof Od)throw t;throw r.captureException(t,{data:{__sentry__:!0},originalException:t}),new Od("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},e._process=function(t){var e=this;this._numProcessing++,t.then((function(t){return e._numProcessing--,t}),(function(t){return e._numProcessing--,t}))},e._sendEnvelope=function(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)return this._transport.send(t).then(null,(function(t){tt&&h.error("Error while sending event:",t)}));tt&&h.error("Transport disabled")},e._clearOutcomes=function(){var t=this._outcomes;return this._outcomes={},Object.keys(t).map((function(e){var n=e.split(":");return{reason:n[0],category:n[1],quantity:t[e]}}))},t}();function Bd(t){return void 0===t.type}function Hd(t){return"transaction"===t.type}var zd=function(t){function e(e){var n;return function(t,e,n,r){void 0===n&&(n=[e]),void 0===r&&(r="npm");var i=t._metadata||{};i.sdk||(i.sdk={name:"sentry.javascript."+e,packages:n.map((function(t){return{name:r+":@sentry/"+t,version:ee}})),version:ee}),t._metadata=i}(e,"browser",["browser"],Te.SENTRY_SDK_SOURCE||"npm"),n=t.call(this,e)||this,e.sendClientReports&&Te.document&&Te.document.addEventListener("visibilitychange",(function(){"hidden"===Te.document.visibilityState&&n._flushOutcomes()})),n}Zn(e,t);var n=e.prototype;return n.eventFromException=function(t,e){return function(t,e,n,r){var i=en(t,e,n&&n.syntheticException||void 0,r);return X(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),et(i)}(this._options.stackParser,t,e,this._options.attachStacktrace)},n.eventFromMessage=function(t,e,n){return void 0===e&&(e="info"),function(t,e,n,r,i){void 0===n&&(n="info");var o=nn(t,e,r&&r.syntheticException||void 0,i);return o.level=n,r&&r.event_id&&(o.event_id=r.event_id),et(o)}(this._options.stackParser,t,e,n,this._options.attachStacktrace)},n.captureUserFeedback=function(t){if(this._isEnabled()){var e=function(t,e){var n=e.metadata,r=e.tunnel,i=e.dsn,o=m({event_id:t.event_id,sent_at:(new Date).toISOString()},n&&n.sdk&&{sdk:{name:n.sdk.name,version:n.sdk.version}},!!r&&!!i&&{dsn:xi(i)}),a=function(t){return[{type:"user_report"},t]}(t);return Ci(o,[a])}(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this._sendEnvelope(e)}},n._prepareEvent=function(e,n,r){return e.platform=e.platform||"javascript",t.prototype._prepareEvent.call(this,e,n,r)},n._flushOutcomes=function(){var t=this._clearOutcomes();if(0!==t.length&&this._dsn){var e,n,r=(e=t,Ci((n=this._options.tunnel&&xi(this._dsn))?{dsn:n}:{},[[{type:"client_report"},{timestamp:ct(),discarded_events:e}]]));this._sendEnvelope(r)}},e}(Ud);function qd(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Wd(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Wd(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Wd(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&n(!1)}),t);e.forEach((function(t){et(t).then((function(){--i||(clearTimeout(o),n(!0))}),r)}))}))}}}(t.bufferSize||Jd));var r={};function i(i){var o=[];if(Ri(i,(function(e,n){var i=Ni(n);if(function(t,e,n){return void 0===n&&(n=Date.now()),function(t,e){return t[e]||t.all||0}(t,e)>n}(r,i)){var a=Kd(e,n);t.recordDroppedEvent("ratelimit_backoff",i,a)}else o.push(e)})),0===o.length)return et();var a=Ci(i[0],o),s=function(e){Ri(a,(function(n,r){var i=Kd(n,r);t.recordDroppedEvent(e,Ni(r),i)}))};return n.add((function(){return e({body:Mi(a,t.textEncoder)}).then((function(t){return void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&tt&&h.warn("Sentry responded with status code "+t.statusCode+" to sent event."),r=function(t,e,n){var r=e.statusCode,i=e.headers;void 0===n&&(n=Date.now());var o=m({},t),a=i&&i["x-sentry-rate-limits"],s=i&&i["retry-after"];if(a)for(var c,u=qd(a.trim().split(","));!(c=u()).done;){var l=c.value.split(":",5),d=l[0],p=l[1],f=l[4],h=parseInt(d,10),v=1e3*(isNaN(h)?60:h);if(p)for(var g,y=qd(p.split(";"));!(g=y()).done;){var _=g.value;"metric_bucket"===_&&f&&!f.split(";").includes("custom")||(o[_]=n+v)}else o.all=n+v}else s?o.all=n+function(t,e){void 0===e&&(e=Date.now());var n=parseInt(""+t,10);if(!isNaN(n))return 1e3*n;var r=Date.parse(""+t);return isNaN(r)?Yd:r-e}(s,n):429===r&&(o.all=n+6e4);return o}(r,t),t}),(function(t){throw s("network_error"),t}))})).then((function(t){return t}),(function(t){if(t instanceof Od)return tt&&h.error("Skipped sending event because buffer is full."),s("queue_overflow"),et();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:function(t){return n.drain(t)}}}function Kd(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}var Gd=void 0;function $d(t,e){void 0===e&&(e=function(){if(Gd)return Gd;if(wn(Te.fetch))return Gd=Te.fetch.bind(Te);var t=Te.document,e=Te.fetch;if(t&&"function"==typeof t.createElement)try{var n=t.createElement("iframe");n.hidden=!0,t.head.appendChild(n);var r=n.contentWindow;r&&r.fetch&&(e=r.fetch),t.head.removeChild(n)}catch(t){}return Gd=e.bind(Te)}());var n=0,r=0;return Vd(t,(function(i){var o=i.body.length;n+=o,r++;var a=m({body:i.body,method:"POST",referrerPolicy:"origin",headers:t.headers,keepalive:n<=6e4&&r<15},t.fetchOptions);try{return e(t.url,a).then((function(t){return n-=o,r--,{statusCode:t.status,headers:{"x-sentry-rate-limits":t.headers.get("X-Sentry-Rate-Limits"),"retry-after":t.headers.get("Retry-After")}}}))}catch(t){return Gd=void 0,n-=o,r--,nt(t)}}))}var Xd="?";function Qd(t,e,n,r){var i={filename:t,function:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}var Zd=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,tp=/\((\S*)(?::(\d+))(?::(\d+))\)/,ep=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,np=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,rp=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ip=function(){for(var t=arguments.length,e=new Array(t),n=0;n1024)){var s=gt.test(a)?a.replace(gt,"$1"):a;if(!s.match(/\S*Error: /)){for(var c,u=mt(r);!(c=u()).done;){var l=(0,c.value)(s);if(l){n.push(l);break}}if(n.length>=50)break}}}return function(t){if(!t.length)return[];var e=Array.from(t);return/sentryWrapped/.test(e[e.length-1].function||"")&&e.pop(),e.reverse(),yt.test(e[e.length-1].function||"")&&(e.pop(),yt.test(e[e.length-1].function||"")&&e.pop()),e.slice(0,50).map((function(t){return m({},t,{filename:t.filename||e[e.length-1].filename,function:t.function||"?"})}))}(n)}}.apply(void 0,[[30,function(t){var e=Zd.exec(t);if(e){if(e[2]&&0===e[2].indexOf("eval")){var n=tp.exec(e[2]);n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3])}var r=op(e[1]||Xd,e[2]),i=r[0];return Qd(r[1],i,e[3]?+e[3]:void 0,e[4]?+e[4]:void 0)}}],[50,function(t){var e=ep.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=np.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],i=e[1]||Xd,o=op(i,r);return i=o[0],Qd(r=o[1],i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}],[40,function(t){var e=rp.exec(t);return e?Qd(e[2],e[1]||Xd,+e[3],e[4]?+e[4]:void 0):void 0}]]),op=function(t,e){var n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:Xd,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},ap="Dedupe",sp=function(){var t;return{name:ap,setupOnce:function(){},processEvent:function(e){if(e.type)return e;try{if(function(t,e){return!!e&&(!!function(t,e){var n=t.message,r=e.message;return!(!n&&!r)&&(!(n&&!r||!n&&r)&&(n===r&&(!!up(t,e)&&!!cp(t,e))))}(t,e)||!!function(t,e){var n=lp(e),r=lp(t);return!(!n||!r)&&(n.type===r.type&&n.value===r.value&&(!!up(t,e)&&!!cp(t,e)))}(t,e))}(e,t))return null}catch(t){}return t=e}}};function cp(t,e){var n=dp(t),r=dp(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(var i=0;i>t/4).toString(16)}))}function bp(){return Date.now()/1e3}var Sp=function(){var t=gp.performance;if(!t||!t.now)return bp;var e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return function(){return(n+t.now())/1e3}}(),kp=(function(){var t=gp.performance;if(t&&t.now){var e=36e5,n=t.now(),r=Date.now(),i=t.timeOrigin?Math.abs(t.timeOrigin+n-r):e,o=i=0?n:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function Np(t){return t.transaction}var Lp=1;function Pp(t){var e=t.spanContext(),n=e.spanId,r=e.traceId,i=jp(t);return Mp({data:i.data,op:i.op,parent_span_id:i.parent_span_id,span_id:n,status:i.status,tags:i.tags,trace_id:r,origin:i.origin})}function jp(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function Fp(t){var e=$p();if(!e)return{};var n=function(t,e,n){var r=e.getOptions(),i=(e.getDsn()||{}).publicKey,o=(n&&n.getUser()||{}).segment,a=Mp({environment:r.environment||Cp,release:r.release,user_segment:o,public_key:i,trace_id:t});return e.emit&&e.emit("createDsc",a),a}(jp(t).trace_id||"",e,Yp().getScope()),r=Np(t);if(!r)return n;var i=r&&r._frozenDynamicSamplingContext;if(i)return i;var o=r.metadata,a=o.sampleRate,s=o.source;null!=a&&(n.sample_rate=""+a);var c=jp(r);return s&&"url"!==s&&(n.transaction=c.description),n.sampled=String(function(t){var e=t.spanContext().traceFlags;return Boolean(e&Lp)}(r)),e.emit&&e.emit("createDsc",n),n}var Up=function(){function t(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=Bp()}t.clone=function(e){return e?e.clone():new t};var e=t.prototype;return e.clone=function(){var e=new t;return e._breadcrumbs=[].concat(this._breadcrumbs),e._tags=m({},this._tags),e._extra=m({},this._extra),e._contexts=m({},this._contexts),e._user=this._user,e._level=this._level,e._span=this._span,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[].concat(this._eventProcessors),e._requestSession=this._requestSession,e._attachments=[].concat(this._attachments),e._sdkProcessingMetadata=m({},this._sdkProcessingMetadata),e._propagationContext=m({},this._propagationContext),e._client=this._client,e},e.setClient=function(t){this._client=t},e.getClient=function(){return this._client},e.addScopeListener=function(t){this._scopeListeners.push(t)},e.addEventProcessor=function(t){return this._eventProcessors.push(t),this},e.setUser=function(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&Dp(this._session,{user:t}),this._notifyScopeListeners(),this},e.getUser=function(){return this._user},e.getRequestSession=function(){return this._requestSession},e.setRequestSession=function(t){return this._requestSession=t,this},e.setTags=function(t){return this._tags=m({},this._tags,t),this._notifyScopeListeners(),this},e.setTag=function(t,e){var n;return this._tags=m({},this._tags,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setExtras=function(t){return this._extra=m({},this._extra,t),this._notifyScopeListeners(),this},e.setExtra=function(t,e){var n;return this._extra=m({},this._extra,((n={})[t]=e,n)),this._notifyScopeListeners(),this},e.setFingerprint=function(t){return this._fingerprint=t,this._notifyScopeListeners(),this},e.setLevel=function(t){return this._level=t,this._notifyScopeListeners(),this},e.setTransactionName=function(t){return this._transactionName=t,this._notifyScopeListeners(),this},e.setContext=function(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this},e.setSpan=function(t){return this._span=t,this._notifyScopeListeners(),this},e.getSpan=function(){return this._span},e.getTransaction=function(){var t=this._span;return t&&t.transaction},e.setSession=function(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this},e.getSession=function(){return this._session},e.update=function(e){if(!e)return this;var n="function"==typeof e?e(this):e;if(n instanceof t){var r=n.getScopeData();this._tags=m({},this._tags,r.tags),this._extra=m({},this._extra,r.extra),this._contexts=m({},this._contexts,r.contexts),r.user&&Object.keys(r.user).length&&(this._user=r.user),r.level&&(this._level=r.level),r.fingerprint.length&&(this._fingerprint=r.fingerprint),n.getRequestSession()&&(this._requestSession=n.getRequestSession()),r.propagationContext&&(this._propagationContext=r.propagationContext)}else if(hp(n)){var i=e;this._tags=m({},this._tags,i.tags),this._extra=m({},this._extra,i.extra),this._contexts=m({},this._contexts,i.contexts),i.user&&(this._user=i.user),i.level&&(this._level=i.level),i.fingerprint&&(this._fingerprint=i.fingerprint),i.requestSession&&(this._requestSession=i.requestSession),i.propagationContext&&(this._propagationContext=i.propagationContext)}return this},e.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=Bp(),this},e.addBreadcrumb=function(t,e){var n="number"==typeof e?e:100;if(n<=0)return this;var r=m({timestamp:bp()},t),i=this._breadcrumbs;return i.push(r),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this},e.getLastBreadcrumb=function(){return this._breadcrumbs[this._breadcrumbs.length-1]},e.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},e.addAttachment=function(t){return this._attachments.push(t),this},e.getAttachments=function(){return this.getScopeData().attachments},e.clearAttachments=function(){return this._attachments=[],this},e.getScopeData=function(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:this._span}},e.applyToEvent=function(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=[]),function(t,e){var n=e.fingerprint,r=e.span,i=e.breadcrumbs,o=e.sdkProcessingMetadata;!function(t,e){var n=e.extra,r=e.tags,i=e.user,o=e.contexts,a=e.level,s=e.transactionName,c=Mp(n);c&&Object.keys(c).length&&(t.extra=m({},c,t.extra));var u=Mp(r);u&&Object.keys(u).length&&(t.tags=m({},u,t.tags));var l=Mp(i);l&&Object.keys(l).length&&(t.user=m({},l,t.user));var d=Mp(o);d&&Object.keys(d).length&&(t.contexts=m({},d,t.contexts)),a&&(t.level=a),s&&(t.transaction=s)}(t,e),r&&function(t,e){t.contexts=m({trace:Pp(e)},t.contexts);var n=Np(e);if(n){t.sdkProcessingMetadata=m({dynamicSamplingContext:Fp(e)},t.sdkProcessingMetadata);var r=jp(n).description;r&&(t.tags=m({transaction:r},t.tags))}}(t,r),function(t,e){var n;t.fingerprint=t.fingerprint?(n=t.fingerprint,Array.isArray(n)?n:[n]):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){var n=[].concat(t.breadcrumbs||[],e);t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata=m({},t.sdkProcessingMetadata,e)}(t,o)}(t,this.getScopeData()),Op([].concat(n,yp("globalEventProcessors",(function(){return[]})),this._eventProcessors),t,e)},e.setSDKProcessingMetadata=function(t){return this._sdkProcessingMetadata=m({},this._sdkProcessingMetadata,t),this},e.setPropagationContext=function(t){return this._propagationContext=t,this},e.getPropagationContext=function(){return this._propagationContext},e.captureException=function(t,e){var n=e&&e.event_id?e.event_id:_p();if(!this._client)return Ip.warn("No client configured on scope - will not capture exception!"),n;var r=new Error("Sentry syntheticException");return this._client.captureException(t,m({originalException:t,syntheticException:r},e,{event_id:n}),this),n},e.captureMessage=function(t,e,n){var r=n&&n.event_id?n.event_id:_p();if(!this._client)return Ip.warn("No client configured on scope - will not capture message!"),r;var i=new Error(t);return this._client.captureMessage(t,e,m({originalException:t,syntheticException:i},n,{event_id:r}),this),r},e.captureEvent=function(t,e){var n=e&&e.event_id?e.event_id:_p();return this._client?(this._client.captureEvent(t,m({},e,{event_id:n}),this),n):(Ip.warn("No client configured on scope - will not capture event!"),n)},e._notifyScopeListeners=function(){var t=this;this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((function(e){e(t)})),this._notifyingListeners=!1)},t}();function Bp(){return{traceId:_p(),spanId:_p().substring(16)}}var Hp=parseFloat("7.119.1"),zp=function(){function t(t,e,n,r){var i,o;void 0===r&&(r=Hp),this._version=r,e?i=e:(i=new Up).setClient(t),n?o=n:(o=new Up).setClient(t),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}var e=t.prototype;return e.isOlderThan=function(t){return this._version1?n-1:0),i=1;it.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(r=i()).done;){var o=r.value;try{o(e)}catch(e){kp&&Ip.error("Error while triggering instrumentation handler.\nType: "+t+"\nName: "+Qp(o)+"\nError:",e)}}}("console",{args:n,level:t});var i=wp[t];i&&i.apply(gp.console,n)}}))}))}var rf=["fatal","error","warning","log","info","debug"];function of(t){return"warn"===t?"warning":rf.includes(t)?t:"log"}function af(t,e){if(!Array.isArray(t))return"";for(var n,r=[],i=0;i(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","import { dynamicRequire, isNodeEnv } from './node';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance(): Performance | undefined {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = (module) => {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: () => {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n","import { isRegExp, isString } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","import type { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*healthcheck.*$/,\n /^.*healthy.*$/,\n /^.*live.*$/,\n /^.*ready.*$/,\n /^.*heartbeat.*$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcess: EventProcessor = (event: Event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n}\n\n/** JSDoc */\nexport function _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nexport function _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n __DEBUG_BUILD__ &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n const { values } = event.exception;\n try {\n const { type = '', value = '' } = (values && values[values.length - 1]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n }\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: { [key: string]: unknown }, name: string, value: unknown): void {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(value: V):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { node } from './node-stack-trace';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = stack.slice(0, STACKTRACE_FRAME_LIMIT);\n\n const lastFrameFunction = localStack[localStack.length - 1].function;\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (lastFrameFunction && /sentryWrapped/.test(lastFrameFunction)) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n const firstFrameFunction = localStack[localStack.length - 1].function;\n // 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)\n if (firstFrameFunction && /captureMessage|captureException/.test(firstFrameFunction)) {\n localStack.pop();\n }\n\n return localStack.map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n const getRandomByte =\n crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","import type { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalSingleton, GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] as const;\nexport type ConsoleLevel = (typeof CONSOLE_LEVELS)[number];\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record<(typeof CONSOLE_LEVELS)[number], LoggerMethod>;\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const originalConsole = GLOBAL_OBJ.console as Console & Record;\n const wrappedLevels: Partial = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] as WrappedFunction).__sentry_original__;\n if (level in originalConsole && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] as LoggerConsoleMethods[typeof level];\n originalConsole[level] = originalWrappedFunc as Console[typeof level];\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level as (typeof CONSOLE_LEVELS)[number]];\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if (__DEBUG_BUILD__) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nlet logger: Logger;\nif (__DEBUG_BUILD__) {\n logger = getGlobalSingleton('logger', makeLogger);\n} else {\n logger = makeLogger();\n}\n\nexport { logger };\n","export const DEFAULT_ENVIRONMENT = 'production';\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States = States.PENDING;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]> = [];\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport {\n arrayify,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isPlainObject,\n isThenable,\n logger,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { updateSession } from './session';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /** Transaction Name */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n this._user = user || {};\n if (this._session) {\n updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as (scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getAttachments(): Attachment[] {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n public applyToEvent(event: Event, hint: EventHint = {}): PromiseLike {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transaction = this._span.transaction;\n if (transaction) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: transaction.getDynamicSamplingContext(),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n __DEBUG_BUILD__ &&\n processor.id &&\n result === null &&\n logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalSingleton, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this._stack = [{ scope }];\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n this.getScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n this.getScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n this.getScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n this.getScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n this.getScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n this.getScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (__DEBUG_BUILD__ && !result) {\n // eslint-disable-next-line no-console\n console.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n public shouldSendDefaultPii(): boolean {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n private _withClient(callback: (client: Client, scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n __DEBUG_BUILD__ && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(carrier) || getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {\n const globalHubTopStack = parent.getStackTop();\n setHubOnCarrier(carrier, new Hub(globalHubTopStack.client, Scope.clone(globalHubTopStack.scope)));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope: Scope) => {\n scope.addEventProcessor((event: SentryEvent) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n}\n","import type {\n Breadcrumb,\n CaptureContext,\n CheckIn,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n MonitorConfig,\n Primitive,\n Severity,\n SeverityLevel,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { logger, uuid4 } from '@sentry/utils';\n\nimport type { Hub } from './hub';\nimport { getCurrentHub } from './hub';\nimport type { Scope } from './scope';\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): ReturnType {\n return getCurrentHub().captureException(exception, { captureContext });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): ReturnType {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event, hint?: EventHint): ReturnType {\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb): ReturnType {\n getCurrentHub().addBreadcrumb(breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): ReturnType {\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): ReturnType {\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): ReturnType {\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): ReturnType {\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): ReturnType {\n getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): ReturnType {\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const client = getCurrentHub().getClient();\n if (!client) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n __DEBUG_BUILD__ && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig);\n }\n\n return uuid4();\n}\n","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\n/** JSDoc */\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nexport class TryCatch implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'TryCatch';\n\n /**\n * @inheritDoc\n */\n public name: string = TryCatch.id;\n\n /** JSDoc */\n private readonly _options: TryCatchOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n public setupOnce(): void {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n}\n\n/** JSDoc */\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: () => void): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type {\n HandlerDataFetch,\n HandlerDataXhr,\n SentryWrappedXMLHttpRequest,\n SentryXhrData,\n WrappedFunction,\n} from '@sentry/types';\n\nimport { isString } from './is';\nimport { CONSOLE_LEVELS, logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v2__';\n\nexport type InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n __DEBUG_BUILD__ && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in WINDOW)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: string): void {\n if (!(level in WINDOW.console)) {\n return;\n }\n\n fill(WINDOW.console, level, function (originalConsoleMethod: () => any): Function {\n return function (...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(WINDOW.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(WINDOW, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(WINDOW, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in WINDOW)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const url = args[1];\n const xhrInfo: SentryXhrData = (this[SENTRY_XHR_DATA_KEY] = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n request_headers: {},\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args: args as [string, string],\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr: this,\n } as HandlerDataXhr);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs as [string, string];\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n if (sentryXhrData && args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in WINDOW)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler: (typeof WINDOW)['onerror'] | null = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n WINDOW.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nlet _oldOnUnhandledRejectionHandler: (typeof WINDOW)['onunhandledrejection'] | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n WINDOW.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n// TODO remove this in v7 (this means the method will no longer be exported, under any name)\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, Severity, SeverityLevel, StackFrame, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n isUnhandledRejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception as DOMError) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n input: string,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\n return event;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Hub, Integration, Primitive, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\n/** JSDoc */\ntype GlobalHandlersIntegrations = Record;\n\n/** Global handlers */\nexport class GlobalHandlers implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GlobalHandlers';\n\n /**\n * @inheritDoc\n */\n public name: string = GlobalHandlers.id;\n\n /** JSDoc */\n private readonly _options: GlobalHandlersIntegrations;\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n private _installFunc: Record void) | undefined> = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n\n /** JSDoc */\n public constructor(options?: GlobalHandlersIntegrations) {\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key as GlobalHandlersIntegrationsOptionKeys];\n if (installFunc && options[key as GlobalHandlersIntegrationsOptionKeys]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key as GlobalHandlersIntegrationsOptionKeys] = undefined;\n }\n }\n }\n}\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler(): void {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler(): void {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e: any) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n __DEBUG_BUILD__ && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions(): [Hub, StackParser, boolean | undefined] {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n .replace(':80', '')\n .replace(':443', '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable max-lines */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event as SentryEvent, HandlerDataFetch, HandlerDataXhr, Integration } from '@sentry/types';\nimport type {\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n addInstrumentationHandler,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n SENTRY_XHR_DATA_KEY,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\ntype HandlerData = Record;\n\n/** JSDoc */\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nexport const BREADCRUMB_INTEGRATION_ID = 'Breadcrumbs';\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nexport class Breadcrumbs implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = BREADCRUMB_INTEGRATION_ID;\n\n /**\n * @inheritDoc\n */\n public name: string = Breadcrumbs.id;\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n public readonly options: Readonly;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial) {\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n public setupOnce(): void {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n\n /**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\n public addSentryBreadcrumb(event: SentryEvent): void {\n if (this.options.sentry) {\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n }\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerData) => void {\n function _innerDomBreadcrumb(handlerData: HandlerData): void {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n target = _isEvent(event)\n ? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })\n : htmlTreeAsString(event, { keyAttrs, maxStringLength });\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _consoleBreadcrumb(handlerData: HandlerData & { args: unknown[]; level: string }): void {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/6010\n // see: https://github.com/getsentry/sentry-javascript/issues/5916\n for (let i = 0; i < handlerData.args.length; i++) {\n if (handlerData.args[i] === 'ref=Ref<') {\n handlerData.args[i + 1] = 'viewRef';\n break;\n }\n }\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _xhrBreadcrumb(handlerData: HandlerData & HandlerDataXhr): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _fetchBreadcrumb(handlerData: HandlerData & HandlerDataFetch & { response?: Response }): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: handlerData.response && handlerData.response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp,\n endTimestamp,\n };\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _historyBreadcrumb(handlerData: HandlerData & { from: string; to: string }): void {\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return event && !!(event as Record).target;\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, ExtendedError, Integration, StackParser } from '@sentry/types';\nimport { isInstanceOf } from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { exceptionFromError } from '../eventbuilder';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\ninterface LinkedErrorsOptions {\n key: string;\n limit: number;\n}\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: LinkedErrorsOptions['key'];\n\n /**\n * @inheritDoc\n */\n private readonly _limit: LinkedErrorsOptions['limit'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: Partial = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n const client = getCurrentHub().getClient();\n if (!client) {\n return;\n }\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(client.getOptions().stackParser, self._key, self._limit, event, hint) : event;\n });\n }\n}\n\n/**\n * @inheritDoc\n */\nexport function _handler(\n parser: StackParser,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): Event | null {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(parser, limit, hint.originalException as ExtendedError, key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nexport function _walkErrorTree(\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n stack: Exception[] = [],\n): Exception[] {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(parser, error[key]);\n return _walkErrorTree(parser, limit, error[key], key, [exception, ...stack]);\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, Integration } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\n/** HttpContext integration collects information about HTTP request headers */\nexport class HttpContext implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'HttpContext';\n\n /**\n * @inheritDoc\n */\n public name: string = HttpContext.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n if (getCurrentHub().getIntegration(HttpContext)) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n}\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Primitive,\n Span as SpanInterface,\n SpanContext,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[] = [];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * @inheritDoc\n */\n public traceId: string = uuid4();\n\n /**\n * @inheritDoc\n */\n public spanId: string = uuid4().substring(16);\n\n /**\n * @inheritDoc\n */\n public parentSpanId?: string;\n\n /**\n * Internal keeper of the status\n */\n public status?: SpanStatusType | string;\n\n /**\n * @inheritDoc\n */\n public sampled?: boolean;\n\n /**\n * Timestamp in seconds when the span was created.\n */\n public startTimestamp: number = timestampInSeconds();\n\n /**\n * Timestamp in seconds when the span ended.\n */\n public endTimestamp?: number;\n\n /**\n * @inheritDoc\n */\n public op?: string;\n\n /**\n * @inheritDoc\n */\n public description?: string;\n\n /**\n * @inheritDoc\n */\n public tags: { [key: string]: Primitive } = {};\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any } = {};\n\n /**\n * List of spans that were finalized\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n */\n public instrumenter: Instrumenter = 'sentry';\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext?: SpanContext) {\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n if (spanContext.instrumenter) {\n this.instrumenter = spanContext.instrumenter;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startChild(\n spanContext?: Pick>,\n ): Span {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n if (__DEBUG_BUILD__ && childSpan.transaction) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = childSpan.transaction.name || '< unknown name >';\n const idStr = childSpan.transaction.spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };\n logger.log(logMessage);\n }\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public setData(key: string, value: any): this {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setHttpStatus(httpStatus: number): this {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = spanStatusfromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public isSuccess(): boolean {\n return this.status === 'ok';\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): void {\n if (\n __DEBUG_BUILD__ &&\n // Don't call this for transactions\n this.transaction &&\n this.transaction.spanId !== this.spanId\n ) {\n const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n }\n\n /**\n * @inheritDoc\n */\n public toTraceparent(): string {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(spanContext: SpanContext): this {\n this.data = spanContext.data || {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId || this.spanId;\n this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags || {};\n this.traceId = spanContext.traceId || this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getTraceContext(): TraceContext {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public toJSON(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n start_timestamp: number;\n status?: string;\n tags?: { [key: string]: Primitive };\n timestamp?: number;\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function spanStatusfromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n Event,\n Measurements,\n MeasurementUnit,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { Span as SpanClass, SpanRecorder } from './span';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n public metadata: TransactionMetadata;\n\n /**\n * The reference to the current hub.\n */\n public _hub: Hub;\n\n private _name: string;\n\n private _measurements: Measurements = {};\n\n private _contexts: Contexts = {};\n\n private _trimEnd?: boolean;\n\n private _frozenDynamicSamplingContext: Readonly> | undefined = undefined;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this.metadata = {\n source: 'custom',\n ...transactionContext.metadata,\n spanMetadata: {},\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n /** Getter for `name` property */\n public get name(): string {\n return this._name;\n }\n\n /** Setter for `name` property, which also sets `source` as custom */\n public set name(newName: string) {\n this.setName(newName);\n }\n\n /**\n * JSDoc\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.metadata.source = source;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * @inheritDoc\n */\n public setMetadata(newMetadata: Partial): void {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): string | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n __DEBUG_BUILD__ && logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n __DEBUG_BUILD__ && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const metadata = this.metadata;\n\n const transaction: Event = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n dynamicSamplingContext: this.getDynamicSamplingContext(),\n },\n ...(metadata.source && {\n transaction_info: {\n source: metadata.source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n __DEBUG_BUILD__ &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name || '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n */\n public getDynamicSamplingContext(): Readonly> {\n if (this._frozenDynamicSamplingContext) {\n return this._frozenDynamicSamplingContext;\n }\n\n const hub: Hub = this._hub || getCurrentHub();\n const client = hub && hub.getClient();\n\n if (!client) return {};\n\n const { environment, release } = client.getOptions() || {};\n const { publicKey: public_key } = client.getDsn() || {};\n\n const maybeSampleRate = this.metadata.sampleRate;\n const sample_rate = maybeSampleRate !== undefined ? maybeSampleRate.toString() : undefined;\n\n const { segment: user_segment } = hub.getScope().getUser() || {};\n\n const source = this.metadata.source;\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const transaction = source && source !== 'url' ? this.name : undefined;\n\n const dsc = dropUndefinedKeys({\n environment: environment || DEFAULT_ENVIRONMENT,\n release,\n transaction,\n user_segment,\n public_key,\n trace_id: this.traceId,\n sample_rate,\n });\n\n // Uncomment if we want to make DSC immutable\n // this._frozenDynamicSamplingContext = dsc;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n}\n","/* eslint-disable max-lines */\nimport type { TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp?: number) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record = {};\n\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number = 0;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean = false;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean = false;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[] = [];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number] = IDLE_TRANSACTION_FINISH_REASONS[4];\n\n public constructor(\n transactionContext: TransactionContext,\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n __DEBUG_BUILD__ && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._restartIdleTimeout();\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.finish();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public finish(endTimestamp: number = timestampInSeconds()): string | undefined {\n this._finished = true;\n this.activities = {};\n\n if (this.op === 'ui.action.click') {\n this.setTag(FINISH_REASON_TAG, this._finishReason);\n }\n\n if (this.spanRecorder) {\n __DEBUG_BUILD__ &&\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus('cancelled');\n __DEBUG_BUILD__ &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n __DEBUG_BUILD__ &&\n logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n __DEBUG_BUILD__ && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n __DEBUG_BUILD__ && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n const scope = this._idleHub.getScope();\n if (scope.getTransaction() === this) {\n scope.setSpan(undefined);\n }\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n __DEBUG_BUILD__ && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.finish(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n __DEBUG_BUILD__ && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n __DEBUG_BUILD__ && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n __DEBUG_BUILD__ && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n __DEBUG_BUILD__ && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n __DEBUG_BUILD__ && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n __DEBUG_BUILD__ && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n","import type { Options } from '@sentry/types';\n\nimport { getCurrentHub } from '../hub';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getCurrentHub().getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n","import type { Transaction } from '@sentry/types';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * TODO(v7): Reorganize these exports\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n */\nexport { TRACEPARENT_REGEXP, extractTraceparentData } from '@sentry/utils';\n\n/** Grabs active transaction off scope, if any */\nexport function getActiveTransaction(maybeHub?: Hub): T | undefined {\n const hub = maybeHub || getCurrentHub();\n const scope = hub.getScope();\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n","import { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport type { SpanStatusType } from './span';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addInstrumentationHandler('error', errorCallback);\n addInstrumentationHandler('unhandledrejection', errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n __DEBUG_BUILD__ && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n","import type { ClientOptions, CustomSamplingContext, Options, SamplingContext, TransactionContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n const scope = this.getScope();\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': span.toTraceparent(),\n }\n : {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param transaction: The transaction needing a sampling decision\n * @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler`\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample(\n transaction: T,\n options: Pick,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n sampleRate: Number(transaction.sampled),\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setMetadata({\n sampleRate,\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n __DEBUG_BUILD__ && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n const client = this.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n __DEBUG_BUILD__ &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n transactionContext.sampled = false;\n }\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n): IdleTransaction {\n const client = hub.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n","import type { TraceparentData } from '@sentry/types';\n\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent: string): TraceparentData | undefined {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n\n if (!traceparent || !matches) {\n // empty string or no matches is invalid traceparent data\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n","import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n return {\n ...acc,\n ...currBaggageObject,\n };\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext: Partial,\n): string | undefined {\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): number => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport { getActiveTransaction } from '@sentry/core';\nimport type { Measurements } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, htmlTreeAsString, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../types';\nimport { onCLS } from '../web-vitals/getCLS';\nimport { onFID } from '../web-vitals/getFID';\nimport { onLCP } from '../web-vitals/getLCP';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport { observe } from '../web-vitals/lib/observe';\nimport type { NavigatorDeviceMemory, NavigatorNetworkInformation } from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n\n return (): void => {\n if (clsCallback) {\n clsCallback();\n }\n if (lcpCallback) {\n lcpCallback();\n }\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n const entryHandler = (entries: PerformanceEntry[]): void => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n };\n\n observe('longtask', entryHandler);\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n const entryHandler = (entries: PerformanceEventTiming[]): void => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n }\n };\n\n observe('event', entryHandler, { durationThreshold: 0 });\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): ReturnType {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n return onCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): ReturnType {\n return onLCP(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): void {\n onFID(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp: number | undefined;\n let requestStartTimestamp: number | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name as string).replace(WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n __DEBUG_BUILD__ &&\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record, timeOrigin: number): void {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n}\n\nexport interface ResourceEntry extends Record {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceName: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record = {};\n if ('transferSize' in entry) {\n data['http.response_transfer_size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['http.response_content_length'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['http.decoded_response_content_length'] = entry.decodedBodySize;\n }\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (onReport: ReportCallback): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n","/* eslint-disable max-lines */\nimport { getCurrentHub, hasTracingEnabled } from '@sentry/core';\nimport type { DynamicSamplingContext, Span } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n BAGGAGE_HEADER_NAME,\n dynamicSamplingContextToSentryBaggageHeader,\n isInstanceOf,\n SENTRY_XHR_DATA_KEY,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * Default: ['localhost', /^\\//] {@see DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\n/** Data returned from fetch callback */\nexport interface FetchData {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[]; // the arguments passed to the fetch call itself\n fetchData?: {\n method: string;\n url: string;\n // span_id\n __span?: string;\n };\n\n // TODO Should this be unknown instead? If we vendor types, make it a Response\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response?: any;\n error?: unknown;\n\n startTimestamp: number;\n endTimestamp?: number;\n}\n\n/** Data returned from XHR request */\nexport interface XHRData {\n xhr?: {\n [SENTRY_XHR_DATA_KEY]?: {\n method: string;\n url: string;\n status_code: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: Record;\n };\n __sentry_xhr_span_id__?: string;\n setRequestHeader?: (key: string, val: string) => void;\n getRequestHeader?: (key: string) => string;\n __sentry_own_request__?: boolean;\n };\n startTimestamp: number;\n endTimestamp?: number;\n}\n\ntype PolymorphicRequestHeaders =\n | Record\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial): void {\n // eslint-disable-next-line deprecation/deprecation\n const { traceFetch, traceXHR, tracePropagationTargets, tracingOrigins, shouldCreateSpanForRequest } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record = {};\n\n if (traceFetch) {\n addInstrumentationHandler('fetch', (handlerData: FetchData) => {\n fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler('xhr', (handlerData: XHRData) => {\n xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track fetch request spans\n */\nexport function fetchCallback(\n handlerData: FetchData,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): void {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n\n const contentLength: string =\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setData('http.response_content_length', contentLengthNum);\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const { method, url } = handlerData.fetchData;\n const span = currentSpan.startChild({\n data: {\n url,\n type: 'fetch',\n 'http.method': method,\n },\n description: `${method} ${url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n options.headers = addTracingHeadersToFetchRequest(\n request,\n activeTransaction.getDynamicSamplingContext(),\n span,\n options,\n );\n }\n }\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n dynamicSamplingContext: Partial,\n span: Span,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n): PolymorphicRequestHeaders {\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n const sentryTraceHeader = span.toTraceparent();\n\n const headers =\n typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nexport function xhrCallback(\n handlerData: XHRData,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): void {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (\n !hasTracingEnabled() ||\n (xhr && xhr.__sentry_own_request__) ||\n !(xhr && sentryXhrData && shouldCreateSpan(sentryXhrData.url))\n ) {\n return;\n }\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n span.setHttpStatus(sentryXhrData.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...sentryXhrData.data,\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n url: sentryXhrData.url,\n },\n description: `${sentryXhrData.method} ${sentryXhrData.url}`,\n op: 'http.client',\n });\n\n xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url)) {\n try {\n xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n\n const dynamicSamplingContext = activeTransaction.getDynamicSamplingContext();\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n xhr.setRequestHeader(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n","/* eslint-disable max-lines */\nimport type { Hub, IdleTransaction } from '@sentry/core';\nimport {\n addTracingExtensions,\n extractTraceparentData,\n getActiveTransaction,\n startIdleTransaction,\n TRACING_DEFAULTS,\n} from '@sentry/core';\nimport type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';\nimport { baggageHeaderToDynamicSamplingContext, getDomElement, logger } from '@sentry/utils';\n\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport {\n addPerformanceEntries,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nimport { WINDOW } from './types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableLongTask: boolean;\n enableInteractions: boolean;\n onStartRouteTransaction: (t: Transaction | undefined, ctx: TransactionContext, getCurrentHub: () => Hub) => void;\n }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(this: void, context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation(\n this: void,\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nexport class BrowserTracing implements Integration {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string = BROWSER_TRACING_INTEGRATION_ID;\n\n private _getCurrentHub?: () => Hub;\n\n private _latestRouteName?: string;\n private _latestRouteSource?: TransactionSource;\n\n private _collectWebVitals: () => void;\n\n public constructor(_options?: Partial) {\n addTracingExtensions();\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n _experiments,\n } = this.options;\n\n instrumentRouting(\n (context: TransactionContext) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTraceMetaTagValue = isPageloadTransaction ? getMetaContent('sentry-trace') : null;\n const baggageMetaTagValue = isPageloadTransaction ? getMetaContent('baggage') : null;\n\n const traceParentData = sentryTraceMetaTagValue ? extractTraceparentData(sentryTraceMetaTagValue) : undefined;\n const dynamicSamplingContext = baggageMetaTagValue\n ? baggageHeaderToDynamicSamplingContext(baggageMetaTagValue)\n : undefined;\n\n const expandedContext: TransactionContext = {\n ...context,\n ...traceParentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n __DEBUG_BUILD__ &&\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n /** Start listener for interaction transactions */\n private _registerInteractionListener(): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n __DEBUG_BUILD__ && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | null {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : null;\n}\n","import type { Transaction, TransactionContext } from '@sentry/types';\nimport { addInstrumentationHandler, browserPerformanceTimeOrigin, logger } from '@sentry/utils';\n\nimport { WINDOW } from './types';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!WINDOW || !WINDOW.location) {\n __DEBUG_BUILD__ && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = WINDOW.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler('history', ({ to, from }: { to: string; from?: string }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n __DEBUG_BUILD__ && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n","import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n __DEBUG_BUILD__ &&\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}","import type { ClientOptions, Event, EventHint, StackFrame, StackParser } from '@sentry/types';\nimport { dateTimestampInSeconds, GLOBAL_OBJ, normalize, resolvedSyncPromise, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { Scope } from '../scope';\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!__DEBUG_BUILD__) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nexport const REPLAY_SESSION_KEY = 'sentryReplaySession';\nexport const REPLAY_EVENT_NAME = 'replay_event';\nexport const RECORDING_EVENT_NAME = 'replay_recording';\nexport const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nexport const SESSION_IDLE_PAUSE_DURATION = 300_000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nexport const SESSION_IDLE_EXPIRE_DURATION = 900_000; // 15 minutes in ms\n\n// The maximum length of a session\nexport const MAX_SESSION_LIFE = 3_600_000; // 60 minutes in ms\n\n/** Default flush delays */\nexport const DEFAULT_FLUSH_MIN_DELAY = 5_000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nexport const DEFAULT_FLUSH_MAX_DELAY = 5_500;\n\n/* How long to wait for error checkouts */\nexport const BUFFER_CHECKOUT_TIME = 60_000;\n\nexport const RETRY_BASE_INTERVAL = 5000;\nexport const RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nexport const NETWORK_BODY_MAX_SIZE = 150_000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nexport const CONSOLE_ARG_MAX_SIZE = 5_000;\n\n/* Min. time to wait before we consider something a slow click. */\nexport const SLOW_CLICK_THRESHOLD = 3_000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nexport const SLOW_CLICK_SCROLL_TIMEOUT = 300;\n/* Clicks in this time period are considered e.g. double/triple clicks. */\nexport const MULTI_CLICK_TIMEOUT = 1_000;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nexport const REPLAY_MAX_EVENT_BUFFER_SIZE = 20_000_000; // ~20MB\n","var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = n === null || n === void 0 ? void 0 : n.host;\n return Boolean(host && host.shadowRoot && host.shadowRoot === n);\n}\nfunction isInputTypeMasked({ maskInputOptions, tagName, type, }) {\n if (tagName.toLowerCase() === 'option') {\n tagName = 'select';\n }\n const actualType = typeof type === 'string' ? type.toLowerCase() : undefined;\n return (maskInputOptions[tagName.toLowerCase()] ||\n (actualType && maskInputOptions[actualType]) ||\n actualType === 'password' ||\n (tagName === 'input' && !type && maskInputOptions['text']));\n}\nfunction hasInputMaskOptions({ tagName, type, maskInputOptions, maskInputSelector, }) {\n return (maskInputSelector || isInputTypeMasked({ maskInputOptions, tagName, type }));\n}\nfunction maskInputValue({ input, maskInputSelector, unmaskInputSelector, maskInputOptions, tagName, type, value, maskInputFn, }) {\n let text = value || '';\n if (unmaskInputSelector && input.matches(unmaskInputSelector)) {\n return text;\n }\n if (input.hasAttribute('data-rr-is-password')) {\n type = 'password';\n }\n if (isInputTypeMasked({ maskInputOptions, tagName, type }) ||\n (maskInputSelector && input.matches(maskInputSelector))) {\n if (maskInputFn) {\n text = maskInputFn(text);\n }\n else {\n text = '*'.repeat(text.length);\n }\n }\n return text;\n}\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext('2d');\n if (!ctx)\n return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some((pixel) => pixel !== 0))\n return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute('data-rr-is-password')\n ? 'password'\n : type\n ? type.toLowerCase()\n : null;\n}\nfunction getInputValue(el, tagName, type) {\n typeof type === 'string' ? type.toLowerCase() : '';\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\n return el.getAttribute('value') || '';\n }\n return el.value;\n}\nfunction defineCustomElement(w, elementName) {\n try {\n if (!w.customElements.get(elementName)) {\n const CustomElement = w.HTMLElement;\n w.customElements.define(elementName, class extends CustomElement {\n });\n }\n }\n catch (_a) { }\n}\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\nconst IGNORED_NODE = -2;\nfunction defaultMaskFn(str) {\n return str ? str.replace(/[\\S]/g, '*') : '';\n}\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return 'form';\n }\n const processedTagName = element.tagName.toLowerCase().trim();\n if (tagNameRegex.test(processedTagName)) {\n return 'div';\n }\n return processedTagName;\n}\nfunction getCssRulesString(s) {\n try {\n const rules = s.rules || s.cssRules;\n return rules ? Array.from(rules).map(getCssRuleString).join('') : null;\n }\n catch (error) {\n return null;\n }\n}\nfunction getCssRuleString(rule) {\n let cssStringified = rule.cssText;\n if (isCSSImportRule(rule)) {\n try {\n cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;\n }\n catch (_a) {\n }\n }\n return validateStringifiedCssRule(cssStringified);\n}\nfunction validateStringifiedCssRule(cssStringified) {\n if (cssStringified.indexOf(':') > -1) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, '$1\\\\$2');\n }\n return cssStringified;\n}\nfunction isCSSImportRule(rule) {\n return 'styleSheet' in rule;\n}\nfunction stringifyStyleSheet(sheet) {\n return sheet.cssRules\n ? Array.from(sheet.cssRules)\n .map((rule) => rule.cssText ? validateStringifiedCssRule(rule.cssText) : '')\n .join('')\n : '';\n}\nfunction extractOrigin(url) {\n let origin = '';\n if (url.indexOf('//') > -1) {\n origin = url.split('/').slice(0, 3).join('/');\n }\n else {\n origin = url.split('/')[0];\n }\n origin = origin.split('?')[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst RELATIVE_PATH = /^(?!www\\.|(?:http|ftp)s?:\\/\\/|[A-Za-z]:\\\\|\\/\\/|#).*/;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || '';\n if (!filePath) {\n return origin;\n }\n if (!RELATIVE_PATH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === '/') {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split('/');\n const parts = filePath.split('/');\n stack.pop();\n for (const part of parts) {\n if (part === '.') {\n continue;\n }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\n });\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === '') {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars;\n let match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return '';\n }\n let output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === ',') {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n }\n else {\n let descriptorsStr = '';\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n let c = attributeValue.charAt(pos);\n if (c === '') {\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\n }\n else {\n if (c === ')') {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(', ');\n}\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === '') {\n return attributeValue;\n }\n const a = doc.createElement('a');\n a.href = attributeValue;\n return a.href;\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\n}\nfunction getHref() {\n const a = document.createElement('a');\n a.href = '';\n return a.href;\n}\nfunction transformAttribute(doc, element, _tagName, _name, value, maskAllText, unmaskTextSelector, maskTextFn) {\n if (!value) {\n return value;\n }\n const name = _name.toLowerCase();\n const tagName = _tagName.toLowerCase();\n if (name === 'src' || name === 'href') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset') {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style') {\n return absoluteToStylesheet(value, getHref());\n }\n else if (tagName === 'object' && name === 'data') {\n return absoluteToDoc(doc, value);\n }\n else if (maskAllText &&\n _shouldMaskAttribute(element, name, tagName, unmaskTextSelector)) {\n return maskTextFn ? maskTextFn(value) : defaultMaskFn(value);\n }\n return value;\n}\nfunction _shouldMaskAttribute(element, attribute, tagName, unmaskTextSelector) {\n if (unmaskTextSelector && element.matches(unmaskTextSelector)) {\n return false;\n }\n return (['placeholder', 'title', 'aria-label'].indexOf(attribute) > -1 ||\n (tagName === 'input' &&\n attribute === 'value' &&\n element.hasAttribute('type') &&\n ['submit', 'button'].indexOf(element.getAttribute('type').toLowerCase()) > -1));\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === 'string') {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < element.classList.length; eIndex++) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n return false;\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) {\n if (!node) {\n return false;\n }\n if (node.nodeType !== node.ELEMENT_NODE) {\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n }\n if (unmaskTextSelector) {\n if (node.matches(unmaskTextSelector) ||\n node.closest(unmaskTextSelector)) {\n return false;\n }\n }\n if (maskAllText) {\n return true;\n }\n if (typeof maskTextClass === 'string') {\n if (node.classList.contains(maskTextClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < node.classList.length; eIndex++) {\n const className = node.classList[eIndex];\n if (maskTextClass.test(className)) {\n return true;\n }\n }\n }\n if (maskTextSelector) {\n if (node.matches(maskTextSelector)) {\n return true;\n }\n }\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n }\n catch (error) {\n return;\n }\n if (readyState !== 'complete') {\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener('load', () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n iframeEl.src === '') {\n setTimeout(listener, 0);\n return;\n }\n iframeEl.addEventListener('load', listener);\n}\nfunction serializeNode(n, options) {\n var _a;\n const { doc, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, } = options;\n let rootId;\n if (doc.__sn) {\n const docId = doc.__sn.id;\n rootId = docId === 1 ? undefined : docId;\n }\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== 'CSS1Compat') {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode,\n rootId,\n };\n }\n else {\n return {\n type: NodeType.Document,\n childNodes: [],\n rootId,\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId,\n };\n case n.ELEMENT_NODE:\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n for (const { name, value } of Array.from(n.attributes)) {\n if (!skipAttribute(tagName, name)) {\n attributes[name] = transformAttribute(doc, n, tagName, name, value, maskAllText, unmaskTextSelector, maskTextFn);\n }\n }\n if (tagName === 'link' && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = getCssRulesString(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText ||\n n.textContent ||\n '').trim().length) {\n const cssText = getCssRulesString(n.sheet);\n if (cssText) {\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select' ||\n tagName === 'option') {\n const el = n;\n const type = getInputType(el);\n const value = getInputValue(el, tagName.toUpperCase(), type);\n const checked = n.checked;\n if (type !== 'submit' &&\n type !== 'button' &&\n value) {\n attributes.value = maskInputValue({\n input: el,\n type,\n tagName,\n value,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes.selected = true;\n }\n else {\n delete attributes.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n const blankCanvas = document.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === 'img' && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement('canvas');\n canvasCtx = canvasService.getContext('2d');\n }\n const image = n;\n const oldValue = image.crossOrigin;\n image.crossOrigin = 'anonymous';\n const recordInlineImage = () => {\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n catch (err) {\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\n }\n oldValue\n ? (attributes.crossOrigin = oldValue)\n : delete attributes.crossOrigin;\n };\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.onload = recordInlineImage;\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes.rr_mediaCurrentTime = n.currentTime;\n }\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock,\n rootId,\n };\n case n.TEXT_NODE:\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\n textContent = stringifyStyleSheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref());\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n if (parentTagName === 'TEXTAREA' && textContent) {\n textContent = '';\n }\n else if (parentTagName === 'OPTION' && textContent) {\n const option = n.parentNode;\n textContent = maskInputValue({\n input: option,\n type: null,\n tagName: parentTagName,\n value: textContent,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n else if (!isStyle &&\n !isScript &&\n needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) &&\n textContent) {\n textContent = maskTextFn\n ? maskTextFn(textContent)\n : defaultMaskFn(textContent);\n }\n return {\n type: NodeType.Text,\n textContent: textContent || '',\n isStyle,\n rootId,\n };\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: '',\n rootId,\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: n.textContent || '',\n rootId,\n };\n default:\n return false;\n }\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined || maybeAttr === null) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n }\n else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n (sn.attributes.rel === 'preload' ||\n sn.attributes.rel === 'modulepreload') &&\n sn.attributes.as === 'script') ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n sn.attributes.href.endsWith('.js')))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const { doc, map, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, keepIframeSrcFn = () => false, } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n });\n if (!_serializedNode) {\n console.warn(n, 'not serialized');\n return null;\n }\n let id;\n if ('__sn' in n) {\n id = n.__sn.id;\n }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n n.__sn = serializedNode;\n if (id === IGNORED_NODE) {\n return null;\n }\n map[id] = n;\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n if (n.shadowRoot)\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document ||\n serializedNode.type === NodeType.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n _serializedNode.type === NodeType.Element &&\n _serializedNode.tagName === 'head') {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n };\n for (const childN of Array.from(n.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n) && n.shadowRoot) {\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedChildNode.isShadow = true;\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode && isShadowRoot(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(n, () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const { blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskInputSelector = null, unmaskInputSelector = null, maskAllText = false, maskAllInputs = false, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\n const idNodeMap = {};\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n }\n : maskAllInputs === false\n ? {}\n : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true,\n }\n : slimDOM === false\n ? {}\n : slimDOM;\n return [\n serializeNodeWithId(n, {\n doc: n,\n map: idNodeMap,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n }),\n idNodeMap,\n ];\n}\nfunction skipAttribute(tagName, attributeName, value) {\n return ((tagName === 'video' || tagName === 'audio') && attributeName === 'autoplay');\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\nfunction parse(css, options = {}) {\n let lineno = 1;\n let column = 1;\n function updatePosition(str) {\n const lines = str.match(/\\n/g);\n if (lines) {\n lineno += lines.length;\n }\n let i = str.lastIndexOf('\\n');\n column = i === -1 ? column + str.length : str.length - i;\n }\n function position() {\n const start = { line: lineno, column };\n return (node) => {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n class Position {\n constructor(start) {\n this.start = start;\n this.end = { line: lineno, column };\n this.source = options.source;\n }\n }\n Position.prototype.content = css;\n const errorsList = [];\n function error(msg) {\n const err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = css;\n if (options.silent) {\n errorsList.push(err);\n }\n else {\n throw err;\n }\n }\n function stylesheet() {\n const rulesList = rules();\n return {\n type: 'stylesheet',\n stylesheet: {\n source: options.source,\n rules: rulesList,\n parsingErrors: errorsList,\n },\n };\n }\n function open() {\n return match(/^{\\s*/);\n }\n function close() {\n return match(/^}/);\n }\n function rules() {\n let node;\n const rules = [];\n whitespace();\n comments(rules);\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\n if (node !== false) {\n rules.push(node);\n comments(rules);\n }\n }\n return rules;\n }\n function match(re) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n function whitespace() {\n match(/^\\s*/);\n }\n function comments(rules = []) {\n let c;\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n c = comment();\n }\n return rules;\n }\n function comment() {\n const pos = position();\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\n return;\n }\n let i = 2;\n while ('' !== css.charAt(i) &&\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\n ++i;\n }\n i += 2;\n if ('' === css.charAt(i - 1)) {\n return error('End of comment missing');\n }\n const str = css.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n css = css.slice(i);\n column += 2;\n return pos({\n type: 'comment',\n comment: str,\n });\n }\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n return trim(m[0])\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\n return m.replace(/,/g, '\\u200C');\n })\n .split(/\\s*(?![^(]*\\)),\\s*/)\n .map((s) => {\n return s.replace(/\\u200C/g, ',');\n });\n }\n function declaration() {\n const pos = position();\n let propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const prop = trim(propMatch[0]);\n if (!match(/^:\\s*/)) {\n return error(`property missing ':'`);\n }\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\n const ret = pos({\n type: 'declaration',\n property: prop.replace(commentre, ''),\n value: val ? trim(val[0]).replace(commentre, '') : '',\n });\n match(/^[;\\s]*/);\n return ret;\n }\n function declarations() {\n const decls = [];\n if (!open()) {\n return error(`missing '{'`);\n }\n comments(decls);\n let decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n decl = declaration();\n }\n if (!close()) {\n return error(`missing '}'`);\n }\n return decls;\n }\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n if (!vals.length) {\n return;\n }\n return pos({\n type: 'keyframe',\n values: vals,\n declarations: declarations(),\n });\n }\n function atkeyframes() {\n const pos = position();\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\n if (!m) {\n return;\n }\n const vendor = m[1];\n m = match(/^([-\\w]+)\\s*/);\n if (!m) {\n return error('@keyframes missing name');\n }\n const name = m[1];\n if (!open()) {\n return error(`@keyframes missing '{'`);\n }\n let frame;\n let frames = comments();\n while ((frame = keyframe())) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n if (!close()) {\n return error(`@keyframes missing '}'`);\n }\n return pos({\n type: 'keyframes',\n name,\n vendor,\n keyframes: frames,\n });\n }\n function atsupports() {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n if (!open()) {\n return error(`@supports missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@supports missing '}'`);\n }\n return pos({\n type: 'supports',\n supports,\n rules: style,\n });\n }\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@host missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@host missing '}'`);\n }\n return pos({\n type: 'host',\n rules: style,\n });\n }\n function atmedia() {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n if (!open()) {\n return error(`@media missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@media missing '}'`);\n }\n return pos({\n type: 'media',\n media,\n rules: style,\n });\n }\n function atcustommedia() {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n return pos({\n type: 'custom-media',\n name: trim(m[1]),\n media: trim(m[2]),\n });\n }\n function atpage() {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n const sel = selector() || [];\n if (!open()) {\n return error(`@page missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@page missing '}'`);\n }\n return pos({\n type: 'page',\n selectors: sel,\n declarations: decls,\n });\n }\n function atdocument() {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n if (!open()) {\n return error(`@document missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@document missing '}'`);\n }\n return pos({\n type: 'document',\n document: doc,\n vendor,\n rules: style,\n });\n }\n function atfontface() {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@font-face missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@font-face missing '}'`);\n }\n return pos({\n type: 'font-face',\n declarations: decls,\n });\n }\n const atimport = _compileAtrule('import');\n const atcharset = _compileAtrule('charset');\n const atnamespace = _compileAtrule('namespace');\n function _compileAtrule(name) {\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\n return () => {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret = { type: name };\n ret[name] = m[1].trim();\n return pos(ret);\n };\n }\n function atrule() {\n if (css[0] !== '@') {\n return;\n }\n return (atkeyframes() ||\n atmedia() ||\n atcustommedia() ||\n atsupports() ||\n atimport() ||\n atcharset() ||\n atnamespace() ||\n atdocument() ||\n atpage() ||\n athost() ||\n atfontface());\n }\n function rule() {\n const pos = position();\n const sel = selector();\n if (!sel) {\n return error('selector missing');\n }\n comments();\n return pos({\n type: 'rule',\n selectors: sel,\n declarations: declarations(),\n });\n }\n return addParent(stylesheet());\n}\nfunction trim(str) {\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\n}\nfunction addParent(obj, parent) {\n const isNode = obj && typeof obj.type === 'string';\n const childParent = isNode ? obj : parent;\n for (const k of Object.keys(obj)) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach((v) => {\n addParent(v, childParent);\n });\n }\n else if (value && typeof value === 'object') {\n addParent(value, childParent);\n }\n }\n if (isNode) {\n Object.defineProperty(obj, 'parent', {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null,\n });\n }\n return obj;\n}\n\nconst tagMap = {\n script: 'noscript',\n altglyph: 'altGlyph',\n altglyphdef: 'altGlyphDef',\n altglyphitem: 'altGlyphItem',\n animatecolor: 'animateColor',\n animatemotion: 'animateMotion',\n animatetransform: 'animateTransform',\n clippath: 'clipPath',\n feblend: 'feBlend',\n fecolormatrix: 'feColorMatrix',\n fecomponenttransfer: 'feComponentTransfer',\n fecomposite: 'feComposite',\n feconvolvematrix: 'feConvolveMatrix',\n fediffuselighting: 'feDiffuseLighting',\n fedisplacementmap: 'feDisplacementMap',\n fedistantlight: 'feDistantLight',\n fedropshadow: 'feDropShadow',\n feflood: 'feFlood',\n fefunca: 'feFuncA',\n fefuncb: 'feFuncB',\n fefuncg: 'feFuncG',\n fefuncr: 'feFuncR',\n fegaussianblur: 'feGaussianBlur',\n feimage: 'feImage',\n femerge: 'feMerge',\n femergenode: 'feMergeNode',\n femorphology: 'feMorphology',\n feoffset: 'feOffset',\n fepointlight: 'fePointLight',\n fespecularlighting: 'feSpecularLighting',\n fespotlight: 'feSpotLight',\n fetile: 'feTile',\n feturbulence: 'feTurbulence',\n foreignobject: 'foreignObject',\n glyphref: 'glyphRef',\n lineargradient: 'linearGradient',\n radialgradient: 'radialGradient',\n};\nfunction getTagName(n) {\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\n if (tagName === 'link' && n.attributes._cssText) {\n tagName = 'style';\n }\n return tagName;\n}\nfunction escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\nfunction addHoverClass(cssText, cache) {\n const cachedStyle = cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.get(cssText);\n if (cachedStyle)\n return cachedStyle;\n const ast = parse(cssText, {\n silent: true,\n });\n if (!ast.stylesheet) {\n return cssText;\n }\n const selectors = [];\n ast.stylesheet.rules.forEach((rule) => {\n if ('selectors' in rule) {\n (rule.selectors || []).forEach((selector) => {\n if (HOVER_SELECTOR.test(selector)) {\n selectors.push(selector);\n }\n });\n }\n });\n if (selectors.length === 0) {\n return cssText;\n }\n const selectorMatcher = new RegExp(selectors\n .filter((selector, index) => selectors.indexOf(selector) === index)\n .sort((a, b) => b.length - a.length)\n .map((selector) => {\n return escapeRegExp(selector);\n })\n .join('|'), 'g');\n const result = cssText.replace(selectorMatcher, (selector) => {\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\n return `${selector}, ${newSelector}`;\n });\n cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.set(cssText, result);\n return result;\n}\nfunction createCache() {\n const stylesWithHoverClass = new Map();\n return {\n stylesWithHoverClass,\n };\n}\nfunction buildNode(n, options) {\n const { doc, hackCss, cache } = options;\n switch (n.type) {\n case NodeType.Document:\n return doc.implementation.createDocument(null, '', null);\n case NodeType.DocumentType:\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\n case NodeType.Element:\n const tagName = getTagName(n);\n let node;\n if (n.isSVG) {\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\n }\n else {\n node = doc.createElement(tagName);\n }\n for (const name in n.attributes) {\n if (!n.attributes.hasOwnProperty(name)) {\n continue;\n }\n let value = n.attributes[name];\n if (tagName === 'option' && name === 'selected' && value === false) {\n continue;\n }\n value =\n typeof value === 'boolean' || typeof value === 'number' || value === null ? '' : value;\n if (!name.startsWith('rr_')) {\n const isTextarea = tagName === 'textarea' && name === 'value';\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\n if (isRemoteOrDynamicCss && hackCss) {\n value = addHoverClass(value, cache);\n }\n if (isTextarea || isRemoteOrDynamicCss) {\n const child = doc.createTextNode(value);\n for (const c of Array.from(node.childNodes)) {\n if (c.nodeType === node.TEXT_NODE) {\n node.removeChild(c);\n }\n }\n node.appendChild(child);\n continue;\n }\n try {\n if (n.isSVG && name === 'xlink:href') {\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value);\n }\n else if (name === 'onload' ||\n name === 'onclick' ||\n name.substring(0, 7) === 'onmouse') {\n node.setAttribute('_' + name, value);\n }\n else if (tagName === 'meta' &&\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\n name === 'content') {\n node.setAttribute('csp-content', value);\n continue;\n }\n else if (tagName === 'link' &&\n (n.attributes.rel === 'preload' || n.attributes.rel === 'modulepreload') &&\n n.attributes.as === 'script') {\n }\n else if (tagName === 'link' &&\n n.attributes.rel === 'prefetch' &&\n typeof n.attributes.href === 'string' &&\n n.attributes.href.endsWith('.js')) {\n }\n else if (tagName === 'img' &&\n n.attributes.srcset &&\n n.attributes.rr_dataURL) {\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\n }\n else {\n node.setAttribute(name, value);\n }\n }\n catch (error) {\n }\n }\n else {\n if (tagName === 'canvas' && name === 'rr_dataURL') {\n const image = document.createElement('img');\n image.src = value;\n image.onload = () => {\n const ctx = node.getContext('2d');\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n }\n else if (tagName === 'img' && name === 'rr_dataURL') {\n const image = node;\n if (!image.currentSrc.startsWith('data:')) {\n image.setAttribute('rrweb-original-src', n.attributes.src);\n image.src = value;\n }\n }\n if (name === 'rr_width') {\n node.style.width = value;\n }\n else if (name === 'rr_height') {\n node.style.height = value;\n }\n else if (name === 'rr_mediaCurrentTime') {\n node.currentTime = n.attributes\n .rr_mediaCurrentTime;\n }\n else if (name === 'rr_mediaState') {\n switch (value) {\n case 'played':\n node\n .play()\n .catch((e) => console.warn('media playback error', e));\n break;\n case 'paused':\n node.pause();\n break;\n }\n }\n }\n }\n if (n.isShadowHost) {\n if (!node.shadowRoot) {\n node.attachShadow({ mode: 'open' });\n if (doc.defaultView) {\n defineCustomElement(doc.defaultView, tagName);\n }\n }\n else {\n while (node.shadowRoot.firstChild) {\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\n }\n }\n }\n return node;\n case NodeType.Text:\n return doc.createTextNode(n.isStyle && hackCss\n ? addHoverClass(n.textContent, cache)\n : n.textContent);\n case NodeType.CDATA:\n return doc.createCDATASection(n.textContent);\n case NodeType.Comment:\n return doc.createComment(n.textContent);\n default:\n return null;\n }\n}\nfunction buildNodeWithSN(n, options) {\n const { doc, map, skipChild = false, hackCss = true, afterAppend, cache, } = options;\n let node = buildNode(n, { doc, hackCss, cache });\n if (!node) {\n return null;\n }\n if (n.rootId) {\n console.assert(map[n.rootId] === doc, 'Target document should has the same root id.');\n }\n if (n.type === NodeType.Document) {\n doc.close();\n doc.open();\n if (n.compatMode === 'BackCompat' &&\n n.childNodes &&\n n.childNodes[0].type !== NodeType.DocumentType) {\n if (n.childNodes[0].type === NodeType.Element &&\n 'xmlns' in n.childNodes[0].attributes &&\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\n doc.write('');\n }\n else {\n doc.write('');\n }\n }\n node = doc;\n }\n node.__sn = n;\n map[n.id] = node;\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\n !skipChild) {\n for (const childN of n.childNodes) {\n const childNode = buildNodeWithSN(childN, {\n doc,\n map,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n if (!childNode) {\n console.warn('Failed to rebuild', childN);\n continue;\n }\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\n node.shadowRoot.appendChild(childNode);\n }\n else {\n node.appendChild(childNode);\n }\n if (afterAppend) {\n afterAppend(childNode);\n }\n }\n }\n return node;\n}\nfunction visit(idNodeMap, onVisit) {\n function walk(node) {\n onVisit(node);\n }\n for (const key in idNodeMap) {\n if (idNodeMap[key]) {\n walk(idNodeMap[key]);\n }\n }\n}\nfunction handleScroll(node) {\n const n = node.__sn;\n if (n.type !== NodeType.Element) {\n return;\n }\n const el = node;\n for (const name in n.attributes) {\n if (!(n.attributes.hasOwnProperty(name) && name.startsWith('rr_'))) {\n continue;\n }\n const value = n.attributes[name];\n if (name === 'rr_scrollLeft') {\n el.scrollLeft = value;\n }\n if (name === 'rr_scrollTop') {\n el.scrollTop = value;\n }\n }\n}\nfunction rebuild(n, options) {\n const { doc, onVisit, hackCss = true, afterAppend, cache } = options;\n const idNodeMap = {};\n const node = buildNodeWithSN(n, {\n doc,\n map: idNodeMap,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n visit(idNodeMap, (visitedNode) => {\n if (onVisit) {\n onVisit(visitedNode);\n }\n handleScroll(visitedNode);\n });\n return [node, idNodeMap];\n}\n\nexport { IGNORED_NODE, NodeType, addHoverClass, buildNodeWithSN, createCache, defineCustomElement, getInputType, getInputValue, hasInputMaskOptions, is2DCanvasBlank, isElement, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, snapshot, transformAttribute };\n","var EventType;\n(function (EventType) {\n EventType[EventType[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType[EventType[\"Load\"] = 1] = \"Load\";\n EventType[EventType[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType[EventType[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType[EventType[\"Meta\"] = 4] = \"Meta\";\n EventType[EventType[\"Custom\"] = 5] = \"Custom\";\n EventType[EventType[\"Plugin\"] = 6] = \"Plugin\";\n})(EventType || (EventType = {}));\nvar IncrementalSource;\n(function (IncrementalSource) {\n IncrementalSource[IncrementalSource[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource[IncrementalSource[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource[IncrementalSource[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource[IncrementalSource[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource[IncrementalSource[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource[IncrementalSource[\"Input\"] = 5] = \"Input\";\n IncrementalSource[IncrementalSource[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource[IncrementalSource[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource[IncrementalSource[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource[IncrementalSource[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource[IncrementalSource[\"Font\"] = 10] = \"Font\";\n IncrementalSource[IncrementalSource[\"Log\"] = 11] = \"Log\";\n IncrementalSource[IncrementalSource[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource[IncrementalSource[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n})(IncrementalSource || (IncrementalSource = {}));\nvar MouseInteractions;\n(function (MouseInteractions) {\n MouseInteractions[MouseInteractions[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions[MouseInteractions[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions[MouseInteractions[\"Click\"] = 2] = \"Click\";\n MouseInteractions[MouseInteractions[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions[MouseInteractions[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions[MouseInteractions[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions[MouseInteractions[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions[MouseInteractions[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions[MouseInteractions[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions[MouseInteractions[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions[MouseInteractions[\"TouchCancel\"] = 10] = \"TouchCancel\";\n})(MouseInteractions || (MouseInteractions = {}));\nvar CanvasContext;\n(function (CanvasContext) {\n CanvasContext[CanvasContext[\"2D\"] = 0] = \"2D\";\n CanvasContext[CanvasContext[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext[CanvasContext[\"WebGL2\"] = 2] = \"WebGL2\";\n})(CanvasContext || (CanvasContext = {}));\nvar MediaInteractions;\n(function (MediaInteractions) {\n MediaInteractions[MediaInteractions[\"Play\"] = 0] = \"Play\";\n MediaInteractions[MediaInteractions[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions[MediaInteractions[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions[MediaInteractions[\"VolumeChange\"] = 3] = \"VolumeChange\";\n})(MediaInteractions || (MediaInteractions = {}));\nvar ReplayerEvents;\n(function (ReplayerEvents) {\n ReplayerEvents[\"Start\"] = \"start\";\n ReplayerEvents[\"Pause\"] = \"pause\";\n ReplayerEvents[\"Resume\"] = \"resume\";\n ReplayerEvents[\"Resize\"] = \"resize\";\n ReplayerEvents[\"Finish\"] = \"finish\";\n ReplayerEvents[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents[\"EventCast\"] = \"event-cast\";\n ReplayerEvents[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents[\"Flush\"] = \"flush\";\n ReplayerEvents[\"StateChange\"] = \"state-change\";\n ReplayerEvents[\"PlayBack\"] = \"play-back\";\n})(ReplayerEvents || (ReplayerEvents = {}));\n\nexport { CanvasContext, EventType, IncrementalSource, MediaInteractions, MouseInteractions, ReplayerEvents };\n","import { IncrementalSource } from './types.js';\nimport { IGNORED_NODE, isShadowRoot, NodeType } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nfunction createMirror() {\n return {\n map: {},\n getId(n) {\n if (!n || !n.__sn) {\n return -1;\n }\n return n.__sn.id;\n },\n getNode(id) {\n return this.map[id] || null;\n },\n removeNodeFromMap(n) {\n const id = n.__sn && n.__sn.id;\n delete this.map[id];\n if (n.childNodes) {\n n.childNodes.forEach((child) => this.removeNodeFromMap(child));\n }\n },\n has(id) {\n return this.map.hasOwnProperty(id);\n },\n reset() {\n this.map = {};\n },\n };\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\n '\\r\\n' +\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n '\\r\\n' +\n 'or you can use record.mirror to access the mirror instance during recording.';\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n};\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === 'map') {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n}\nfunction throttle(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function (arg) {\n let now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n let remaining = wait - (now - previous);\n let context = this;\n let args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n }\n else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(target, key, isRevoked\n ? d\n : {\n set(value) {\n setTimeout(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n },\n });\n return () => hookSetter(target, key, original || {}, true);\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => { };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === 'function') {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original,\n },\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n }\n catch (_a) {\n return () => { };\n }\n}\nfunction getWindowHeight() {\n return (window.innerHeight ||\n (document.documentElement && document.documentElement.clientHeight) ||\n (document.body && document.body.clientHeight));\n}\nfunction getWindowWidth() {\n return (window.innerWidth ||\n (document.documentElement && document.documentElement.clientWidth) ||\n (document.body && document.body.clientWidth));\n}\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector) {\n if (!node) {\n return false;\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n let needBlock = false;\n const needUnblock = unblockSelector && node.matches(unblockSelector);\n if (typeof blockClass === 'string') {\n if (node.closest !== undefined) {\n needBlock =\n !needUnblock &&\n node.closest('.' + blockClass) !== null;\n }\n else {\n needBlock =\n !needUnblock && node.classList.contains(blockClass);\n }\n }\n else {\n !needUnblock &&\n node.classList.forEach((className) => {\n if (blockClass.test(className)) {\n needBlock = true;\n }\n });\n }\n if (!needBlock && blockSelector) {\n needBlock = node.matches(blockSelector);\n }\n return ((!needUnblock && needBlock) ||\n isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector));\n }\n if (node.nodeType === node.TEXT_NODE) {\n return isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector);\n }\n return isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector);\n}\nfunction isIgnored(n) {\n if ('__sn' in n) {\n return n.__sn.id === IGNORED_NODE;\n }\n return false;\n}\nfunction isAncestorRemoved(target, mirror) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror.getId(target);\n if (!mirror.has(id)) {\n return true;\n }\n if (target.parentNode &&\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror);\n}\nfunction isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype\n .forEach;\n }\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype\n .forEach;\n }\n if (!Node.prototype.contains) {\n Node.prototype.contains = function contains(node) {\n if (!(0 in arguments)) {\n throw new TypeError('1 argument is required');\n }\n do {\n if (this === node) {\n return true;\n }\n } while ((node = node && node.parentNode));\n return false;\n };\n }\n}\nclass TreeIndex {\n constructor() {\n this.reset();\n }\n add(mutation) {\n const parentTreeNode = this.indexes.get(mutation.parentId);\n const treeNode = {\n id: mutation.node.id,\n mutation,\n children: [],\n texts: [],\n attributes: [],\n };\n if (!parentTreeNode) {\n this.tree[treeNode.id] = treeNode;\n }\n else {\n treeNode.parent = parentTreeNode;\n parentTreeNode.children[treeNode.id] = treeNode;\n }\n this.indexes.set(treeNode.id, treeNode);\n }\n remove(mutation, mirror) {\n const parentTreeNode = this.indexes.get(mutation.parentId);\n const treeNode = this.indexes.get(mutation.id);\n const deepRemoveFromMirror = (id) => {\n this.removeIdSet.add(id);\n const node = mirror.getNode(id);\n node === null || node === void 0 ? void 0 : node.childNodes.forEach((childNode) => {\n if ('__sn' in childNode) {\n deepRemoveFromMirror(childNode.__sn.id);\n }\n });\n };\n const deepRemoveFromTreeIndex = (node) => {\n this.removeIdSet.add(node.id);\n Object.values(node.children).forEach((n) => deepRemoveFromTreeIndex(n));\n const _treeNode = this.indexes.get(node.id);\n if (_treeNode) {\n const _parentTreeNode = _treeNode.parent;\n if (_parentTreeNode) {\n delete _treeNode.parent;\n delete _parentTreeNode.children[_treeNode.id];\n this.indexes.delete(mutation.id);\n }\n }\n };\n if (!treeNode) {\n this.removeNodeMutations.push(mutation);\n deepRemoveFromMirror(mutation.id);\n }\n else if (!parentTreeNode) {\n delete this.tree[treeNode.id];\n this.indexes.delete(treeNode.id);\n deepRemoveFromTreeIndex(treeNode);\n }\n else {\n delete treeNode.parent;\n delete parentTreeNode.children[treeNode.id];\n this.indexes.delete(mutation.id);\n deepRemoveFromTreeIndex(treeNode);\n }\n }\n text(mutation) {\n const treeNode = this.indexes.get(mutation.id);\n if (treeNode) {\n treeNode.texts.push(mutation);\n }\n else {\n this.textMutations.push(mutation);\n }\n }\n attribute(mutation) {\n const treeNode = this.indexes.get(mutation.id);\n if (treeNode) {\n treeNode.attributes.push(mutation);\n }\n else {\n this.attributeMutations.push(mutation);\n }\n }\n scroll(d) {\n this.scrollMap.set(d.id, d);\n }\n input(d) {\n this.inputMap.set(d.id, d);\n }\n flush() {\n const { tree, removeNodeMutations, textMutations, attributeMutations, } = this;\n const batchMutationData = {\n source: IncrementalSource.Mutation,\n removes: removeNodeMutations,\n texts: textMutations,\n attributes: attributeMutations,\n adds: [],\n };\n const walk = (treeNode, removed) => {\n if (removed) {\n this.removeIdSet.add(treeNode.id);\n }\n batchMutationData.texts = batchMutationData.texts\n .concat(removed ? [] : treeNode.texts)\n .filter((m) => !this.removeIdSet.has(m.id));\n batchMutationData.attributes = batchMutationData.attributes\n .concat(removed ? [] : treeNode.attributes)\n .filter((m) => !this.removeIdSet.has(m.id));\n if (!this.removeIdSet.has(treeNode.id) &&\n !this.removeIdSet.has(treeNode.mutation.parentId) &&\n !removed) {\n batchMutationData.adds.push(treeNode.mutation);\n if (treeNode.children) {\n Object.values(treeNode.children).forEach((n) => walk(n, false));\n }\n }\n else {\n Object.values(treeNode.children).forEach((n) => walk(n, true));\n }\n };\n Object.values(tree).forEach((n) => walk(n, false));\n for (const id of this.scrollMap.keys()) {\n if (this.removeIdSet.has(id)) {\n this.scrollMap.delete(id);\n }\n }\n for (const id of this.inputMap.keys()) {\n if (this.removeIdSet.has(id)) {\n this.inputMap.delete(id);\n }\n }\n const scrollMap = new Map(this.scrollMap);\n const inputMap = new Map(this.inputMap);\n this.reset();\n return {\n mutationData: batchMutationData,\n scrollMap,\n inputMap,\n };\n }\n reset() {\n this.tree = [];\n this.indexes = new Map();\n this.removeNodeMutations = [];\n this.textMutations = [];\n this.attributeMutations = [];\n this.removeIdSet = new Set();\n this.scrollMap = new Map();\n this.inputMap = new Map();\n }\n idRemoved(id) {\n return this.removeIdSet.has(id);\n }\n}\nfunction queueToResolveTrees(queue) {\n const queueNodeMap = {};\n const putIntoMap = (m, parent) => {\n const nodeInTree = {\n value: m,\n parent,\n children: [],\n };\n queueNodeMap[m.node.id] = nodeInTree;\n return nodeInTree;\n };\n const queueNodeTrees = [];\n for (const mutation of queue) {\n const { nextId, parentId } = mutation;\n if (nextId && nextId in queueNodeMap) {\n const nextInTree = queueNodeMap[nextId];\n if (nextInTree.parent) {\n const idx = nextInTree.parent.children.indexOf(nextInTree);\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\n }\n else {\n const idx = queueNodeTrees.indexOf(nextInTree);\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\n }\n continue;\n }\n if (parentId in queueNodeMap) {\n const parentInTree = queueNodeMap[parentId];\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\n continue;\n }\n queueNodeTrees.push(putIntoMap(mutation, null));\n }\n return queueNodeTrees;\n}\nfunction iterateResolveTree(tree, cb) {\n cb(tree.value);\n for (let i = tree.children.length - 1; i >= 0; i--) {\n iterateResolveTree(tree.children[i], cb);\n }\n}\nfunction isIframeINode(node) {\n if ('__sn' in node) {\n return (node.__sn.type === NodeType.Element && node.__sn.tagName === 'iframe');\n }\n return false;\n}\nfunction getBaseDimension(node, rootIframe) {\n var _a, _b;\n const frameElement = (_b = (_a = node.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) === null || _b === void 0 ? void 0 : _b.frameElement;\n if (!frameElement || frameElement === rootIframe) {\n return {\n x: 0,\n y: 0,\n relativeScale: 1,\n absoluteScale: 1,\n };\n }\n const frameDimension = frameElement.getBoundingClientRect();\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\n const relativeScale = frameDimension.height / frameElement.clientHeight;\n return {\n x: frameDimension.x * frameBaseDimension.relativeScale +\n frameBaseDimension.x,\n y: frameDimension.y * frameBaseDimension.relativeScale +\n frameBaseDimension.y,\n relativeScale,\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\n };\n}\nfunction hasShadowRoot(n) {\n return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);\n}\n\nexport { TreeIndex, _mirror, createMirror, getBaseDimension, getWindowHeight, getWindowWidth, hasShadowRoot, hookSetter, isAncestorRemoved, isBlocked, isIframeINode, isIgnored, isTouchEvent, iterateResolveTree, on, patch, polyfill, queueToResolveTrees, throttle };\n","import { isShadowRoot, maskInputValue, transformAttribute, needMaskingText, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isAncestorRemoved, isIframeINode, hasShadowRoot } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\n return '__ln' in n;\n}\nclass DoubleLinkedList {\n constructor() {\n this.length = 0;\n this.head = null;\n }\n get(position) {\n if (position >= this.length) {\n throw new Error('Position outside of list range');\n }\n let current = this.head;\n for (let index = 0; index < position; index++) {\n current = (current === null || current === void 0 ? void 0 : current.next) || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null,\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n }\n else if (n.nextSibling &&\n isNodeInLinkedList(n.nextSibling) &&\n n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n }\n else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n this.length++;\n }\n removeNode(n) {\n const current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n }\n }\n else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nfunction isINode(n) {\n return '__sn' in n;\n}\nclass MutationBuffer {\n constructor() {\n this.frozen = false;\n this.locked = false;\n this.texts = [];\n this.attributes = [];\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.processMutations = (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n };\n this.emit = () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n) => {\n var _a, _b, _c, _d, _e;\n const shadowHost = n.getRootNode\n ? (_a = n.getRootNode()) === null || _a === void 0 ? void 0 : _a.host\n : null;\n let rootShadowHost = shadowHost;\n while ((_c = (_b = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _b === void 0 ? void 0 : _b.call(rootShadowHost)) === null || _c === void 0 ? void 0 : _c.host)\n rootShadowHost =\n ((_e = (_d = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _d === void 0 ? void 0 : _d.call(rootShadowHost)) === null || _e === void 0 ? void 0 : _e.host) ||\n null;\n const notInDoc = !this.doc.contains(n) &&\n (!rootShadowHost || !this.doc.contains(rootShadowHost));\n if (!n.parentNode || notInDoc) {\n return;\n }\n const parentId = isShadowRoot(n.parentNode)\n ? this.mirror.getId(shadowHost)\n : this.mirror.getId(n.parentNode);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n let sn = serializeNodeWithId(n, {\n doc: this.doc,\n map: this.mirror.map,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n unblockSelector: this.unblockSelector,\n maskTextClass: this.maskTextClass,\n maskTextSelector: this.maskTextSelector,\n unmaskTextSelector: this.unmaskTextSelector,\n maskInputSelector: this.maskInputSelector,\n unmaskInputSelector: this.unmaskInputSelector,\n skipChild: true,\n inlineStylesheet: this.inlineStylesheet,\n maskAllText: this.maskAllText,\n maskInputOptions: this.maskInputOptions,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isIframeINode(currentN)) {\n this.iframeManager.addIframe(currentN);\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n this.iframeManager.attachIframe(iframe, childSn);\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn,\n });\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n of this.movedSet) {\n if (isParentRemoved(this.removes, n, this.mirror) &&\n !this.movedSet.has(n.parentNode)) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) &&\n !isParentRemoved(this.removes, n, this.mirror)) {\n pushAdd(n);\n }\n else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n }\n else {\n this.droppedSet.add(n);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(candidate.value.parentNode);\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n for (let index = addList.length - 1; index >= 0; index--) {\n const _node = addList.get(index);\n if (_node) {\n const parentId = this.mirror.getId(_node.value.parentNode);\n const nextId = getNextId(_node.value);\n if (parentId !== -1 && nextId !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts\n .map((text) => ({\n id: this.mirror.getId(text.node),\n value: text.value,\n }))\n .filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes\n .map((attribute) => ({\n id: this.mirror.getId(attribute.node),\n attributes: attribute.attributes,\n }))\n .filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds,\n };\n if (!payload.texts.length &&\n !payload.attributes.length &&\n !payload.removes.length &&\n !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.removes = [];\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n };\n this.processMutation = (m) => {\n if (isIgnored(m.target)) {\n return;\n }\n switch (m.type) {\n case 'characterData': {\n const value = m.target.textContent;\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextSelector, this.maskAllText) && value\n ? this.maskTextFn\n ? this.maskTextFn(value)\n : value.replace(/[\\S]/g, '*')\n : value,\n node: m.target,\n });\n }\n break;\n }\n case 'attributes': {\n const target = m.target;\n let value = target.getAttribute(m.attributeName);\n if (m.attributeName === 'value') {\n value = maskInputValue({\n input: target,\n maskInputSelector: this.maskInputSelector,\n unmaskInputSelector: this.unmaskInputSelector,\n maskInputOptions: this.maskInputOptions,\n tagName: target.tagName,\n type: target.getAttribute('type'),\n value,\n maskInputFn: this.maskInputFn,\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) || value === m.oldValue) {\n return;\n }\n let item = this.attributes.find((a) => a.node === m.target);\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n };\n this.attributes.push(item);\n }\n if (m.attributeName === 'type' &&\n target.tagName === 'INPUT' &&\n (m.oldValue || '').toLowerCase() === 'password') {\n target.setAttribute('data-rr-is-password', 'true');\n }\n if (m.attributeName === 'style') {\n const old = this.doc.createElement('span');\n if (m.oldValue) {\n old.setAttribute('style', m.oldValue);\n }\n if (item.attributes.style === undefined ||\n item.attributes.style === null) {\n item.attributes.style = {};\n }\n try {\n const styleObj = item.attributes.style;\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) ||\n newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === '') {\n styleObj[pname] = newValue;\n }\n else {\n styleObj[pname] = [newValue, newPriority];\n }\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === '') {\n styleObj[pname] = false;\n }\n }\n }\n catch (error) {\n console.warn('[rrweb] Error when parsing update to style attribute:', error);\n }\n }\n else {\n const element = m.target;\n item.attributes[m.attributeName] = transformAttribute(this.doc, element, element.tagName, m.attributeName, value, this.maskAllText, this.unmaskTextSelector, this.maskTextFn);\n }\n break;\n }\n case 'childList': {\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target)\n ? this.mirror.getId(m.target.host)\n : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) || isIgnored(n)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n }\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) &&\n this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n }\n else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) ? true : undefined,\n });\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n };\n this.genAdds = (n, target) => {\n if (target && isBlocked(target, this.blockClass, this.blockSelector, this.unblockSelector)) {\n return;\n }\n if (isINode(n)) {\n if (isIgnored(n)) {\n return;\n }\n this.movedSet.add(n);\n let targetId = null;\n if (target && isINode(target)) {\n targetId = target.__sn.id;\n }\n if (targetId) {\n this.movedMap[moveKey(n.__sn.id, targetId)] = true;\n }\n }\n else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector))\n n.childNodes.forEach((childN) => this.genAdds(childN));\n };\n }\n init(options) {\n [\n 'mutationCb',\n 'blockClass',\n 'blockSelector',\n 'unblockSelector',\n 'maskTextClass',\n 'maskTextSelector',\n 'unmaskTextSelector',\n 'maskInputSelector',\n 'unmaskInputSelector',\n 'inlineStylesheet',\n 'maskAllText',\n 'maskInputOptions',\n 'maskTextFn',\n 'maskInputFn',\n 'recordCanvas',\n 'inlineImages',\n 'slimDOMOptions',\n 'doc',\n 'mirror',\n 'iframeManager',\n 'shadowDomManager',\n 'canvasManager',\n ].forEach((key) => {\n this[key] = options[key];\n });\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n }\n}\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction isParentRemoved(removes, n, mirror) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n const parentId = mirror.getId(parentNode);\n if (removes.some((r) => r.id === parentId)) {\n return true;\n }\n return isParentRemoved(removes, parentNode, mirror);\n}\nfunction isAncestorInSet(set, n) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return isAncestorInSet(set, parentNode);\n}\n\nexport { MutationBuffer as default };\n","const callbackWrapper = (cb) => {\n const rrwebWrapped = (...rest) => {\n try {\n return cb(...rest);\n }\n catch (error) {\n try {\n error.__rrweb__ = true;\n }\n catch (_a) {\n }\n throw error;\n }\n };\n return rrwebWrapped;\n};\n\nexport { callbackWrapper };\n","import { getInputType, getInputValue, hasInputMaskOptions, maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isBlocked, hookSetter, patch, isTouchEvent, getWindowHeight, getWindowWidth } from '../utils.js';\nimport { MouseInteractions, IncrementalSource } from '../types.js';\nimport MutationBuffer from './mutation.js';\nimport { callbackWrapper } from '../sentry/callbackWrapper.js';\n\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if ('composedPath' in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n }\n else if ('path' in event && event.path.length) {\n return event.path[0];\n }\n }\n catch (_a) { }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n var _a, _b;\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n let mutationObserverCtor = window.MutationObserver ||\n window.__rrMutationObserver;\n const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');\n if (angularZoneSymbol &&\n window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\n if (options.onMutation && options.onMutation(mutations) === false) {\n return;\n }\n mutationBuffer.processMutations(mutations);\n }));\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n });\n return observer;\n}\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\n if (sampling.mousemove === false) {\n return () => { };\n }\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\n ? sampling.mousemoveCallback\n : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle((source) => {\n const totalOffset = Date.now() - timeBaseline;\n callbackWrapper(mousemoveCb)(positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }), source);\n positions = [];\n timeBaseline = null;\n }, callbackThreshold);\n const updatePosition = throttle((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = isTouchEvent(evt)\n ? evt.changedTouches[0]\n : evt;\n if (!timeBaseline) {\n timeBaseline = Date.now();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror.getId(target),\n timeOffset: Date.now() - timeBaseline,\n });\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n ? IncrementalSource.Drag\n : evt instanceof MouseEvent\n ? IncrementalSource.MouseMove\n : IncrementalSource.TouchMove);\n }, threshold, {\n trailing: false,\n });\n const handlers = [\n on('mousemove', callbackWrapper(updatePosition), doc),\n on('touchmove', callbackWrapper(updatePosition), doc),\n on('drag', callbackWrapper(updatePosition), doc),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n if (sampling.mouseInteraction === false) {\n return () => { };\n }\n const disableMap = sampling.mouseInteraction === true ||\n sampling.mouseInteraction === undefined\n ? {}\n : sampling.mouseInteraction;\n const handlers = [];\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const e = isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror.getId(target);\n const { clientX, clientY } = e;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[eventKey],\n id,\n x: clientX,\n y: clientY,\n });\n };\n };\n Object.keys(MouseInteractions)\n .filter((key) => Number.isNaN(Number(key)) &&\n !key.endsWith('_Departed') &&\n disableMap[key] !== false)\n .forEach((eventKey) => {\n const eventName = eventKey.toLowerCase();\n const handler = callbackWrapper(getHandler(eventKey));\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n const updatePosition = throttle((evt) => {\n const target = getEventTarget(evt);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const id = mirror.getId(target);\n if (target === doc) {\n const scrollEl = (doc.scrollingElement || doc.documentElement);\n callbackWrapper(scrollCb)({\n id,\n x: scrollEl.scrollLeft,\n y: scrollEl.scrollTop,\n });\n }\n else {\n callbackWrapper(scrollCb)({\n id,\n x: target.scrollLeft,\n y: target.scrollTop,\n });\n }\n }, sampling.scroll || 100);\n return on('scroll', callbackWrapper(updatePosition), doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb, }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = throttle(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n callbackWrapper(viewportResizeCb)({\n width: Number(width),\n height: Number(height),\n });\n lastH = height;\n lastW = width;\n }\n }, 200);\n return on('resize', callbackWrapper(updateDimension), window);\n}\nfunction wrapEventWithUserTriggeredFlag(v, enable) {\n const value = Object.assign({}, v);\n if (!enable)\n delete value.userTriggered;\n return value;\n}\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nconst lastInputValueMap = new WeakMap();\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputSelector, unmaskInputSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const tagName = target && target.tagName;\n const userTriggered = event.isTrusted;\n if (tagName === 'OPTION')\n target = target.parentElement;\n if (!target ||\n !tagName ||\n INPUT_TAGS.indexOf(tagName) < 0 ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const el = target;\n const type = getInputType(el);\n if (el.classList.contains(ignoreClass) ||\n (ignoreSelector && el.matches(ignoreSelector))) {\n return;\n }\n let text = getInputValue(el, tagName, type);\n let isChecked = false;\n if (type === 'radio' || type === 'checkbox') {\n isChecked = target.checked;\n }\n if (hasInputMaskOptions({\n maskInputOptions,\n maskInputSelector,\n tagName,\n type,\n })) {\n text = maskInputValue({\n input: el,\n maskInputOptions,\n maskInputSelector,\n unmaskInputSelector,\n tagName,\n type,\n value: text,\n maskInputFn,\n });\n }\n cbWithDedup(target, callbackWrapper(wrapEventWithUserTriggeredFlag)({ text, isChecked, userTriggered }, userTriggeredOnInput));\n const name = target.name;\n if (type === 'radio' && name && isChecked) {\n doc\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\n .forEach((el) => {\n if (el !== target) {\n const text = maskInputValue({\n input: el,\n maskInputOptions,\n maskInputSelector,\n unmaskInputSelector,\n tagName,\n type,\n value: getInputValue(el, tagName, type),\n maskInputFn,\n });\n cbWithDedup(el, callbackWrapper(wrapEventWithUserTriggeredFlag)({\n text,\n isChecked: !isChecked,\n userTriggered: false,\n }, userTriggeredOnInput));\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue ||\n lastInputValue.text !== v.text ||\n lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror.getId(target);\n inputCb(Object.assign(Object.assign({}, v), { id }));\n }\n }\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\n const propertyDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');\n const hookProperties = [\n [HTMLInputElement.prototype, 'value'],\n [HTMLInputElement.prototype, 'checked'],\n [HTMLSelectElement.prototype, 'value'],\n [HTMLTextAreaElement.prototype, 'value'],\n [HTMLSelectElement.prototype, 'selectedIndex'],\n [HTMLOptionElement.prototype, 'selected'],\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\n set() {\n callbackWrapper(eventHandler)({ target: this });\n },\n })));\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if ((hasNestedCSSRule('CSSGroupingRule') &&\n childRule.parentRule instanceof CSSGroupingRule) ||\n (hasNestedCSSRule('CSSMediaRule') &&\n childRule.parentRule instanceof CSSMediaRule) ||\n (hasNestedCSSRule('CSSSupportsRule') &&\n childRule.parentRule instanceof CSSSupportsRule) ||\n (hasNestedCSSRule('CSSConditionRule') &&\n childRule.parentRule instanceof CSSConditionRule)) {\n const rules = Array.from(childRule.parentRule.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n else {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => { };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const id = mirror.getId(thisArg.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n adds: [{ rule, index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const id = mirror.getId(thisArg.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n removes: [{ index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n }\n else {\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n insertRule: type.prototype.insertRule,\n deleteRule: type.prototype.deleteRule,\n };\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const id = mirror.getId(thisArg.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index || 0,\n ],\n },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const id = mirror.getId(thisArg.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index] },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror }, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n var _a, _b;\n const [property, value, priority] = argumentsList;\n const id = mirror.getId((_b = (_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id,\n set: {\n property,\n value,\n priority,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n var _a, _b;\n const [property] = argumentsList;\n const id = mirror.getId((_b = (_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id,\n remove: {\n property,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, }) {\n const handler = (type) => throttle(callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const { currentTime, volume, muted } = target;\n mediaInteractionCb({\n type,\n id: mirror.getId(target),\n currentTime,\n volume,\n muted,\n });\n }), sampling.media || 500);\n const handlers = [\n on('play', handler(0)),\n on('pause', handler(1)),\n on('seeked', handler(2)),\n on('volumechange', handler(3)),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => { };\n }\n const handlers = [];\n const fontMap = new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n const fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== 'string',\n descriptors,\n fontSource: typeof source === 'string'\n ? source\n :\n JSON.stringify(Array.from(new Uint8Array(source))),\n });\n return fontFace;\n };\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\n return function (fontFace) {\n setTimeout(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }, 0);\n return original.apply(this, [fontFace]);\n };\n });\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction mergeHooks(o, hooks) {\n const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, } = o;\n o.mutationCb = (...p) => {\n if (hooks.mutation) {\n hooks.mutation(...p);\n }\n mutationCb(...p);\n };\n o.mousemoveCb = (...p) => {\n if (hooks.mousemove) {\n hooks.mousemove(...p);\n }\n mousemoveCb(...p);\n };\n o.mouseInteractionCb = (...p) => {\n if (hooks.mouseInteraction) {\n hooks.mouseInteraction(...p);\n }\n mouseInteractionCb(...p);\n };\n o.scrollCb = (...p) => {\n if (hooks.scroll) {\n hooks.scroll(...p);\n }\n scrollCb(...p);\n };\n o.viewportResizeCb = (...p) => {\n if (hooks.viewportResize) {\n hooks.viewportResize(...p);\n }\n viewportResizeCb(...p);\n };\n o.inputCb = (...p) => {\n if (hooks.input) {\n hooks.input(...p);\n }\n inputCb(...p);\n };\n o.mediaInteractionCb = (...p) => {\n if (hooks.mediaInteaction) {\n hooks.mediaInteaction(...p);\n }\n mediaInteractionCb(...p);\n };\n o.styleSheetRuleCb = (...p) => {\n if (hooks.styleSheetRule) {\n hooks.styleSheetRule(...p);\n }\n styleSheetRuleCb(...p);\n };\n o.styleDeclarationCb = (...p) => {\n if (hooks.styleDeclaration) {\n hooks.styleDeclaration(...p);\n }\n styleDeclarationCb(...p);\n };\n o.canvasMutationCb = (...p) => {\n if (hooks.canvasMutation) {\n hooks.canvasMutation(...p);\n }\n canvasMutationCb(...p);\n };\n o.fontCb = (...p) => {\n if (hooks.font) {\n hooks.font(...p);\n }\n fontCb(...p);\n };\n}\nfunction initObservers(o, hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => { };\n }\n mergeHooks(o, hooks);\n const mutationObserver = initMutationObserver(o, o.doc);\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o);\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n const styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow,\n });\n const fontObserver = o.collectFonts ? initFontObserver(o) : () => { };\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n mutationObserver.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n try {\n styleSheetObserver();\n styleDeclarationObserver();\n }\n catch (e) {\n }\n fontObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== 'undefined';\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(typeof window[prop] !== 'undefined' &&\n window[prop].prototype &&\n 'insertRule' in window[prop].prototype &&\n 'deleteRule' in window[prop].prototype);\n}\n\nexport { INPUT_TAGS, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n","/*\n * base64-arraybuffer 1.0.2 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n","class IframeManager {\n constructor(options) {\n this.iframes = new WeakMap();\n this.mutationCb = options.mutationCb;\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n attachIframe(iframeEl, childSn) {\n var _a;\n this.mutationCb({\n adds: [\n {\n parentId: iframeEl.__sn.id,\n nextId: null,\n node: childSn,\n },\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true,\n });\n (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);\n }\n}\n\nexport { IframeManager };\n","import { initMutationObserver, initScrollObserver } from './observer.js';\nimport { patch } from '../utils.js';\n\nclass ShadowDomManager {\n constructor(options) {\n this.restorePatches = [];\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n const manager = this;\n this.restorePatches.push(patch(HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n const shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager.addShadowRoot(this.shadowRoot, this.ownerDocument);\n return shadowRoot;\n };\n }));\n }\n addShadowRoot(shadowRoot, doc) {\n initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);\n initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));\n }\n observeAttachShadow(iframeElement) {\n if (iframeElement.contentWindow) {\n const manager = this;\n this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n const shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);\n return shadowRoot;\n };\n }));\n }\n }\n reset() {\n this.restorePatches.forEach((restorePatch) => restorePatch());\n }\n}\n\nexport { ShadowDomManager };\n","import { encode } from './../../../../../../ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js';\n\nconst webGLVarMap = new Map();\nfunction variableListFor(ctx, ctor) {\n let contextMap = webGLVarMap.get(ctx);\n if (!contextMap) {\n contextMap = new Map();\n webGLVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n if (!value ||\n !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))\n return;\n const name = value.constructor.name;\n const list = variableListFor(ctx, name);\n let index = list.indexOf(value);\n if (index === -1) {\n index = list.length;\n list.push(value);\n }\n return index;\n};\nfunction serializeArg(value, win, ctx) {\n if (value instanceof Array) {\n return value.map((arg) => serializeArg(arg, win, ctx));\n }\n else if (value === null) {\n return value;\n }\n else if (value instanceof Float32Array ||\n value instanceof Float64Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Uint8Array ||\n value instanceof Uint16Array ||\n value instanceof Int16Array ||\n value instanceof Int8Array ||\n value instanceof Uint8ClampedArray) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [Object.values(value)],\n };\n }\n else if (value instanceof ArrayBuffer) {\n const name = value.constructor.name;\n const base64 = encode(value);\n return {\n rr_type: name,\n base64,\n };\n }\n else if (value instanceof DataView) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.buffer, win, ctx),\n value.byteOffset,\n value.byteLength,\n ],\n };\n }\n else if (value instanceof HTMLImageElement) {\n const name = value.constructor.name;\n const { src } = value;\n return {\n rr_type: name,\n src,\n };\n }\n else if (value instanceof ImageData) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [serializeArg(value.data, win, ctx), value.width, value.height],\n };\n }\n else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\n const name = value.constructor.name;\n const index = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name,\n index: index,\n };\n }\n return value;\n}\nconst serializeArgs = (args, win, ctx) => {\n return [...args].map((arg) => serializeArg(arg, win, ctx));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n const webGLConstructorNames = [\n 'WebGLActiveInfo',\n 'WebGLBuffer',\n 'WebGLFramebuffer',\n 'WebGLProgram',\n 'WebGLRenderbuffer',\n 'WebGLShader',\n 'WebGLShaderPrecisionFormat',\n 'WebGLTexture',\n 'WebGLUniformLocation',\n 'WebGLVertexArrayObject',\n 'WebGLVertexArrayObjectOES',\n ];\n const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');\n return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));\n};\n\nexport { isInstanceOfWebGLObject, saveWebGLVar, serializeArg, serializeArgs, variableListFor };\n","import { CanvasContext } from '../../../types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\nimport { saveWebGLVar, serializeArgs } from './serialize-args.js';\n\nfunction patchGLPrototype(prototype, type, cb, blockClass, unblockSelector, blockSelector, mirror, win) {\n const handlers = [];\n const props = Object.getOwnPropertyNames(prototype);\n for (const prop of props) {\n try {\n if (typeof prototype[prop] !== 'function') {\n continue;\n }\n const restoreHandler = patch(prototype, prop, function (original) {\n return function (...args) {\n const result = original.apply(this, args);\n saveWebGLVar(result, win, prototype);\n if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector)) {\n const id = mirror.getId(this.canvas);\n const recordArgs = serializeArgs([...args], win, prototype);\n const mutation = {\n type,\n property: prop,\n args: recordArgs,\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n const hookHandler = hookSetter(prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type,\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, unblockSelector, mirror) {\n const handlers = [];\n handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, unblockSelector, mirror, win));\n if (typeof win.WebGL2RenderingContext !== 'undefined') {\n handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, unblockSelector, mirror, win));\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nexport { initCanvasWebGLMutationObserver as default };\n","import { snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, on, createMirror, getWindowWidth, getWindowHeight, isIframeINode, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../types.js';\nimport { IframeManager } from './iframe-manager.js';\nimport { ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManager } from './observers/canvas/canvas-manager.js';\nimport { callbackWrapper } from '../sentry/callbackWrapper.js';\n\nfunction wrapEvent(e) {\n return Object.assign(Object.assign({}, e), { timestamp: Date.now() });\n}\nlet wrappedEmit;\nlet takeFullSnapshot;\nconst mirror = createMirror();\nfunction record(options = {}) {\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, maskInputSelector = null, unmaskTextSelector = null, unmaskInputSelector = null, inlineStylesheet = true, maskAllText = false, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, mousemoveWait, recordCanvas = false, userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, onMutation, } = options;\n if (!emit) {\n throw new Error('emit function is required');\n }\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\n sampling.mousemove = mousemoveWait;\n }\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n radio: true,\n checkbox: true,\n }\n : _maskInputOptions !== undefined\n ? _maskInputOptions\n : {};\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\n ? {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n headMetaAuthorship: _slimDOMOptions === 'all',\n headMetaDescKeywords: _slimDOMOptions === 'all',\n }\n : _slimDOMOptions\n ? _slimDOMOptions\n : {};\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (e, isCheckout) => {\n var _a;\n if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&\n e.type !== EventType.FullSnapshot &&\n !(e.type === EventType.IncrementalSnapshot &&\n e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n emit(eventProcessor(e), isCheckout);\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n }\n else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation &&\n e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms &&\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Mutation }, m),\n }));\n };\n const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Scroll }, p),\n }));\n const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),\n }));\n const iframeManager = new IframeManager({\n mutationCb: wrappedMutationEmit,\n });\n const canvasManager = new CanvasManager({\n recordCanvas,\n mutationCb: wrappedCanvasMutationEmit,\n win: window,\n blockClass,\n blockSelector,\n unblockSelector,\n mirror,\n });\n const shadowDomManager = new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n onMutation,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n inlineStylesheet,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n canvasManager,\n },\n mirror,\n });\n takeFullSnapshot = (isCheckout = false) => {\n var _a, _b, _c, _d;\n wrappedEmit(wrapEvent({\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight(),\n },\n }), isCheckout);\n mutationBuffers.forEach((buf) => buf.lock());\n const [node, idNodeMap] = snapshot(document, {\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n inlineStylesheet,\n maskAllText,\n maskAllInputs: maskInputOptions,\n maskTextFn,\n slimDOM: slimDOMOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n) => {\n if (isIframeINode(n)) {\n iframeManager.addIframe(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n shadowDomManager.observeAttachShadow(iframe);\n },\n keepIframeSrcFn,\n });\n if (!node) {\n return console.warn('Failed to snapshot the document');\n }\n mirror.map = idNodeMap;\n wrappedEmit(wrapEvent({\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: {\n left: window.pageXOffset !== undefined\n ? window.pageXOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||\n ((_b = (_a = document === null || document === void 0 ? void 0 : document.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollLeft) ||\n 0,\n top: window.pageYOffset !== undefined\n ? window.pageYOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||\n ((_d = (_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.parentElement) === null || _d === void 0 ? void 0 : _d.scrollTop) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollTop) ||\n 0,\n },\n },\n }));\n mutationBuffers.forEach((buf) => buf.unlock());\n };\n try {\n const handlers = [];\n handlers.push(on('DOMContentLoaded', () => {\n wrappedEmit(wrapEvent({\n type: EventType.DomContentLoaded,\n data: {},\n }));\n }));\n const observe = (doc) => {\n var _a;\n return callbackWrapper(initObservers)({\n onMutation,\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions,\n },\n })),\n mouseInteractionCb: (d) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),\n })),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.ViewportResize }, d),\n })),\n inputCb: (v) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Input }, v),\n })),\n mediaInteractionCb: (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),\n })),\n styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),\n })),\n styleDeclarationCb: (r) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),\n })),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Font }, p),\n })),\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskAllText,\n maskInputFn,\n maskTextFn,\n blockSelector,\n unblockSelector,\n slimDOMOptions,\n mirror,\n iframeManager,\n shadowDomManager,\n canvasManager,\n plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit(wrapEvent({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload,\n },\n })),\n }))) || [],\n }, hooks);\n };\n iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n }\n catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n };\n if (document.readyState === 'interactive' ||\n document.readyState === 'complete') {\n init();\n }\n else {\n handlers.push(on('load', () => {\n wrappedEmit(wrapEvent({\n type: EventType.Load,\n data: {},\n }));\n init();\n }, window));\n }\n return () => {\n handlers.forEach((h) => h());\n };\n }\n catch (error) {\n console.warn(error);\n }\n}\nrecord.addCustomEvent = (tag, payload) => {\n if (!wrappedEmit) {\n throw new Error('please add custom event after start recording');\n }\n wrappedEmit(wrapEvent({\n type: EventType.Custom,\n data: {\n tag,\n payload,\n },\n }));\n};\nrecord.freezePage = () => {\n mutationBuffers.forEach((buf) => buf.freeze());\n};\nrecord.takeFullSnapshot = (isCheckout) => {\n if (!takeFullSnapshot) {\n throw new Error('please take full snapshot after start recording');\n }\n takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\n\nexport { record as default };\n","import { __rest } from './../../../../../../ext/tslib/tslib.es6.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\n\nclass CanvasManager {\n reset() {\n this.pendingCanvasMutations.clear();\n this.resetObservers && this.resetObservers();\n }\n freeze() {\n this.frozen = true;\n }\n unfreeze() {\n this.frozen = false;\n }\n lock() {\n this.locked = true;\n }\n unlock() {\n this.locked = false;\n }\n constructor(options) {\n this.pendingCanvasMutations = new Map();\n this.rafStamps = { latestId: 0, invokeId: null };\n this.frozen = false;\n this.locked = false;\n this.processMutation = function (target, mutation) {\n const newFrame = this.rafStamps.invokeId &&\n this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n };\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n if (options.recordCanvas === true)\n this.initCanvasMutationObserver(options.win, options.blockClass, options.blockSelector, options.unblockSelector);\n }\n initCanvasMutationObserver(win, blockClass, unblockSelector, blockSelector) {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector);\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\n this.resetObservers = () => {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n };\n }\n startPendingCanvasMutationFlusher() {\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n startRAFTimestamping() {\n const setLatestRAFTimestamp = (timestamp) => {\n this.rafStamps.latestId = timestamp;\n requestAnimationFrame(setLatestRAFTimestamp);\n };\n requestAnimationFrame(setLatestRAFTimestamp);\n }\n flushPendingCanvasMutations() {\n this.pendingCanvasMutations.forEach((values, canvas) => {\n const id = this.mirror.getId(canvas);\n this.flushPendingCanvasMutationFor(canvas, id);\n });\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n flushPendingCanvasMutationFor(canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1)\n return;\n const values = valuesWithType.map((value) => {\n const rest = __rest(value, [\"type\"]);\n return rest;\n });\n const { type } = valuesWithType[0];\n this.mutationCb({ id, type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n }\n}\n\nexport { CanvasManager };\n","import { patch, isBlocked } from '../../../utils.js';\n\nfunction initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector) {\n const handlers = [];\n try {\n const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {\n return function (contextType, ...args) {\n if (!isBlocked(this, blockClass, blockSelector, unblockSelector)) {\n if (!('__context' in this))\n this.__context = contextType;\n }\n return original.apply(this, [contextType, ...args]);\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n console.error('failed to patch HTMLCanvasElement.prototype.getContext');\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nexport { initCanvasContextObserver as default };\n","import { CanvasContext } from '../../../types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\n\nfunction initCanvas2DMutationObserver(cb, win, blockClass, unblockSelector, blockSelector, mirror) {\n const handlers = [];\n const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);\n for (const prop of props2D) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {\n continue;\n }\n const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {\n return function (...args) {\n if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector)) {\n setTimeout(() => {\n const recordArgs = [...args];\n if (prop === 'drawImage') {\n if (recordArgs[0] &&\n recordArgs[0] instanceof HTMLCanvasElement) {\n const canvas = recordArgs[0];\n const ctx = canvas.getContext('2d');\n let imgd = ctx === null || ctx === void 0 ? void 0 : ctx.getImageData(0, 0, canvas.width, canvas.height);\n let pix = imgd === null || imgd === void 0 ? void 0 : imgd.data;\n recordArgs[0] = JSON.stringify(pix);\n }\n }\n cb(this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: recordArgs,\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nexport { initCanvas2DMutationObserver as default };\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\n\nexport { __rest };\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../../types';\n\n/**\n * Add a breadcrumb event to replay.\n */\nexport function addBreadcrumbEvent(replay: ReplayContainer, breadcrumb: Breadcrumb): void {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category as string)) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n void replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1_000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n","import type { INode } from '@sentry-internal/rrweb-snapshot';\n\nexport interface DomHandlerData {\n name: string;\n event: Node | { target: EventTarget };\n}\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nexport function getClickTargetNode(event: DomHandlerData['event'] | MouseEvent): Node | INode | null {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n const closestInteractive = target.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || target;\n}\n\n/** Get the event target node. */\nexport function getTargetNode(event: Node | { target: EventTarget | null }): Node | INode | null {\n if (isEventWithTarget(event)) {\n return event.target as Node | null;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event: unknown): event is { target: EventTarget | null } {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n","import { fill } from '@sentry/utils';\n\nimport { WINDOW } from '../../constants';\n\ntype WindowOpenHandler = () => void;\n\nlet handlers: undefined | WindowOpenHandler[];\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nexport function onWindowOpen(cb: WindowOpenHandler): () => void {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers as WindowOpenHandler[]).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen(): void {\n fill(WINDOW, 'open', function (originalWindowOpen: () => void): () => void {\n return function (...args: unknown[]): void {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n","import type { Breadcrumb } from '@sentry/types';\n\nimport { WINDOW } from '../constants';\nimport type { MultiClickFrame, ReplayClickDetector, ReplayContainer, SlowClickConfig, SlowClickFrame } from '../types';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClickTargetNode } from './util/domUtils';\nimport { onWindowOpen } from './util/onWindowOpen';\n\ntype ClickBreadcrumb = Breadcrumb & {\n timestamp: number;\n};\n\ninterface Click {\n timestamp: number;\n mutationAfter?: number;\n scrollAfter?: number;\n clickBreadcrumb: ClickBreadcrumb;\n clickCount: number;\n node: HTMLElement;\n}\n\n/** Handle a click. */\nexport function handleClick(clickDetector: ReplayClickDetector, clickBreadcrumb: Breadcrumb, node: HTMLElement): void {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nexport class ClickDetector implements ReplayClickDetector {\n // protected for testing\n protected _lastMutation = 0;\n protected _lastScroll = 0;\n\n private _clicks: Click[] = [];\n private _teardown: undefined | (() => void);\n\n private _multiClickTimeout: number;\n private _threshold: number;\n private _scollTimeout: number;\n private _timeout: number;\n private _ignoreSelector: string;\n\n private _replay: ReplayContainer;\n private _checkClickTimeout?: ReturnType;\n private _addBreadcrumbEvent: typeof addBreadcrumbEvent;\n\n public constructor(\n replay: ReplayContainer,\n slowClickConfig: SlowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._multiClickTimeout = slowClickConfig.multiClickTimeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n public addListeners(): void {\n const mutationHandler = (): void => {\n this._lastMutation = nowInSeconds();\n };\n\n const scrollHandler = (): void => {\n this._lastScroll = nowInSeconds();\n };\n\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n const clickHandler = (event: MouseEvent): void => {\n if (!event.target) {\n return;\n }\n\n const node = getClickTargetNode(event);\n if (node) {\n this._handleMultiClick(node as HTMLElement);\n }\n };\n\n const obs = new MutationObserver(mutationHandler);\n\n obs.observe(WINDOW.document.documentElement, {\n attributes: true,\n characterData: true,\n childList: true,\n subtree: true,\n });\n\n WINDOW.addEventListener('scroll', scrollHandler, { passive: true });\n WINDOW.addEventListener('click', clickHandler, { passive: true });\n\n this._teardown = () => {\n WINDOW.removeEventListener('scroll', scrollHandler);\n WINDOW.removeEventListener('click', clickHandler);\n cleanupWindowOpen();\n\n obs.disconnect();\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n public removeListeners(): void {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** Handle a click */\n public handleClick(breadcrumb: Breadcrumb, node: HTMLElement): void {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const click = this._getClick(node);\n\n if (click) {\n // this means a click on the same element was captured in the last 1s, so we consider this a multi click\n return;\n }\n\n const newClick: Click = {\n timestamp: breadcrumb.timestamp,\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Count multiple clicks on elements. */\n private _handleMultiClick(node: HTMLElement): void {\n const click = this._getClick(node);\n\n if (!click) {\n return;\n }\n\n click.clickCount++;\n }\n\n /** Try to get an existing click on the given element. */\n private _getClick(node: HTMLElement): Click | undefined {\n const now = nowInSeconds();\n\n // Find any click on the same element in the last second\n // If one exists, we consider this click as a double/triple/etc click\n return this._clicks.find(click => click.node === node && now - click.timestamp < this._multiClickTimeout);\n }\n\n /** Check the clicks that happened. */\n private _checkClicks(): void {\n const timedOutClicks: Click[] = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // If an action happens after the multi click threshold, we can skip waiting and handle the click right away\n const actionTime = click.scrollAfter || click.mutationAfter || 0;\n if (actionTime && actionTime >= this._multiClickTimeout) {\n timedOutClicks.push(click);\n return;\n }\n\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n this._generateBreadcrumbs(click);\n\n const pos = this._clicks.indexOf(click);\n if (pos !== -1) {\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n private _generateBreadcrumbs(click: Click): void {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb: SlowClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb: MultiClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n private _scheduleCheckClicks(): void {\n this._checkClickTimeout = setTimeout(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nexport function ignoreElement(node: HTMLElement, ignoreSelector: string): boolean {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is ClickBreadcrumb {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds(): number {\n return Date.now() / 1000;\n}\n","var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = n === null || n === void 0 ? void 0 : n.host;\n return Boolean(host && host.shadowRoot && host.shadowRoot === n);\n}\nfunction isInputTypeMasked({ maskInputOptions, tagName, type, }) {\n if (tagName.toLowerCase() === 'option') {\n tagName = 'select';\n }\n const actualType = typeof type === 'string' ? type.toLowerCase() : undefined;\n return (maskInputOptions[tagName.toLowerCase()] ||\n (actualType && maskInputOptions[actualType]) ||\n actualType === 'password' ||\n (tagName === 'input' && !type && maskInputOptions['text']));\n}\nfunction hasInputMaskOptions({ tagName, type, maskInputOptions, maskInputSelector, }) {\n return (maskInputSelector || isInputTypeMasked({ maskInputOptions, tagName, type }));\n}\nfunction maskInputValue({ input, maskInputSelector, unmaskInputSelector, maskInputOptions, tagName, type, value, maskInputFn, }) {\n let text = value || '';\n if (unmaskInputSelector && input.matches(unmaskInputSelector)) {\n return text;\n }\n if (input.hasAttribute('data-rr-is-password')) {\n type = 'password';\n }\n if (isInputTypeMasked({ maskInputOptions, tagName, type }) ||\n (maskInputSelector && input.matches(maskInputSelector))) {\n if (maskInputFn) {\n text = maskInputFn(text);\n }\n else {\n text = '*'.repeat(text.length);\n }\n }\n return text;\n}\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext('2d');\n if (!ctx)\n return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some((pixel) => pixel !== 0))\n return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute('data-rr-is-password')\n ? 'password'\n : type\n ? type.toLowerCase()\n : null;\n}\nfunction getInputValue(el, tagName, type) {\n typeof type === 'string' ? type.toLowerCase() : '';\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\n return el.getAttribute('value') || '';\n }\n return el.value;\n}\nfunction defineCustomElement(w, elementName) {\n try {\n if (!w.customElements.get(elementName)) {\n const CustomElement = w.HTMLElement;\n w.customElements.define(elementName, class extends CustomElement {\n });\n }\n }\n catch (_a) { }\n}\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\nconst IGNORED_NODE = -2;\nfunction defaultMaskFn(str) {\n return str ? str.replace(/[\\S]/g, '*') : '';\n}\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return 'form';\n }\n const processedTagName = element.tagName.toLowerCase().trim();\n if (tagNameRegex.test(processedTagName)) {\n return 'div';\n }\n return processedTagName;\n}\nfunction getCssRulesString(s) {\n try {\n const rules = s.rules || s.cssRules;\n return rules ? Array.from(rules).map(getCssRuleString).join('') : null;\n }\n catch (error) {\n return null;\n }\n}\nfunction getCssRuleString(rule) {\n let cssStringified = rule.cssText;\n if (isCSSImportRule(rule)) {\n try {\n cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;\n }\n catch (_a) {\n }\n }\n return validateStringifiedCssRule(cssStringified);\n}\nfunction validateStringifiedCssRule(cssStringified) {\n if (cssStringified.indexOf(':') > -1) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, '$1\\\\$2');\n }\n return cssStringified;\n}\nfunction isCSSImportRule(rule) {\n return 'styleSheet' in rule;\n}\nfunction stringifyStyleSheet(sheet) {\n return sheet.cssRules\n ? Array.from(sheet.cssRules)\n .map((rule) => rule.cssText ? validateStringifiedCssRule(rule.cssText) : '')\n .join('')\n : '';\n}\nfunction extractOrigin(url) {\n let origin = '';\n if (url.indexOf('//') > -1) {\n origin = url.split('/').slice(0, 3).join('/');\n }\n else {\n origin = url.split('/')[0];\n }\n origin = origin.split('?')[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst RELATIVE_PATH = /^(?!www\\.|(?:http|ftp)s?:\\/\\/|[A-Za-z]:\\\\|\\/\\/|#).*/;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || '';\n if (!filePath) {\n return origin;\n }\n if (!RELATIVE_PATH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === '/') {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split('/');\n const parts = filePath.split('/');\n stack.pop();\n for (const part of parts) {\n if (part === '.') {\n continue;\n }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\n });\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === '') {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars;\n let match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return '';\n }\n let output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === ',') {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n }\n else {\n let descriptorsStr = '';\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n let c = attributeValue.charAt(pos);\n if (c === '') {\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\n }\n else {\n if (c === ')') {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(', ');\n}\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === '') {\n return attributeValue;\n }\n const a = doc.createElement('a');\n a.href = attributeValue;\n return a.href;\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\n}\nfunction getHref() {\n const a = document.createElement('a');\n a.href = '';\n return a.href;\n}\nfunction transformAttribute(doc, element, _tagName, _name, value, maskAllText, unmaskTextSelector, maskTextFn) {\n if (!value) {\n return value;\n }\n const name = _name.toLowerCase();\n const tagName = _tagName.toLowerCase();\n if (name === 'src' || name === 'href') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset') {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style') {\n return absoluteToStylesheet(value, getHref());\n }\n else if (tagName === 'object' && name === 'data') {\n return absoluteToDoc(doc, value);\n }\n else if (maskAllText &&\n _shouldMaskAttribute(element, name, tagName, unmaskTextSelector)) {\n return maskTextFn ? maskTextFn(value) : defaultMaskFn(value);\n }\n return value;\n}\nfunction _shouldMaskAttribute(element, attribute, tagName, unmaskTextSelector) {\n if (unmaskTextSelector && element.matches(unmaskTextSelector)) {\n return false;\n }\n return (['placeholder', 'title', 'aria-label'].indexOf(attribute) > -1 ||\n (tagName === 'input' &&\n attribute === 'value' &&\n element.hasAttribute('type') &&\n ['submit', 'button'].indexOf(element.getAttribute('type').toLowerCase()) > -1));\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === 'string') {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < element.classList.length; eIndex++) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n return false;\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) {\n if (!node) {\n return false;\n }\n if (node.nodeType !== node.ELEMENT_NODE) {\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n }\n if (unmaskTextSelector) {\n if (node.matches(unmaskTextSelector) ||\n node.closest(unmaskTextSelector)) {\n return false;\n }\n }\n if (maskAllText) {\n return true;\n }\n if (typeof maskTextClass === 'string') {\n if (node.classList.contains(maskTextClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < node.classList.length; eIndex++) {\n const className = node.classList[eIndex];\n if (maskTextClass.test(className)) {\n return true;\n }\n }\n }\n if (maskTextSelector) {\n if (node.matches(maskTextSelector)) {\n return true;\n }\n }\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n }\n catch (error) {\n return;\n }\n if (readyState !== 'complete') {\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener('load', () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n iframeEl.src === '') {\n setTimeout(listener, 0);\n return;\n }\n iframeEl.addEventListener('load', listener);\n}\nfunction serializeNode(n, options) {\n var _a;\n const { doc, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, } = options;\n let rootId;\n if (doc.__sn) {\n const docId = doc.__sn.id;\n rootId = docId === 1 ? undefined : docId;\n }\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== 'CSS1Compat') {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode,\n rootId,\n };\n }\n else {\n return {\n type: NodeType.Document,\n childNodes: [],\n rootId,\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId,\n };\n case n.ELEMENT_NODE:\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n for (const { name, value } of Array.from(n.attributes)) {\n if (!skipAttribute(tagName, name)) {\n attributes[name] = transformAttribute(doc, n, tagName, name, value, maskAllText, unmaskTextSelector, maskTextFn);\n }\n }\n if (tagName === 'link' && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = getCssRulesString(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText ||\n n.textContent ||\n '').trim().length) {\n const cssText = getCssRulesString(n.sheet);\n if (cssText) {\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select' ||\n tagName === 'option') {\n const el = n;\n const type = getInputType(el);\n const value = getInputValue(el, tagName.toUpperCase(), type);\n const checked = n.checked;\n if (type !== 'submit' &&\n type !== 'button' &&\n value) {\n attributes.value = maskInputValue({\n input: el,\n type,\n tagName,\n value,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes.selected = true;\n }\n else {\n delete attributes.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n const blankCanvas = document.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === 'img' && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement('canvas');\n canvasCtx = canvasService.getContext('2d');\n }\n const image = n;\n const oldValue = image.crossOrigin;\n image.crossOrigin = 'anonymous';\n const recordInlineImage = () => {\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n catch (err) {\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\n }\n oldValue\n ? (attributes.crossOrigin = oldValue)\n : delete attributes.crossOrigin;\n };\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.onload = recordInlineImage;\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes.rr_mediaCurrentTime = n.currentTime;\n }\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n return {\n type: NodeType.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock,\n rootId,\n };\n case n.TEXT_NODE:\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\n textContent = stringifyStyleSheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref());\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n if (parentTagName === 'TEXTAREA' && textContent) {\n textContent = '';\n }\n else if (parentTagName === 'OPTION' && textContent) {\n const option = n.parentNode;\n textContent = maskInputValue({\n input: option,\n type: null,\n tagName: parentTagName,\n value: textContent,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n else if (!isStyle &&\n !isScript &&\n needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) &&\n textContent) {\n textContent = maskTextFn\n ? maskTextFn(textContent)\n : defaultMaskFn(textContent);\n }\n return {\n type: NodeType.Text,\n textContent: textContent || '',\n isStyle,\n rootId,\n };\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: '',\n rootId,\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: n.textContent || '',\n rootId,\n };\n default:\n return false;\n }\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined || maybeAttr === null) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n }\n else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n (sn.attributes.rel === 'preload' ||\n sn.attributes.rel === 'modulepreload') &&\n sn.attributes.as === 'script') ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n sn.attributes.href.endsWith('.js')))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const { doc, map, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, keepIframeSrcFn = () => false, } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n });\n if (!_serializedNode) {\n console.warn(n, 'not serialized');\n return null;\n }\n let id;\n if ('__sn' in n) {\n id = n.__sn.id;\n }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n n.__sn = serializedNode;\n if (id === IGNORED_NODE) {\n return null;\n }\n map[id] = n;\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n if (n.shadowRoot)\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document ||\n serializedNode.type === NodeType.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n _serializedNode.type === NodeType.Element &&\n _serializedNode.tagName === 'head') {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n };\n for (const childN of Array.from(n.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n) && n.shadowRoot) {\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedChildNode.isShadow = true;\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode && isShadowRoot(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(n, () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const { blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskInputSelector = null, unmaskInputSelector = null, maskAllText = false, maskAllInputs = false, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\n const idNodeMap = {};\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n }\n : maskAllInputs === false\n ? {}\n : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true,\n }\n : slimDOM === false\n ? {}\n : slimDOM;\n return [\n serializeNodeWithId(n, {\n doc: n,\n map: idNodeMap,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n }),\n idNodeMap,\n ];\n}\nfunction visitSnapshot(node, onVisit) {\n function walk(current) {\n onVisit(current);\n if (current.type === NodeType.Document ||\n current.type === NodeType.Element) {\n current.childNodes.forEach(walk);\n }\n }\n walk(node);\n}\nfunction cleanupSnapshot() {\n _id = 1;\n}\nfunction skipAttribute(tagName, attributeName, value) {\n return ((tagName === 'video' || tagName === 'audio') && attributeName === 'autoplay');\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\nfunction parse(css, options = {}) {\n let lineno = 1;\n let column = 1;\n function updatePosition(str) {\n const lines = str.match(/\\n/g);\n if (lines) {\n lineno += lines.length;\n }\n let i = str.lastIndexOf('\\n');\n column = i === -1 ? column + str.length : str.length - i;\n }\n function position() {\n const start = { line: lineno, column };\n return (node) => {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n class Position {\n constructor(start) {\n this.start = start;\n this.end = { line: lineno, column };\n this.source = options.source;\n }\n }\n Position.prototype.content = css;\n const errorsList = [];\n function error(msg) {\n const err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = css;\n if (options.silent) {\n errorsList.push(err);\n }\n else {\n throw err;\n }\n }\n function stylesheet() {\n const rulesList = rules();\n return {\n type: 'stylesheet',\n stylesheet: {\n source: options.source,\n rules: rulesList,\n parsingErrors: errorsList,\n },\n };\n }\n function open() {\n return match(/^{\\s*/);\n }\n function close() {\n return match(/^}/);\n }\n function rules() {\n let node;\n const rules = [];\n whitespace();\n comments(rules);\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\n if (node !== false) {\n rules.push(node);\n comments(rules);\n }\n }\n return rules;\n }\n function match(re) {\n const m = re.exec(css);\n if (!m) {\n return;\n }\n const str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n function whitespace() {\n match(/^\\s*/);\n }\n function comments(rules = []) {\n let c;\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n c = comment();\n }\n return rules;\n }\n function comment() {\n const pos = position();\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\n return;\n }\n let i = 2;\n while ('' !== css.charAt(i) &&\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\n ++i;\n }\n i += 2;\n if ('' === css.charAt(i - 1)) {\n return error('End of comment missing');\n }\n const str = css.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n css = css.slice(i);\n column += 2;\n return pos({\n type: 'comment',\n comment: str,\n });\n }\n function selector() {\n const m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n return trim(m[0])\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\n return m.replace(/,/g, '\\u200C');\n })\n .split(/\\s*(?![^(]*\\)),\\s*/)\n .map((s) => {\n return s.replace(/\\u200C/g, ',');\n });\n }\n function declaration() {\n const pos = position();\n let propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n const prop = trim(propMatch[0]);\n if (!match(/^:\\s*/)) {\n return error(`property missing ':'`);\n }\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\n const ret = pos({\n type: 'declaration',\n property: prop.replace(commentre, ''),\n value: val ? trim(val[0]).replace(commentre, '') : '',\n });\n match(/^[;\\s]*/);\n return ret;\n }\n function declarations() {\n const decls = [];\n if (!open()) {\n return error(`missing '{'`);\n }\n comments(decls);\n let decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n decl = declaration();\n }\n if (!close()) {\n return error(`missing '}'`);\n }\n return decls;\n }\n function keyframe() {\n let m;\n const vals = [];\n const pos = position();\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n if (!vals.length) {\n return;\n }\n return pos({\n type: 'keyframe',\n values: vals,\n declarations: declarations(),\n });\n }\n function atkeyframes() {\n const pos = position();\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\n if (!m) {\n return;\n }\n const vendor = m[1];\n m = match(/^([-\\w]+)\\s*/);\n if (!m) {\n return error('@keyframes missing name');\n }\n const name = m[1];\n if (!open()) {\n return error(`@keyframes missing '{'`);\n }\n let frame;\n let frames = comments();\n while ((frame = keyframe())) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n if (!close()) {\n return error(`@keyframes missing '}'`);\n }\n return pos({\n type: 'keyframes',\n name,\n vendor,\n keyframes: frames,\n });\n }\n function atsupports() {\n const pos = position();\n const m = match(/^@supports *([^{]+)/);\n if (!m) {\n return;\n }\n const supports = trim(m[1]);\n if (!open()) {\n return error(`@supports missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@supports missing '}'`);\n }\n return pos({\n type: 'supports',\n supports,\n rules: style,\n });\n }\n function athost() {\n const pos = position();\n const m = match(/^@host\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@host missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@host missing '}'`);\n }\n return pos({\n type: 'host',\n rules: style,\n });\n }\n function atmedia() {\n const pos = position();\n const m = match(/^@media *([^{]+)/);\n if (!m) {\n return;\n }\n const media = trim(m[1]);\n if (!open()) {\n return error(`@media missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@media missing '}'`);\n }\n return pos({\n type: 'media',\n media,\n rules: style,\n });\n }\n function atcustommedia() {\n const pos = position();\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n return pos({\n type: 'custom-media',\n name: trim(m[1]),\n media: trim(m[2]),\n });\n }\n function atpage() {\n const pos = position();\n const m = match(/^@page */);\n if (!m) {\n return;\n }\n const sel = selector() || [];\n if (!open()) {\n return error(`@page missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@page missing '}'`);\n }\n return pos({\n type: 'page',\n selectors: sel,\n declarations: decls,\n });\n }\n function atdocument() {\n const pos = position();\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n const vendor = trim(m[1]);\n const doc = trim(m[2]);\n if (!open()) {\n return error(`@document missing '{'`);\n }\n const style = comments().concat(rules());\n if (!close()) {\n return error(`@document missing '}'`);\n }\n return pos({\n type: 'document',\n document: doc,\n vendor,\n rules: style,\n });\n }\n function atfontface() {\n const pos = position();\n const m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(`@font-face missing '{'`);\n }\n let decls = comments();\n let decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(`@font-face missing '}'`);\n }\n return pos({\n type: 'font-face',\n declarations: decls,\n });\n }\n const atimport = _compileAtrule('import');\n const atcharset = _compileAtrule('charset');\n const atnamespace = _compileAtrule('namespace');\n function _compileAtrule(name) {\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\n return () => {\n const pos = position();\n const m = match(re);\n if (!m) {\n return;\n }\n const ret = { type: name };\n ret[name] = m[1].trim();\n return pos(ret);\n };\n }\n function atrule() {\n if (css[0] !== '@') {\n return;\n }\n return (atkeyframes() ||\n atmedia() ||\n atcustommedia() ||\n atsupports() ||\n atimport() ||\n atcharset() ||\n atnamespace() ||\n atdocument() ||\n atpage() ||\n athost() ||\n atfontface());\n }\n function rule() {\n const pos = position();\n const sel = selector();\n if (!sel) {\n return error('selector missing');\n }\n comments();\n return pos({\n type: 'rule',\n selectors: sel,\n declarations: declarations(),\n });\n }\n return addParent(stylesheet());\n}\nfunction trim(str) {\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\n}\nfunction addParent(obj, parent) {\n const isNode = obj && typeof obj.type === 'string';\n const childParent = isNode ? obj : parent;\n for (const k of Object.keys(obj)) {\n const value = obj[k];\n if (Array.isArray(value)) {\n value.forEach((v) => {\n addParent(v, childParent);\n });\n }\n else if (value && typeof value === 'object') {\n addParent(value, childParent);\n }\n }\n if (isNode) {\n Object.defineProperty(obj, 'parent', {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null,\n });\n }\n return obj;\n}\n\nconst tagMap = {\n script: 'noscript',\n altglyph: 'altGlyph',\n altglyphdef: 'altGlyphDef',\n altglyphitem: 'altGlyphItem',\n animatecolor: 'animateColor',\n animatemotion: 'animateMotion',\n animatetransform: 'animateTransform',\n clippath: 'clipPath',\n feblend: 'feBlend',\n fecolormatrix: 'feColorMatrix',\n fecomponenttransfer: 'feComponentTransfer',\n fecomposite: 'feComposite',\n feconvolvematrix: 'feConvolveMatrix',\n fediffuselighting: 'feDiffuseLighting',\n fedisplacementmap: 'feDisplacementMap',\n fedistantlight: 'feDistantLight',\n fedropshadow: 'feDropShadow',\n feflood: 'feFlood',\n fefunca: 'feFuncA',\n fefuncb: 'feFuncB',\n fefuncg: 'feFuncG',\n fefuncr: 'feFuncR',\n fegaussianblur: 'feGaussianBlur',\n feimage: 'feImage',\n femerge: 'feMerge',\n femergenode: 'feMergeNode',\n femorphology: 'feMorphology',\n feoffset: 'feOffset',\n fepointlight: 'fePointLight',\n fespecularlighting: 'feSpecularLighting',\n fespotlight: 'feSpotLight',\n fetile: 'feTile',\n feturbulence: 'feTurbulence',\n foreignobject: 'foreignObject',\n glyphref: 'glyphRef',\n lineargradient: 'linearGradient',\n radialgradient: 'radialGradient',\n};\nfunction getTagName(n) {\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\n if (tagName === 'link' && n.attributes._cssText) {\n tagName = 'style';\n }\n return tagName;\n}\nfunction escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\nfunction addHoverClass(cssText, cache) {\n const cachedStyle = cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.get(cssText);\n if (cachedStyle)\n return cachedStyle;\n const ast = parse(cssText, {\n silent: true,\n });\n if (!ast.stylesheet) {\n return cssText;\n }\n const selectors = [];\n ast.stylesheet.rules.forEach((rule) => {\n if ('selectors' in rule) {\n (rule.selectors || []).forEach((selector) => {\n if (HOVER_SELECTOR.test(selector)) {\n selectors.push(selector);\n }\n });\n }\n });\n if (selectors.length === 0) {\n return cssText;\n }\n const selectorMatcher = new RegExp(selectors\n .filter((selector, index) => selectors.indexOf(selector) === index)\n .sort((a, b) => b.length - a.length)\n .map((selector) => {\n return escapeRegExp(selector);\n })\n .join('|'), 'g');\n const result = cssText.replace(selectorMatcher, (selector) => {\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\n return `${selector}, ${newSelector}`;\n });\n cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.set(cssText, result);\n return result;\n}\nfunction createCache() {\n const stylesWithHoverClass = new Map();\n return {\n stylesWithHoverClass,\n };\n}\nfunction buildNode(n, options) {\n const { doc, hackCss, cache } = options;\n switch (n.type) {\n case NodeType.Document:\n return doc.implementation.createDocument(null, '', null);\n case NodeType.DocumentType:\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\n case NodeType.Element:\n const tagName = getTagName(n);\n let node;\n if (n.isSVG) {\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\n }\n else {\n node = doc.createElement(tagName);\n }\n for (const name in n.attributes) {\n if (!n.attributes.hasOwnProperty(name)) {\n continue;\n }\n let value = n.attributes[name];\n if (tagName === 'option' && name === 'selected' && value === false) {\n continue;\n }\n value =\n typeof value === 'boolean' || typeof value === 'number' || value === null ? '' : value;\n if (!name.startsWith('rr_')) {\n const isTextarea = tagName === 'textarea' && name === 'value';\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\n if (isRemoteOrDynamicCss && hackCss) {\n value = addHoverClass(value, cache);\n }\n if (isTextarea || isRemoteOrDynamicCss) {\n const child = doc.createTextNode(value);\n for (const c of Array.from(node.childNodes)) {\n if (c.nodeType === node.TEXT_NODE) {\n node.removeChild(c);\n }\n }\n node.appendChild(child);\n continue;\n }\n try {\n if (n.isSVG && name === 'xlink:href') {\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value);\n }\n else if (name === 'onload' ||\n name === 'onclick' ||\n name.substring(0, 7) === 'onmouse') {\n node.setAttribute('_' + name, value);\n }\n else if (tagName === 'meta' &&\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\n name === 'content') {\n node.setAttribute('csp-content', value);\n continue;\n }\n else if (tagName === 'link' &&\n (n.attributes.rel === 'preload' || n.attributes.rel === 'modulepreload') &&\n n.attributes.as === 'script') {\n }\n else if (tagName === 'link' &&\n n.attributes.rel === 'prefetch' &&\n typeof n.attributes.href === 'string' &&\n n.attributes.href.endsWith('.js')) {\n }\n else if (tagName === 'img' &&\n n.attributes.srcset &&\n n.attributes.rr_dataURL) {\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\n }\n else {\n node.setAttribute(name, value);\n }\n }\n catch (error) {\n }\n }\n else {\n if (tagName === 'canvas' && name === 'rr_dataURL') {\n const image = document.createElement('img');\n image.src = value;\n image.onload = () => {\n const ctx = node.getContext('2d');\n if (ctx) {\n ctx.drawImage(image, 0, 0, image.width, image.height);\n }\n };\n }\n else if (tagName === 'img' && name === 'rr_dataURL') {\n const image = node;\n if (!image.currentSrc.startsWith('data:')) {\n image.setAttribute('rrweb-original-src', n.attributes.src);\n image.src = value;\n }\n }\n if (name === 'rr_width') {\n node.style.width = value;\n }\n else if (name === 'rr_height') {\n node.style.height = value;\n }\n else if (name === 'rr_mediaCurrentTime') {\n node.currentTime = n.attributes\n .rr_mediaCurrentTime;\n }\n else if (name === 'rr_mediaState') {\n switch (value) {\n case 'played':\n node\n .play()\n .catch((e) => console.warn('media playback error', e));\n break;\n case 'paused':\n node.pause();\n break;\n }\n }\n }\n }\n if (n.isShadowHost) {\n if (!node.shadowRoot) {\n node.attachShadow({ mode: 'open' });\n if (doc.defaultView) {\n defineCustomElement(doc.defaultView, tagName);\n }\n }\n else {\n while (node.shadowRoot.firstChild) {\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\n }\n }\n }\n return node;\n case NodeType.Text:\n return doc.createTextNode(n.isStyle && hackCss\n ? addHoverClass(n.textContent, cache)\n : n.textContent);\n case NodeType.CDATA:\n return doc.createCDATASection(n.textContent);\n case NodeType.Comment:\n return doc.createComment(n.textContent);\n default:\n return null;\n }\n}\nfunction buildNodeWithSN(n, options) {\n const { doc, map, skipChild = false, hackCss = true, afterAppend, cache, } = options;\n let node = buildNode(n, { doc, hackCss, cache });\n if (!node) {\n return null;\n }\n if (n.rootId) {\n console.assert(map[n.rootId] === doc, 'Target document should has the same root id.');\n }\n if (n.type === NodeType.Document) {\n doc.close();\n doc.open();\n if (n.compatMode === 'BackCompat' &&\n n.childNodes &&\n n.childNodes[0].type !== NodeType.DocumentType) {\n if (n.childNodes[0].type === NodeType.Element &&\n 'xmlns' in n.childNodes[0].attributes &&\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\n doc.write('');\n }\n else {\n doc.write('');\n }\n }\n node = doc;\n }\n node.__sn = n;\n map[n.id] = node;\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\n !skipChild) {\n for (const childN of n.childNodes) {\n const childNode = buildNodeWithSN(childN, {\n doc,\n map,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n if (!childNode) {\n console.warn('Failed to rebuild', childN);\n continue;\n }\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\n node.shadowRoot.appendChild(childNode);\n }\n else {\n node.appendChild(childNode);\n }\n if (afterAppend) {\n afterAppend(childNode);\n }\n }\n }\n return node;\n}\nfunction visit(idNodeMap, onVisit) {\n function walk(node) {\n onVisit(node);\n }\n for (const key in idNodeMap) {\n if (idNodeMap[key]) {\n walk(idNodeMap[key]);\n }\n }\n}\nfunction handleScroll(node) {\n const n = node.__sn;\n if (n.type !== NodeType.Element) {\n return;\n }\n const el = node;\n for (const name in n.attributes) {\n if (!(n.attributes.hasOwnProperty(name) && name.startsWith('rr_'))) {\n continue;\n }\n const value = n.attributes[name];\n if (name === 'rr_scrollLeft') {\n el.scrollLeft = value;\n }\n if (name === 'rr_scrollTop') {\n el.scrollTop = value;\n }\n }\n}\nfunction rebuild(n, options) {\n const { doc, onVisit, hackCss = true, afterAppend, cache } = options;\n const idNodeMap = {};\n const node = buildNodeWithSN(n, {\n doc,\n map: idNodeMap,\n skipChild: false,\n hackCss,\n afterAppend,\n cache,\n });\n visit(idNodeMap, (visitedNode) => {\n if (onVisit) {\n onVisit(visitedNode);\n }\n handleScroll(visitedNode);\n });\n return [node, idNodeMap];\n}\n\nexport { IGNORED_NODE, NodeType, addHoverClass, buildNodeWithSN, cleanupSnapshot, createCache, defineCustomElement, getInputType, getInputValue, hasInputMaskOptions, is2DCanvasBlank, isElement, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, snapshot, transformAttribute, visitSnapshot };\n","import type { BreadcrumbFrame } from '../types/replayFrame';\n\n/**\n * Create a breadcrumb for a replay.\n */\nexport function createBreadcrumb(\n breadcrumb: Omit & Partial>,\n): BreadcrumbFrame {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n","// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nexport function getAttributesToRecord(attributes: Record): Record {\n const obj: Record = {};\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n","import type { INode } from '@sentry-internal/rrweb-snapshot';\nimport { NodeType } from '@sentry-internal/rrweb-snapshot';\nimport type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { handleClick } from './handleClick';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport type { DomHandlerData } from './util/domUtils';\nimport { getClickTargetNode, getTargetNode } from './util/domUtils';\nimport { getAttributesToRecord } from './util/getAttributesToRecord';\n\nexport const handleDomListener: (replay: ReplayContainer) => (handlerData: DomHandlerData) => void = (\n replay: ReplayContainer,\n) => {\n return (handlerData: DomHandlerData): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick && (handlerData.event as PointerEvent);\n // Ignore clicks if ctrl/alt/meta keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (isClick && replay.clickDetector && event && !event.altKey && !event.metaKey && !event.ctrlKey) {\n handleClick(\n replay.clickDetector,\n result as Breadcrumb & { timestamp: number; data: { nodeId: number } },\n getClickTargetNode(handlerData.event) as HTMLElement,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nexport function getBaseDomBreadcrumb(target: Node | INode | null, message: string): Breadcrumb {\n // `__sn` property is the serialized node created by rrweb\n const serializedNode = target && isRrwebNode(target) && target.__sn.type === NodeType.Element ? target.__sn : null;\n\n return {\n message,\n data: serializedNode\n ? {\n nodeId: serializedNode.id,\n node: {\n id: serializedNode.id,\n tagName: serializedNode.tagName,\n textContent: target\n ? Array.from(target.childNodes)\n .map(\n (node: Node | INode) => '__sn' in node && node.__sn.type === NodeType.Text && node.__sn.textContent,\n )\n .filter(Boolean) // filter out empty values\n .map(text => (text as string).trim())\n .join('')\n : '',\n attributes: getAttributesToRecord(serializedNode.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nexport function handleDom(handlerData: DomHandlerData): Breadcrumb | null {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData: DomHandlerData): { target: Node | INode | null; message: string } {\n const isClick = handlerData.name === 'click';\n\n let message: string | undefined;\n let target: Node | INode | null = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event) : getTargetNode(handlerData.event);\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isRrwebNode(node: EventTarget): node is INode {\n return '__sn' in node;\n}\n","import type { PerformanceNavigationTiming, PerformancePaintTiming } from '../types';\n\nconst NAVIGATION_ENTRY_KEYS: Array = [\n 'name',\n 'type',\n 'startTime',\n 'transferSize',\n 'duration',\n];\n\nfunction isNavigationEntryEqual(a: PerformanceNavigationTiming) {\n return function (b: PerformanceNavigationTiming) {\n return NAVIGATION_ENTRY_KEYS.every(key => a[key] === b[key]);\n };\n}\n\n/**\n * There are some difficulties diagnosing why there are duplicate navigation\n * entries. We've witnessed several intermittent results:\n * - duplicate entries have duration = 0\n * - duplicate entries are the same object reference\n * - none of the above\n *\n * Compare the values of several keys to determine if the entries are duplicates or not.\n */\n// TODO (high-prio): Figure out wth is returned here\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function dedupePerformanceEntries(\n currentList: PerformanceEntryList,\n newList: PerformanceEntryList,\n): PerformanceEntryList {\n // Partition `currentList` into 3 different lists based on entryType\n const [existingNavigationEntries, existingLcpEntries, existingEntries] = currentList.reduce(\n (acc: [PerformanceNavigationTiming[], PerformancePaintTiming[], PerformanceEntryList], entry) => {\n if (entry.entryType === 'navigation') {\n acc[0].push(entry as PerformanceNavigationTiming);\n } else if (entry.entryType === 'largest-contentful-paint') {\n acc[1].push(entry as PerformancePaintTiming);\n } else {\n acc[2].push(entry);\n }\n return acc;\n },\n [[], [], []],\n );\n\n const newEntries: PerformanceEntryList = [];\n const newNavigationEntries: PerformanceNavigationTiming[] = [];\n let newLcpEntry: PerformancePaintTiming | undefined = existingLcpEntries.length\n ? existingLcpEntries[existingLcpEntries.length - 1] // Take the last element as list is sorted\n : undefined;\n\n newList.forEach(entry => {\n if (entry.entryType === 'largest-contentful-paint') {\n // We want the latest LCP event only\n if (!newLcpEntry || newLcpEntry.startTime < entry.startTime) {\n newLcpEntry = entry;\n }\n return;\n }\n\n if (entry.entryType === 'navigation') {\n const navigationEntry = entry as PerformanceNavigationTiming;\n\n // Check if the navigation entry is contained in currentList or newList\n if (\n // Ignore any navigation entries with duration 0, as they are likely duplicates\n entry.duration > 0 &&\n // Ensure new entry does not already exist in existing entries\n !existingNavigationEntries.find(isNavigationEntryEqual(navigationEntry)) &&\n // Ensure new entry does not already exist in new list of navigation entries\n !newNavigationEntries.find(isNavigationEntryEqual(navigationEntry))\n ) {\n newNavigationEntries.push(navigationEntry);\n }\n\n // Otherwise this navigation entry is considered a duplicate and is thrown away\n return;\n }\n\n newEntries.push(entry);\n });\n\n // Re-combine and sort by startTime\n return [\n ...(newLcpEntry ? [newLcpEntry] : []),\n ...existingNavigationEntries,\n ...existingEntries,\n ...newEntries,\n ...newNavigationEntries,\n ].sort((a, b) => a.startTime - b.startTime);\n}\n","/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nexport function timestampToMs(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestampToMs';\nimport { EventBufferSizeExceededError } from '.';\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nexport class EventBufferArray implements EventBuffer {\n /** All the events that are buffered to be sent. */\n public events: RecordingEvent[];\n private _totalSize = 0;\n\n public constructor() {\n this.events = [];\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'sync';\n }\n\n /** @inheritdoc */\n public destroy(): void {\n this.events = [];\n }\n\n /** @inheritdoc */\n public async addEvent(event: RecordingEvent): Promise {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n public finish(): Promise {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n public clear(): void {\n this.events = [];\n this._totalSize = 0;\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n","import { logger } from '@sentry/utils';\n\nimport type { WorkerRequest, WorkerResponse } from '../types';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class WorkerHandler {\n private _worker: Worker;\n private _id: number;\n private _ensureReadyPromise?: Promise;\n\n public constructor(worker: Worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }: MessageEvent) => {\n if ((data as WorkerResponse).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n public destroy(): void {\n __DEBUG_BUILD__ && logger.log('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n public postMessage(method: WorkerRequest['method'], arg?: WorkerRequest['arg']): Promise {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }: MessageEvent): void => {\n const response = data as WorkerResponse;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n __DEBUG_BUILD__ && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response as T);\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n private _getAndIncrementId(): number {\n return this._id++;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestampToMs';\nimport { EventBufferSizeExceededError } from '.';\nimport { WorkerHandler } from './WorkerHandler';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class EventBufferCompressionWorker implements EventBuffer {\n private _worker: WorkerHandler;\n private _earliestTimestamp: number | null;\n private _totalSize = 0;\n\n public constructor(worker: Worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n public destroy(): void {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n public addEvent(event: RecordingEvent): Promise {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n public finish(): Promise {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n public clear(): void {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n void this._worker.postMessage('clear');\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n private _sendEventToWorker(data: string): Promise {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n private async _finishRequest(): Promise {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferCompressionWorker } from './EventBufferCompressionWorker';\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nexport class EventBufferProxy implements EventBuffer {\n private _fallback: EventBufferArray;\n private _compression: EventBufferCompressionWorker;\n private _used: EventBuffer;\n private _ensureWorkerIsLoadedPromise: Promise;\n\n public constructor(worker: Worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return this._used.type;\n }\n\n /** @inheritDoc */\n public get hasEvents(): boolean {\n return this._used.hasEvents;\n }\n\n /** @inheritDoc */\n public destroy(): void {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n public clear(): void {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n public addEvent(event: RecordingEvent): Promise {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n public async finish(): Promise {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n public ensureWorkerIsLoaded(): Promise {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n private async _ensureWorkerIsLoaded(): Promise {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n __DEBUG_BUILD__ && logger.log('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n private async _switchToCompressionWorker(): Promise {\n const { events } = this._fallback;\n\n const addEventPromises: Promise[] = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n __DEBUG_BUILD__ && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n","import { getWorkerURL } from '@sentry-internal/replay-worker';\nimport { logger } from '@sentry/utils';\n\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { EventBuffer } from '../types';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferProxy } from './EventBufferProxy';\n\ninterface CreateEventBufferParams {\n useCompression: boolean;\n}\n\n/**\n * Create an event buffer for replays.\n */\nexport function createEventBuffer({ useCompression }: CreateEventBufferParams): EventBuffer {\n // eslint-disable-next-line no-restricted-globals\n if (useCompression && window.Worker) {\n try {\n const workerUrl = getWorkerURL();\n\n __DEBUG_BUILD__ && logger.log('[Replay] Using compression worker');\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n __DEBUG_BUILD__ && logger.log('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n }\n\n __DEBUG_BUILD__ && logger.log('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nexport class EventBufferSizeExceededError extends Error {\n public constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n","/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nexport function isExpired(\n initialTime: null | number,\n expiry: undefined | number,\n targetTime: number = +new Date(),\n): boolean {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n","import type { Session, Timeouts } from '../types';\nimport { isExpired } from './isExpired';\n\n/**\n * Checks to see if session is expired\n */\nexport function isSessionExpired(session: Session, timeouts: Timeouts, targetTime: number = +new Date()): boolean {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, timeouts.maxSessionLife, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, timeouts.sessionIdleExpire, targetTime)\n );\n}\n","/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nexport function isSampled(sampleRate?: number): boolean {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\n\n/**\n * Save a session to session storage.\n */\nexport function saveSession(session: Session): void {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n if (!hasSessionStorage) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import { uuid4 } from '@sentry/utils';\n\nimport type { Sampled, Session } from '../types';\n\n/**\n * Get a session with defaults & applied sampling.\n */\nexport function makeSession(session: Partial & { sampled: Sampled }): Session {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n shouldRefresh: true,\n };\n}\n","import { logger } from '@sentry/utils';\n\nimport type { Sampled, Session, SessionOptions } from '../types';\nimport { isSampled } from '../util/isSampled';\nimport { saveSession } from './saveSession';\nimport { makeSession } from './Session';\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nexport function getSessionSampleType(sessionSampleRate: number, allowBuffering: boolean): Sampled {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nexport function createSession({ sessionSampleRate, allowBuffering, stickySession = false }: SessionOptions): Session {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n });\n\n __DEBUG_BUILD__ && logger.log(`[Replay] Creating new session: ${session.id}`);\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n","import { logger } from '@sentry/utils';\n\nimport type { Session, SessionOptions, Timeouts } from '../types';\nimport { isSessionExpired } from '../util/isSessionExpired';\nimport { createSession } from './createSession';\nimport { fetchSession } from './fetchSession';\nimport { makeSession } from './Session';\n\ninterface GetSessionParams extends SessionOptions {\n timeouts: Timeouts;\n\n /**\n * The current session (e.g. if stickySession is off)\n */\n currentSession?: Session;\n}\n\n/**\n * Get or create a session\n */\nexport function getSession({\n timeouts,\n currentSession,\n stickySession,\n sessionSampleRate,\n allowBuffering,\n}: GetSessionParams): { type: 'new' | 'saved'; session: Session } {\n // If session exists and is passed, use it instead of always hitting session storage\n const session = currentSession || (stickySession && fetchSession());\n\n if (session) {\n // If there is a session, check if it is valid (e.g. \"last activity\" time\n // should be within the \"session idle time\", and \"session started\" time is\n // within \"max session time\").\n const isExpired = isSessionExpired(session, timeouts);\n\n if (!isExpired || (allowBuffering && session.shouldRefresh)) {\n return { type: 'saved', session };\n } else if (!session.shouldRefresh) {\n // This is the case if we have an error session that is completed\n // (=triggered an error). Session will continue as session-based replay,\n // and when this session is expired, it will not be renewed until user\n // reloads.\n const discardedSession = makeSession({ sampled: false });\n return { type: 'new', session: discardedSession };\n } else {\n __DEBUG_BUILD__ && logger.log('[Replay] Session has expired');\n }\n // Otherwise continue to create a new session\n }\n\n const newSession = createSession({\n stickySession,\n sessionSampleRate,\n allowBuffering,\n });\n\n return { type: 'new', session: newSession };\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { makeSession } from './Session';\n\n/**\n * Fetches a session from storage\n */\nexport function fetchSession(): Session | null {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n\n if (!hasSessionStorage) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) as Session;\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { getCurrentHub } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { EventBufferSizeExceededError } from '../eventBuffer';\nimport type { AddEventResult, RecordingEvent, ReplayContainer, ReplayFrameEvent } from '../types';\nimport { timestampToMs } from './timestampToMs';\n\nfunction isCustomEvent(event: RecordingEvent): event is ReplayFrameEvent {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport async function addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!replay.eventBuffer) {\n // This implies that `_isEnabled` is false\n return null;\n }\n\n if (replay.isPaused()) {\n // Do not add to event buffer when recording is paused\n return null;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return null;\n }\n\n try {\n if (isCheckout) {\n replay.eventBuffer.clear();\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback =\n typeof replayOptions.beforeAddRecordingEvent === 'function' && isCustomEvent(event)\n ? replayOptions.beforeAddRecordingEvent(event)\n : event;\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await replay.eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const reason = error && error instanceof EventBufferSizeExceededError ? 'addEventSizeExceeded' : 'addEvent';\n\n __DEBUG_BUILD__ && logger.error(error);\n await replay.stop(reason);\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n","import type { ErrorEvent, Event, ReplayEvent, TransactionEvent } from '@sentry/types';\n\n/** If the event is an error event */\nexport function isErrorEvent(event: Event): event is ErrorEvent {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nexport function isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nexport function isReplayEvent(event: Event): event is ReplayEvent {\n return event.type === 'replay_event';\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { Event, Transport, TransportMakeRequestResponse } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isTransactionEvent } from '../util/eventUtils';\n\ntype AfterSendEventCallback = (event: Event, sendResponse: TransportMakeRequestResponse | void) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleAfterSendEvent(replay: ReplayContainer): AfterSendEventCallback {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event: Event, sendResponse: TransportMakeRequestResponse | void) => {\n if (!isErrorEvent(event) && !isTransactionEvent(event)) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n if (isTransactionEvent(event) && event.contexts && event.contexts.trace && event.contexts.trace.trace_id) {\n replay.getContext().traceIds.add(event.contexts.trace.trace_id as string);\n return;\n }\n\n // Everything below is just for error events\n if (!isErrorEvent(event)) {\n return;\n }\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n if (event.event_id) {\n replay.getContext().errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode === 'buffer' && event.tags && event.tags.replayId) {\n setTimeout(() => {\n // Capture current event buffer as new replay\n void replay.sendBufferedReplayOrFlush();\n });\n }\n };\n}\n\nfunction isBaseTransportSend(): boolean {\n const client = getCurrentHub().getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send as Transport['send'] & { __sentry__baseTransport__?: true }).__sentry__baseTransport__ || false\n );\n}\n","import { EventType } from '@sentry-internal/rrweb';\n\nimport type { AddEventResult, AllEntryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\n\n/**\n * Create a \"span\" for each performance entry.\n */\nexport function createPerformanceSpans(\n replay: ReplayContainer,\n entries: ReplayPerformanceEntry[],\n): Promise[] {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n","import type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../../types';\nimport { createPerformanceSpans } from '../../util/createPerformanceSpans';\nimport { shouldFilterRequest } from '../../util/shouldFilterRequest';\n\n/** Add a performance entry breadcrumb */\nexport function addNetworkBreadcrumb(\n replay: ReplayContainer,\n result: ReplayPerformanceEntry | null,\n): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n","import { getCurrentHub } from '@sentry/core';\n\nimport type { ReplayContainer } from '../types';\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nexport function shouldFilterRequest(replay: ReplayContainer, url: string): boolean {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (__DEBUG_BUILD__ && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return _isSentryRequest(url);\n}\n\n/**\n * Checks wether a given URL belongs to the configured Sentry DSN.\n */\nfunction _isSentryRequest(url: string): boolean {\n const client = getCurrentHub().getClient();\n const dsn = client && client.getDsn();\n return dsn ? url.includes(dsn.host) : false;\n}\n","export const OBJ = 10;\nexport const OBJ_KEY = 11;\nexport const OBJ_KEY_STR = 12;\nexport const OBJ_VAL = 13;\nexport const OBJ_VAL_STR = 14;\nexport const OBJ_VAL_COMPLETED = 15;\n\nexport const ARR = 20;\nexport const ARR_VAL = 21;\nexport const ARR_VAL_STR = 22;\nexport const ARR_VAL_COMPLETED = 23;\n\nexport type JsonToken =\n | typeof OBJ\n | typeof OBJ_KEY\n | typeof OBJ_KEY_STR\n | typeof OBJ_VAL\n | typeof OBJ_VAL_STR\n | typeof OBJ_VAL_COMPLETED\n | typeof ARR\n | typeof ARR_VAL\n | typeof ARR_VAL_STR\n | typeof ARR_VAL_COMPLETED;\n","import type { JsonToken } from './constants';\nimport {\n ARR,\n ARR_VAL,\n ARR_VAL_COMPLETED,\n ARR_VAL_STR,\n OBJ,\n OBJ_KEY,\n OBJ_KEY_STR,\n OBJ_VAL,\n OBJ_VAL_COMPLETED,\n OBJ_VAL_STR,\n} from './constants';\n\nconst ALLOWED_PRIMITIVES = ['true', 'false', 'null'];\n\n/**\n * Complete an incomplete JSON string.\n * This will ensure that the last element always has a `\"~~\"` to indicate it was truncated.\n * For example, `[1,2,` will be completed to `[1,2,\"~~\"]`\n * and `{\"aa\":\"b` will be completed to `{\"aa\":\"b~~\"}`\n */\nexport function completeJson(incompleteJson: string, stack: JsonToken[]): string {\n if (!stack.length) {\n return incompleteJson;\n }\n\n let json = incompleteJson;\n\n // Most checks are only needed for the last step in the stack\n const lastPos = stack.length - 1;\n const lastStep = stack[lastPos];\n\n json = _fixLastStep(json, lastStep);\n\n // Complete remaining steps - just add closing brackets\n for (let i = lastPos; i >= 0; i--) {\n const step = stack[i];\n\n switch (step) {\n case OBJ:\n json = `${json}}`;\n break;\n case ARR:\n json = `${json}]`;\n break;\n }\n }\n\n return json;\n}\n\nfunction _fixLastStep(json: string, lastStep: JsonToken): string {\n switch (lastStep) {\n // Object cases\n case OBJ:\n return `${json}\"~~\":\"~~\"`;\n case OBJ_KEY:\n return `${json}:\"~~\"`;\n case OBJ_KEY_STR:\n return `${json}~~\":\"~~\"`;\n case OBJ_VAL:\n return _maybeFixIncompleteObjValue(json);\n case OBJ_VAL_STR:\n return `${json}~~\"`;\n case OBJ_VAL_COMPLETED:\n return `${json},\"~~\":\"~~\"`;\n\n // Array cases\n case ARR:\n return `${json}\"~~\"`;\n case ARR_VAL:\n return _maybeFixIncompleteArrValue(json);\n case ARR_VAL_STR:\n return `${json}~~\"`;\n case ARR_VAL_COMPLETED:\n return `${json},\"~~\"`;\n }\n\n return json;\n}\n\nfunction _maybeFixIncompleteArrValue(json: string): string {\n const pos = _findLastArrayDelimiter(json);\n\n if (pos > -1) {\n const part = json.slice(pos + 1);\n\n if (ALLOWED_PRIMITIVES.includes(part.trim())) {\n return `${json},\"~~\"`;\n }\n\n // Everything else is replaced with `\"~~\"`\n return `${json.slice(0, pos + 1)}\"~~\"`;\n }\n\n // fallback, this shouldn't happen, to be save\n return json;\n}\n\nfunction _findLastArrayDelimiter(json: string): number {\n for (let i = json.length - 1; i >= 0; i--) {\n const char = json[i];\n\n if (char === ',' || char === '[') {\n return i;\n }\n }\n\n return -1;\n}\n\nfunction _maybeFixIncompleteObjValue(json: string): string {\n const startPos = json.lastIndexOf(':');\n\n const part = json.slice(startPos + 1);\n\n if (ALLOWED_PRIMITIVES.includes(part.trim())) {\n return `${json},\"~~\":\"~~\"`;\n }\n\n // Everything else is replaced with `\"~~\"`\n // This also means we do not have incomplete numbers, e.g `[1` is replaced with `[\"~~\"]`\n return `${json.slice(0, startPos + 1)}\"~~\"`;\n}\n","import type { JsonToken } from './constants';\nimport {\n ARR,\n ARR_VAL,\n ARR_VAL_COMPLETED,\n ARR_VAL_STR,\n OBJ,\n OBJ_KEY,\n OBJ_KEY_STR,\n OBJ_VAL,\n OBJ_VAL_COMPLETED,\n OBJ_VAL_STR,\n} from './constants';\n\n/**\n * Evaluate an (incomplete) JSON string.\n */\nexport function evaluateJson(json: string): JsonToken[] {\n const stack: JsonToken[] = [];\n\n for (let pos = 0; pos < json.length; pos++) {\n _evaluateJsonPos(stack, json, pos);\n }\n\n return stack;\n}\n\nfunction _evaluateJsonPos(stack: JsonToken[], json: string, pos: number): void {\n const curStep = stack[stack.length - 1];\n\n const char = json[pos];\n\n const whitespaceRegex = /\\s/;\n\n if (whitespaceRegex.test(char)) {\n return;\n }\n\n if (char === '\"' && !_isEscaped(json, pos)) {\n _handleQuote(stack, curStep);\n return;\n }\n\n switch (char) {\n case '{':\n _handleObj(stack, curStep);\n break;\n case '[':\n _handleArr(stack, curStep);\n break;\n case ':':\n _handleColon(stack, curStep);\n break;\n case ',':\n _handleComma(stack, curStep);\n break;\n case '}':\n _handleObjClose(stack, curStep);\n break;\n case ']':\n _handleArrClose(stack, curStep);\n break;\n }\n}\n\nfunction _handleQuote(stack: JsonToken[], curStep: JsonToken): void {\n // End of obj value\n if (curStep === OBJ_VAL_STR) {\n stack.pop();\n stack.push(OBJ_VAL_COMPLETED);\n return;\n }\n\n // End of arr value\n if (curStep === ARR_VAL_STR) {\n stack.pop();\n stack.push(ARR_VAL_COMPLETED);\n return;\n }\n\n // Start of obj value\n if (curStep === OBJ_VAL) {\n stack.push(OBJ_VAL_STR);\n return;\n }\n\n // Start of arr value\n if (curStep === ARR_VAL) {\n stack.push(ARR_VAL_STR);\n return;\n }\n\n // Start of obj key\n if (curStep === OBJ) {\n stack.push(OBJ_KEY_STR);\n return;\n }\n\n // End of obj key\n if (curStep === OBJ_KEY_STR) {\n stack.pop();\n stack.push(OBJ_KEY);\n return;\n }\n}\n\nfunction _handleObj(stack: JsonToken[], curStep: JsonToken): void {\n // Initial object\n if (!curStep) {\n stack.push(OBJ);\n return;\n }\n\n // New object as obj value\n if (curStep === OBJ_VAL) {\n stack.push(OBJ);\n return;\n }\n\n // New object as array element\n if (curStep === ARR_VAL) {\n stack.push(OBJ);\n }\n\n // New object as first array element\n if (curStep === ARR) {\n stack.push(OBJ);\n return;\n }\n}\n\nfunction _handleArr(stack: JsonToken[], curStep: JsonToken): void {\n // Initial array\n if (!curStep) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n\n // New array as obj value\n if (curStep === OBJ_VAL) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n\n // New array as array element\n if (curStep === ARR_VAL) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n }\n\n // New array as first array element\n if (curStep === ARR) {\n stack.push(ARR);\n stack.push(ARR_VAL);\n return;\n }\n}\n\nfunction _handleColon(stack: JsonToken[], curStep: JsonToken): void {\n if (curStep === OBJ_KEY) {\n stack.pop();\n stack.push(OBJ_VAL);\n }\n}\n\nfunction _handleComma(stack: JsonToken[], curStep: JsonToken): void {\n // Comma after obj value\n if (curStep === OBJ_VAL) {\n stack.pop();\n return;\n }\n if (curStep === OBJ_VAL_COMPLETED) {\n // Pop OBJ_VAL_COMPLETED & OBJ_VAL\n stack.pop();\n stack.pop();\n return;\n }\n\n // Comma after arr value\n if (curStep === ARR_VAL) {\n // do nothing - basically we'd pop ARR_VAL but add it right back\n return;\n }\n\n if (curStep === ARR_VAL_COMPLETED) {\n // Pop ARR_VAL_COMPLETED\n stack.pop();\n\n // basically we'd pop ARR_VAL but add it right back\n return;\n }\n}\n\nfunction _handleObjClose(stack: JsonToken[], curStep: JsonToken): void {\n // Empty object {}\n if (curStep === OBJ) {\n stack.pop();\n }\n\n // Object with element\n if (curStep === OBJ_VAL) {\n // Pop OBJ_VAL, OBJ\n stack.pop();\n stack.pop();\n }\n\n // Obj with element\n if (curStep === OBJ_VAL_COMPLETED) {\n // Pop OBJ_VAL_COMPLETED, OBJ_VAL, OBJ\n stack.pop();\n stack.pop();\n stack.pop();\n }\n\n // if was obj value, complete it\n if (stack[stack.length - 1] === OBJ_VAL) {\n stack.push(OBJ_VAL_COMPLETED);\n }\n\n // if was arr value, complete it\n if (stack[stack.length - 1] === ARR_VAL) {\n stack.push(ARR_VAL_COMPLETED);\n }\n}\n\nfunction _handleArrClose(stack: JsonToken[], curStep: JsonToken): void {\n // Empty array []\n if (curStep === ARR) {\n stack.pop();\n }\n\n // Array with element\n if (curStep === ARR_VAL) {\n // Pop ARR_VAL, ARR\n stack.pop();\n stack.pop();\n }\n\n // Array with element\n if (curStep === ARR_VAL_COMPLETED) {\n // Pop ARR_VAL_COMPLETED, ARR_VAL, ARR\n stack.pop();\n stack.pop();\n stack.pop();\n }\n\n // if was obj value, complete it\n if (stack[stack.length - 1] === OBJ_VAL) {\n stack.push(OBJ_VAL_COMPLETED);\n }\n\n // if was arr value, complete it\n if (stack[stack.length - 1] === ARR_VAL) {\n stack.push(ARR_VAL_COMPLETED);\n }\n}\n\nfunction _isEscaped(str: string, pos: number): boolean {\n const previousChar = str[pos - 1];\n\n return previousChar === '\\\\' && !_isEscaped(str, pos - 1);\n}\n","/* eslint-disable max-lines */\n\nimport { completeJson } from './completeJson';\nimport { evaluateJson } from './evaluateJson';\n\n/**\n * Takes an incomplete JSON string, and returns a hopefully valid JSON string.\n * Note that this _can_ fail, so you should check the return value is valid JSON.\n */\nexport function fixJson(incompleteJson: string): string {\n const stack = evaluateJson(incompleteJson);\n\n return completeJson(incompleteJson, stack);\n}\n","import type { TextEncoderInternal } from '@sentry/types';\nimport { dropUndefinedKeys, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { NETWORK_BODY_MAX_SIZE, WINDOW } from '../../constants';\nimport type {\n NetworkBody,\n NetworkMetaWarning,\n NetworkRequestData,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n ReplayPerformanceEntry,\n} from '../../types';\nimport { fixJson } from '../../util/truncateJson/fixJson';\n\n/** Get the size of a body. */\nexport function getBodySize(\n body: RequestInit['body'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nexport function parseContentLengthHeader(header: string | null | undefined): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nexport function getBodyString(body: unknown): string | undefined {\n if (typeof body === 'string') {\n return body;\n }\n\n if (body instanceof URLSearchParams) {\n return body.toString();\n }\n\n if (body instanceof FormData) {\n return _serializeFormData(body);\n }\n\n return undefined;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nexport function makeNetworkReplayBreadcrumb(\n type: string,\n data: ReplayNetworkRequestData | null,\n): ReplayPerformanceEntry | null {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result: ReplayPerformanceEntry = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Get either a JSON network body, or a text representation. */\nexport function getNetworkBody(bodyText: string | undefined): NetworkBody | undefined {\n if (!bodyText) {\n return;\n }\n\n try {\n return JSON.parse(bodyText);\n } catch {\n // return text\n }\n\n return bodyText;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nexport function buildSkippedNetworkRequestOrResponse(bodySize: number | undefined): ReplayNetworkRequestOrResponse {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nexport function buildNetworkRequestOrResponse(\n headers: Record,\n bodySize: number | undefined,\n body: string | undefined,\n): ReplayNetworkRequestOrResponse | undefined {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info: ReplayNetworkRequestOrResponse = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nexport function getAllowedHeaders(headers: Record, allowedHeaders: string[]): Record {\n return Object.keys(headers).reduce((filteredHeaders: Record, key: string) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData: FormData): string {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-ignore passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body: string | undefined): {\n body: NetworkBody | undefined;\n warnings: NetworkMetaWarning[];\n} {\n if (!body || typeof body !== 'string') {\n return {\n body,\n warnings: [],\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n\n if (_strIsProbablyJson(body)) {\n try {\n const json = exceedsSizeLimit ? fixJson(body.slice(0, NETWORK_BODY_MAX_SIZE)) : body;\n const normalizedBody = JSON.parse(json);\n return {\n body: normalizedBody,\n warnings: exceedsSizeLimit ? ['JSON_TRUNCATED'] : [],\n };\n } catch {\n return {\n body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,\n warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],\n };\n }\n }\n\n return {\n body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,\n warnings: exceedsSizeLimit ? ['TEXT_TRUNCATED'] : [],\n };\n}\n\nfunction _strIsProbablyJson(str: string): boolean {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nexport function urlMatches(url: string, urls: (string | RegExp)[]): boolean {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nexport function getFullUrl(url: string, baseURI = WINDOW.document.baseURI): string {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n","import type { Breadcrumb, FetchBreadcrumbData, TextEncoderInternal } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport type {\n FetchHint,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureFetchBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: FetchHint,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n replay: ReplayContainer;\n },\n): Promise {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n __DEBUG_BUILD__ && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichFetchBreadcrumb(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: FetchHint,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { input, response } = hint;\n\n const body = _getFetchRequestArgBody(input);\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: FetchHint,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n): Promise {\n const { startTimestamp, endTimestamp } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails = urlMatches(url, options.networkDetailAllowUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders }: ReplayNetworkOptions,\n input: FetchHint['input'],\n requestBodySize?: number,\n): ReplayNetworkRequestOrResponse | undefined {\n const headers = getRequestHeaders(input, networkRequestHeaders);\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const bodyStr = getBodyString(requestBody);\n return buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n}\n\nasync function _getResponseInfo(\n captureDetails: boolean,\n {\n networkCaptureBodies,\n textEncoder,\n networkResponseHeaders,\n }: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n response: Response,\n responseBodySize?: number,\n): Promise {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = getAllHeaders(response.headers, networkResponseHeaders);\n\n if (!networkCaptureBodies && responseBodySize !== undefined) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n // Only clone the response if we need to\n try {\n // We have to clone this, as the body can only be read once\n const res = response.clone();\n const bodyText = await _parseFetchBody(res);\n\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch {\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchBody(response: Response): Promise {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs: unknown[] = []): RequestInit['body'] | undefined {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] as RequestInit).body;\n}\n\nfunction getAllHeaders(headers: Headers, allowedHeaders: string[]): Record {\n const allHeaders: Record = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) as string;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs: unknown[], allowedHeaders: string[]): Record {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] as Request | RequestInit, allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] as Request | RequestInit, allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input: Request | RequestInit | undefined,\n allowedHeaders: string[],\n): Record {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n","import type { Breadcrumb, TextEncoderInternal, XhrBreadcrumbData } from '@sentry/types';\nimport { logger, SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { ReplayContainer, ReplayNetworkOptions, ReplayNetworkRequestData, XhrHint } from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureXhrBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: XhrHint,\n options: ReplayNetworkOptions & { replay: ReplayContainer },\n): Promise {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n __DEBUG_BUILD__ && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichXhrBreadcrumb(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: XhrHint,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { xhr, input } = hint;\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : getBodySize(xhr.response, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: XhrHint,\n options: ReplayNetworkOptions,\n): ReplayNetworkRequestData | null {\n const { startTimestamp, endTimestamp, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!urlMatches(url, options.networkDetailAllowUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const request = buildNetworkRequestOrResponse(\n networkRequestHeaders,\n requestBodySize,\n options.networkCaptureBodies ? getBodyString(input) : undefined,\n );\n const response = buildNetworkRequestOrResponse(\n networkResponseHeaders,\n responseBodySize,\n options.networkCaptureBodies ? hint.xhr.responseText : undefined,\n );\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction getResponseHeaders(xhr: XMLHttpRequest): Record {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record, line: string) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n FetchBreadcrumbData,\n TextEncoderInternal,\n XhrBreadcrumbData,\n} from '@sentry/types';\nimport { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport type { FetchHint, ReplayContainer, ReplayNetworkOptions, XhrHint } from '../types';\nimport { handleFetchSpanListener } from './handleFetch';\nimport { handleXhrSpanListener } from './handleXhr';\nimport { captureFetchBreadcrumbToReplay, enrichFetchBreadcrumb } from './util/fetchUtils';\nimport { captureXhrBreadcrumbToReplay, enrichXhrBreadcrumb } from './util/xhrUtils';\n\ninterface ExtendedNetworkBreadcrumbsOptions extends ReplayNetworkOptions {\n replay: ReplayContainer;\n textEncoder: TextEncoderInternal;\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nexport function handleNetworkBreadcrumbs(replay: ReplayContainer): void {\n const client = getCurrentHub().getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const { networkDetailAllowUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } =\n replay.getOptions();\n\n const options: ExtendedNetworkBreadcrumbsOptions = {\n replay,\n textEncoder,\n networkDetailAllowUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addInstrumentationHandler('fetch', handleFetchSpanListener(replay));\n addInstrumentationHandler('xhr', handleXhrSpanListener(replay));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nexport function beforeAddNetworkBreadcrumb(\n options: ExtendedNetworkBreadcrumbsOptions,\n breadcrumb: Breadcrumb,\n hint?: BreadcrumbHint,\n): void {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n void captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n void captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n __DEBUG_BUILD__ && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: XhrBreadcrumbData } {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: FetchBreadcrumbData } {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint?: BreadcrumbHint): hint is XhrHint {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint?: BreadcrumbHint): hint is FetchHint {\n return hint && hint.response;\n}\n","import type { HandlerDataFetch } from '@sentry/types';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleFetch(handlerData: HandlerDataFetch): null | ReplayPerformanceEntry {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response && (response as Response).status,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.\n */\nexport function handleFetchSpanListener(replay: ReplayContainer): (handlerData: HandlerDataFetch) => void {\n return (handlerData: HandlerDataFetch) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { HandlerDataXhr } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleXhr(handlerData: HandlerDataXhr): ReplayPerformanceEntry | null {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('xhr', listener)`.\n */\nexport function handleXhrSpanListener(replay: ReplayContainer): (handlerData: HandlerDataXhr) => void {\n return (handlerData: HandlerDataXhr) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { Breadcrumb, Scope } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport { CONSOLE_ARG_MAX_SIZE } from '../constants';\nimport type { ReplayContainer } from '../types';\nimport type { ReplayFrame } from '../types/replayFrame';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { fixJson } from '../util/truncateJson/fixJson';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\nlet _LAST_BREADCRUMB: null | Breadcrumb = null;\n\ntype BreadcrumbWithCategory = Required>;\n\nfunction isBreadcrumbWithCategory(breadcrumb: Breadcrumb): breadcrumb is BreadcrumbWithCategory {\n return !!breadcrumb.category;\n}\n\nexport const handleScopeListener: (replay: ReplayContainer) => (scope: Scope) => void =\n (replay: ReplayContainer) =>\n (scope: Scope): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nexport function handleScope(scope: Scope): Breadcrumb | null {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n !isBreadcrumbWithCategory(newBreadcrumb) ||\n ['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (newBreadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(newBreadcrumb);\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/** exported for tests only */\nexport function normalizeConsoleBreadcrumb(\n breadcrumb: Omit & BreadcrumbWithCategory,\n): ReplayFrame {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n const fixedJson = fixJson(stringified.slice(0, CONSOLE_ARG_MAX_SIZE));\n const json = JSON.parse(fixedJson);\n // We only set this after JSON.parse() was successfull, so we know we didn't run into `catch`\n isTruncated = true;\n return json;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n","import type { BaseClient } from '@sentry/core';\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Client, DynamicSamplingContext } from '@sentry/types';\nimport { addInstrumentationHandler } from '@sentry/utils';\n\nimport { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';\nimport { handleDomListener } from '../coreHandlers/handleDom';\nimport { handleGlobalEventListener } from '../coreHandlers/handleGlobalEvent';\nimport { handleHistorySpanListener } from '../coreHandlers/handleHistory';\nimport { handleNetworkBreadcrumbs } from '../coreHandlers/handleNetworkBreadcrumbs';\nimport { handleScopeListener } from '../coreHandlers/handleScope';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Add global listeners that cannot be removed.\n */\nexport function addGlobalListeners(replay: ReplayContainer): void {\n // Listeners from core SDK //\n const scope = getCurrentHub().getScope();\n const client = getCurrentHub().getClient();\n\n if (scope) {\n scope.addScopeListener(handleScopeListener(replay));\n }\n addInstrumentationHandler('dom', handleDomListener(replay));\n addInstrumentationHandler('history', handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n addGlobalEventProcessor(handleGlobalEventListener(replay, !hasHooks(client)));\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc: DynamicSamplingContext) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n dsc.replay_id = replayId;\n }\n });\n\n client.on('startTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We may be missing the initial startTransaction due to timing issues,\n // so we capture it on finish again.\n client.on('finishTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client: Client | undefined): client is BaseClient {\n return !!(client && client.on);\n}\n","import { WINDOW } from '../constants';\nimport type { AddEventResult, MemoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from './createPerformanceSpans';\n\ntype ReplayMemoryEntry = ReplayPerformanceEntry & { data: { memory: MemoryInfo } };\n\ninterface MemoryInfo {\n jsHeapSizeLimit: number;\n totalJSHeapSize: number;\n usedJSHeapSize: number;\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nexport async function addMemoryEntry(replay: ReplayContainer): Promise> {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-ignore memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry: MemoryInfo): ReplayMemoryEntry {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n","import { record } from '@sentry-internal/rrweb';\nimport { browserPerformanceTimeOrigin } from '@sentry/utils';\n\nimport { WINDOW } from '../constants';\nimport type {\n AllPerformanceEntry,\n AllPerformanceEntryData,\n ExperimentalPerformanceResourceTiming,\n LargestContentfulPaintData,\n NavigationData,\n PaintData,\n PerformanceNavigationTiming,\n PerformancePaintTiming,\n ReplayPerformanceEntry,\n ResourceData,\n} from '../types';\n\n// Map entryType -> function to normalize data for event\n// @ts-ignore TODO: entry type does not fit the create* functions entry type\nconst ENTRY_TYPES: Record<\n string,\n (entry: AllPerformanceEntry) => null | ReplayPerformanceEntry\n> = {\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n ['largest-contentful-paint']: createLargestContentfulPaint,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nexport function createPerformanceEntries(\n entries: AllPerformanceEntry[],\n): ReplayPerformanceEntry[] {\n return entries.map(createPerformanceEntry).filter(Boolean) as ReplayPerformanceEntry[];\n}\n\nfunction createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEntry | null {\n if (ENTRY_TYPES[entry.entryType] === undefined) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time: number): number {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry: PerformanceNavigationTiming): ReplayPerformanceEntry | null {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry: ExperimentalPerformanceResourceTiming,\n): ReplayPerformanceEntry | null {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\nfunction createLargestContentfulPaint(\n entry: PerformanceEntry & { size: number; element: Node },\n): ReplayPerformanceEntry {\n const { entryType, startTime, size } = entry;\n\n let startTimeOrNavigationActivation = 0;\n\n if (WINDOW.performance) {\n const navEntry = WINDOW.performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming & {\n activationStart: number;\n };\n\n // See https://github.com/GoogleChrome/web-vitals/blob/9f11c4c6578fb4c5ee6fa4e32b9d1d756475f135/src/lib/getActivationStart.ts#L21\n startTimeOrNavigationActivation = (navEntry && navEntry.activationStart) || 0;\n }\n\n // value is in ms\n const value = Math.max(startTime - startTimeOrNavigationActivation, 0);\n // LCP doesn't have a \"duration\", it just happens at a single point in time.\n // But the UI expects both, so use end (in seconds) for both timestamps.\n const end = getAbsoluteTime(startTimeOrNavigationActivation) + value / 1000;\n\n return {\n type: entryType,\n name: entryType,\n start: end,\n end,\n data: {\n value, // LCP \"duration\" in ms\n size,\n // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nodeId: record.mirror.getId(entry.element as any),\n },\n };\n}\n","import type { DsnComponents, ReplayEnvelope, ReplayEvent, ReplayRecordingData } from '@sentry/types';\nimport { createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader } from '@sentry/utils';\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nexport function createReplayEnvelope(\n replayEvent: ReplayEvent,\n recordingData: ReplayRecordingData,\n dsn: DsnComponents,\n tunnel?: string,\n): ReplayEnvelope {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\n/**\n * Prepare the recording data ready to be sent.\n */\nexport function prepareRecordingData({\n recordingData,\n headers,\n}: {\n recordingData: ReplayRecordingData;\n headers: Record;\n}): ReplayRecordingData {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n","import type { Scope } from '@sentry/core';\nimport { prepareEvent } from '@sentry/core';\nimport type { IntegrationIndex } from '@sentry/core/build/types/integration';\nimport type { Client, ReplayEvent } from '@sentry/types';\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nexport async function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}: {\n client: Client & { _integrations?: IntegrationIndex };\n scope: Scope;\n replayId: string;\n event: ReplayEvent;\n}): Promise {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n { event_id, integrations },\n scope,\n )) as ReplayEvent | null;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { ReplayEvent, TransportMakeRequestResponse } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { createReplayEnvelope } from './createReplayEnvelope';\nimport { prepareRecordingData } from './prepareRecordingData';\nimport { prepareReplayEvent } from './prepareReplayEvent';\n\n/**\n * Send replay attachment using `fetch()`\n */\nexport async function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}: SendReplayData): Promise {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const hub = getCurrentHub();\n const client = hub.getClient();\n const scope = hub.getScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !scope || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent: ReplayEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n __DEBUG_BUILD__ && logger.log('An event processor returned `null`, will not send event.');\n return;\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response: void | TransportMakeRequestResponse;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nexport class TransportStatusCodeError extends Error {\n public constructor(statusCode: number) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n","import { captureException, setContext } from '@sentry/core';\n\nimport { RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { sendReplayRequest, TransportStatusCodeError } from './sendReplayRequest';\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nexport async function sendReplay(\n replayData: SendReplayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n): Promise {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (__DEBUG_BUILD__ && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return await new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n","export const THROTTLED = '__THROTTLED';\nexport const SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle any>(\n fn: T,\n maxCount: number,\n durationSeconds: number,\n): (...rest: Parameters) => ReturnType | typeof THROTTLED | typeof SKIPPED {\n const counter = new Map();\n\n const _cleanup = (now: number): void => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = (): number => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest: Parameters): ReturnType | typeof THROTTLED | typeof SKIPPED => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n","/* eslint-disable max-lines */ // TODO: We might want to split this file up\nimport { EventType, record } from '@sentry-internal/rrweb';\nimport { captureException, getCurrentHub } from '@sentry/core';\nimport type { ReplayRecordingMode, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport {\n BUFFER_CHECKOUT_TIME,\n MAX_SESSION_LIFE,\n MULTI_CLICK_TIMEOUT,\n SESSION_IDLE_EXPIRE_DURATION,\n SESSION_IDLE_PAUSE_DURATION,\n SLOW_CLICK_SCROLL_TIMEOUT,\n SLOW_CLICK_THRESHOLD,\n WINDOW,\n} from './constants';\nimport { ClickDetector } from './coreHandlers/handleClick';\nimport { handleKeyboardEvent } from './coreHandlers/handleKeyboardEvent';\nimport { setupPerformanceObserver } from './coreHandlers/performanceObserver';\nimport { createEventBuffer } from './eventBuffer';\nimport { clearSession } from './session/clearSession';\nimport { getSession } from './session/getSession';\nimport { saveSession } from './session/saveSession';\nimport type {\n AddEventResult,\n AddUpdateCallback,\n AllPerformanceEntry,\n BreadcrumbFrame,\n EventBuffer,\n InternalEventContext,\n PopEventContext,\n RecordingEvent,\n RecordingOptions,\n ReplayContainer as ReplayContainerInterface,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n Session,\n SlowClickConfig,\n Timeouts,\n} from './types';\nimport { addEvent } from './util/addEvent';\nimport { addGlobalListeners } from './util/addGlobalListeners';\nimport { addMemoryEntry } from './util/addMemoryEntry';\nimport { createBreadcrumb } from './util/createBreadcrumb';\nimport { createPerformanceEntries } from './util/createPerformanceEntries';\nimport { createPerformanceSpans } from './util/createPerformanceSpans';\nimport { debounce } from './util/debounce';\nimport { getHandleRecordingEmit } from './util/handleRecordingEmit';\nimport { isExpired } from './util/isExpired';\nimport { isSessionExpired } from './util/isSessionExpired';\nimport { sendReplay } from './util/sendReplay';\nimport type { SKIPPED } from './util/throttle';\nimport { throttle, THROTTLED } from './util/throttle';\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nexport class ReplayContainer implements ReplayContainerInterface {\n public eventBuffer: EventBuffer | null = null;\n\n /**\n * List of PerformanceEntry from PerformanceObserver\n */\n public performanceEvents: AllPerformanceEntry[] = [];\n\n public session: Session | undefined;\n\n public clickDetector: ClickDetector | undefined;\n\n /**\n * Recording can happen in one of three modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n public recordingMode: ReplayRecordingMode = 'session';\n\n /**\n * The current or last active transcation.\n * This is only available when performance is enabled.\n */\n public lastTransaction?: Transaction;\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n public readonly timeouts: Timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n maxSessionLife: MAX_SESSION_LIFE,\n } as const;\n\n private _throttledAddEvent: (\n event: RecordingEvent,\n isCheckout?: boolean,\n ) => typeof THROTTLED | typeof SKIPPED | Promise;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n private readonly _options: ReplayPluginOptions;\n\n private _performanceObserver: PerformanceObserver | null = null;\n\n private _debouncedFlush: ReturnType;\n private _flushLock: Promise | null = null;\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n private _lastActivity: number = Date.now();\n\n /**\n * Is the integration currently active?\n */\n private _isEnabled: boolean = false;\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n private _isPaused: boolean = false;\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n private _hasInitializedCoreListeners: boolean = false;\n\n /**\n * Function to stop recording\n */\n private _stopRecording: ReturnType | null = null;\n\n private _context: InternalEventContext = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n public constructor({\n options,\n recordingOptions,\n }: {\n options: ReplayPluginOptions;\n recordingOptions: RecordingOptions;\n }) {\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event: RecordingEvent, isCheckout?: boolean) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig: SlowClickConfig | undefined = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n multiClickTimeout: MULTI_CLICK_TIMEOUT,\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n }\n\n /** Get the event context. */\n public getContext(): InternalEventContext {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n public isEnabled(): boolean {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n public isPaused(): boolean {\n return this._isPaused;\n }\n\n /** Get the replay integration options. */\n public getOptions(): ReplayPluginOptions {\n return this._options;\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n public initializeSampling(): void {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n if (errorSampleRate <= 0 && sessionSampleRate <= 0) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n const isSessionSampled = this._loadAndCheckSession();\n\n if (!isSessionSampled) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n this._handleException(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled && this.session.sampled !== 'session') {\n // If not sampled as session-based, then recording mode will be `buffer`\n // Note that we don't explicitly check if `sampled === 'buffer'` because we\n // could have sessions from Session storage that are still `error` from\n // prior SDK version.\n this.recordingMode = 'buffer';\n }\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (this._isEnabled && this.recordingMode === 'session') {\n throw new Error('Replay recording is already in progress');\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n throw new Error('Replay buffering is in progress, call `flush()` to save the replay');\n }\n\n const previousSessionId = this.session && this.session.id;\n\n const { session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n });\n\n session.previousSessionId = previousSessionId;\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n public startBuffering(): void {\n if (this._isEnabled) {\n throw new Error('Replay recording is already in progress');\n }\n\n const previousSessionId = this.session && this.session.id;\n\n const { session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n sessionSampleRate: 0,\n allowBuffering: true,\n });\n\n session.previousSessionId = previousSessionId;\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n public startRecording(): void {\n try {\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n public stopRecording(): boolean {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public async stop(reason?: string): Promise {\n if (!this._isEnabled) {\n return;\n }\n\n try {\n if (__DEBUG_BUILD__) {\n const msg = `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`;\n\n // When `traceInternals` is enabled, we want to log this to the console\n // Else, use the regular debug output\n // eslint-disable-next-line\n const log = this.getOptions()._experiments.traceInternals ? console.warn : logger.log;\n log(msg);\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (this.recordingMode === 'session') {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n public pause(): void {\n this._isPaused = true;\n this.stopRecording();\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n public resume(): void {\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public async sendBufferedReplayOrFlush({ continueRecording = true }: SendBufferedReplayOptions = {}): Promise {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // Re-start recording, but in \"session\" recording mode\n\n // Reset all \"capture on error\" configuration before\n // starting a new recording\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this.session.shouldRefresh = false;\n\n // It's possible that the session lifespan is > max session lifespan\n // because we have been buffering beyond max session lifespan (we ignore\n // expiration given that `shouldRefresh` is true). Since we flip\n // `shouldRefresh`, the session could be considered expired due to\n // lifespan, which is not what we want. Update session start date to be\n // the current timestamp, so that session is not considered to be\n // expired. This means that max replay duration can be MAX_SESSION_LIFE +\n // (length of buffer), which we are ok with.\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this.session.started = activityTime;\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n public addUpdate(cb: AddUpdateCallback): void {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n public triggerUserActivity(): void {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n public updateUserActivity(): void {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n public conditionalFlush(): Promise {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n public flushImmediate(): Promise {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() as Promise;\n }\n\n /**\n * Cancels queued up flushes.\n */\n public cancelFlush(): void {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current sesion (=replay) ID */\n public getSessionId(): string | undefined {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n public checkAndHandleExpiredSession(): boolean | void {\n const oldSessionId = this.getSessionId();\n\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Session was expired if session ids do not match\n const expired = oldSessionId !== this.getSessionId();\n\n if (!expired) {\n return true;\n }\n\n // Session is expired, trigger a full snapshot (which will create a new session)\n this._triggerFullSnapshot();\n\n return false;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n public setInitialState(): void {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEvents = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n public throttledAddEvent(\n event: RecordingEvent,\n isCheckout?: boolean,\n ): typeof THROTTLED | typeof SKIPPED | Promise {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n void addEvent(this, {\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n public getCurrentRoute(): string | undefined {\n const lastTransaction = this.lastTransaction || getCurrentHub().getScope().getTransaction();\n if (!lastTransaction || !['route', 'custom'].includes(lastTransaction.metadata.source)) {\n return undefined;\n }\n\n return lastTransaction.name;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n private _initializeRecording(): void {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n\n this.startRecording();\n }\n\n /** A wrapper to conditionally capture exceptions. */\n private _handleException(error: unknown): void {\n __DEBUG_BUILD__ && logger.error('[Replay]', error);\n\n if (__DEBUG_BUILD__ && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n * Returns false if session is not recorded.\n */\n private _loadAndCheckSession(): boolean {\n const { type, session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering: this._options.errorSampleRate > 0 || this.recordingMode === 'buffer',\n });\n\n // If session was newly created (i.e. was not loaded from storage), then\n // enable flag to create the root replay\n if (type === 'new') {\n this.setInitialState();\n }\n\n const currentSessionId = this.getSessionId();\n if (session.id !== currentSessionId) {\n session.previousSessionId = currentSessionId;\n }\n\n this.session = session;\n\n if (!this.session.sampled) {\n void this.stop('session unsampled');\n return false;\n }\n\n return true;\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n private _addListeners(): void {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n // PerformanceObserver //\n if (!('PerformanceObserver' in WINDOW)) {\n return;\n }\n\n this._performanceObserver = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n private _removeListeners(): void {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceObserver) {\n this._performanceObserver.disconnect();\n this._performanceObserver = null;\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n private _handleVisibilityChange: () => void = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n private _handleWindowBlur: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n /**\n * Handle when page is focused\n */\n private _handleWindowFocus: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n private _handleKeyboardEvent: (event: KeyboardEvent) => void = (event: KeyboardEvent) => {\n handleKeyboardEvent(this, event);\n };\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n private _doChangeToBackgroundTasks(breadcrumb?: BreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, this.timeouts);\n\n if (breadcrumb && !expired) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n private _doChangeToForegroundTasks(breadcrumb?: BreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n __DEBUG_BUILD__ && logger.log('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Trigger rrweb to take a full snapshot which will cause this plugin to\n * create a new Replay event.\n */\n private _triggerFullSnapshot(checkout = true): void {\n try {\n __DEBUG_BUILD__ && logger.log('[Replay] Taking full rrweb snapshot');\n record.takeFullSnapshot(checkout);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n private _updateUserActivity(_lastActivity: number = Date.now()): void {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n private _updateSessionActivity(_lastActivity: number = Date.now()): void {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n private _createCustomBreadcrumb(breadcrumb: BreadcrumbFrame): void {\n this.addUpdate(() => {\n void this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEvents`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n private _addPerformanceEntries(): Promise> {\n // Copy and reset entries before processing\n const entries = [...this.performanceEvents];\n this.performanceEvents = [];\n\n return Promise.all(createPerformanceSpans(this, createPerformanceEntries(entries)));\n }\n\n /**\n * Clear _context\n */\n private _clearContext(): void {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n private _updateInitialTimestampFromEventBuffer(): void {\n const { session, eventBuffer } = this;\n if (!session || !eventBuffer) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n private _popEventContext(): PopEventContext {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n private async _runFlush(): Promise {\n if (!this.session || !this.eventBuffer) {\n __DEBUG_BUILD__ && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n // NOTE: Copy values from instance members, as it's possible they could\n // change before the flush finishes.\n const replayId = this.session.id;\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp: Date.now(),\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n void this.stop('sendReplay');\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n private _flush = async ({\n force = false,\n }: {\n /**\n * If true, flush while ignoring the `_isEnabled` state of\n * Replay integration. (By default, flush is noop if integration\n * is stopped).\n */\n force?: boolean;\n } = {}): Promise => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n __DEBUG_BUILD__ && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n __DEBUG_BUILD__ && logger.error('[Replay] No session found to flush.');\n return;\n }\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = null;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n __DEBUG_BUILD__ && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };\n\n /** Save the session, if it is sticky */\n private _maybeSaveSession(): void {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n private _onMutationHandler = (mutations: unknown[]): boolean => {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n void this.stop('mutationLimit');\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };\n}\n","type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => unknown;\ntype DebounceOptions = { maxWait?: number };\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nexport function debounce(func: CallbackFunction, wait: number, options?: DebounceOptions): DebouncedCallback {\n let callbackReturnValue: unknown;\n\n let timerId: ReturnType | undefined;\n let maxTimerId: ReturnType | undefined;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc(): unknown {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers(): void {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush(): unknown {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced(): unknown {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { logger } from '@sentry/utils';\n\nimport { saveSession } from '../session/saveSession';\nimport type { AddEventResult, OptionFrameEvent, RecordingEvent, ReplayContainer } from '../types';\nimport { addEvent } from './addEvent';\n\ntype RecordingEmitCallback = (event: RecordingEvent, isCheckout?: boolean) => void;\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nexport function getHandleRecordingEmit(replay: ReplayContainer): RecordingEmitCallback {\n let hadFirstEvent = false;\n\n return (event: RecordingEvent, _isCheckout?: boolean) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n __DEBUG_BUILD__ && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // We need to clear existing events on a checkout, otherwise they are\n // incremental event updates and should be appended\n void addEvent(replay, event, isCheckout);\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time.\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n void addSettingsEvent(replay, isCheckout);\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n const options = replay.getOptions();\n\n // TODO: We want this as an experiment so that we can test\n // internally and create metrics before making this the default\n if (options._experiments.delayFlushOnCheckout) {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n // TODO: We should check `recordingMode` here and do nothing if it's\n // buffer, instead of checking inside of timeout, this will make our\n // tests a bit cleaner as we will need to wait on the delay in order to\n // do nothing.\n setTimeout(() => replay.conditionalFlush(), options._experiments.delayFlushOnCheckout);\n\n // Cancel any previously debounced flushes to ensure there are no [near]\n // simultaneous flushes happening. The latter request should be\n // insignificant in this case, so wait for additional user interaction to\n // trigger a new flush.\n //\n // This can happen because there's no guarantee that a recording event\n // happens first. e.g. a mouse click can happen and trigger a debounced\n // flush before the checkout.\n replay.cancelFlush();\n\n return true;\n }\n\n // Flush immediately so that we do not miss the first segment, otherwise\n // it can prevent loading on the UI. This will cause an increase in short\n // replays (e.g. opening and closing a tab quickly), but these can be\n // filtered on the UI.\n if (replay.recordingMode === 'session') {\n // We want to ensure the worker is ready, as otherwise we'd always send the first event uncompressed\n void replay.flushImmediate();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nexport function createOptionsEvent(replay: ReplayContainer): OptionFrameEvent {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay: ReplayContainer, isCheckout?: boolean): Promise {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return Promise.resolve(null);\n }\n\n return addEvent(replay, createOptionsEvent(replay), false);\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../../src/constants';\nimport type { ReplayContainer } from '../../src/types';\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nexport function clearSession(replay: ReplayContainer): void {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession(): void {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n\n if (!hasSessionStorage) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import r from\"./worker\";function e(){const e=new Blob([r]);return URL.createObjectURL(e)}export{e as getWorkerURL};\n","export default `/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\nfunction t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const m=t=>t<256?o[t]:o[256+(t>>>7)],b=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},g=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<{g(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)r=r+a[n-1]<<1,i[n]=r;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},x=t=>{t.bi_valid>8?b(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n{let s,r,o,_,f=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+f++],s+=(255&t.pending_buf[t.sym_buf+f++])<<8,r=t.pending_buf[t.sym_buf+f++],0===s?p(t,r,i):(o=l[r],p(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],g(t,r,_)),s--,o=m(s),p(t,o,n),_=a[o],0!==_&&(s-=d[o],g(t,s,_)))}while(f{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o{g(t,0+(i?1:0),3),x(t),b(t,a),b(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var T=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(g(t,2+(i?1:0),3),E(t,s,r)):(g(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(g(t,e-257,5),g(t,a-1,5),g(t,i-4,4),s=0;s{S||((()=>{let t,n,w,m,b;const g=new Array(16);for(w=0,m=0;m<28;m++)for(h[m]=w,t=0;t<1<>=7;m<30;m++)for(d[m]=b<<7,t=0;t<1<(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=a,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{g(t,2,3),p(t,256,s),(t=>{16===t.bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var F=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const L=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var N=(t,e,a,i)=>{const n=L,s=i+a;t^=-1;for(let a=i;a>>8^n[255&(t^e[a])];return-1^t},I={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=O,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:W,Z_OK:q,Z_STREAM_END:J,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>2*t-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_t=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let ft=(t,e,a)=>(e<{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ut=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ct(t.strm)},wt=(t,e)=>{t.pending_buf[t.pending++]=e},mt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=F(t.adler,e,n,a):2===t.state.wrap&&(t.adler=N(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&sr){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_t(t),i+=e),0===t.strm.avail_in)break;if(a=bt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ft(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ft(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},kt=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_outi+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,ct(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(bt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_watern&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(bt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===X)&&e!==P&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===X&&0===t.strm.avail_in&&a===i?1:0,H(t,t.block_start,a,r),t.block_start+=a,ct(t.strm)),r?3:1)},vt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ft(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2},yt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ut(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ut(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2};function xt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const zt=[new xt(0,0,0,0,kt),new xt(4,4,8,4,vt),new xt(4,5,16,8,vt),new xt(4,6,32,32,vt),new xt(4,4,16,16,yt),new xt(8,16,32,32,yt),new xt(8,16,128,128,yt),new xt(8,32,128,256,yt),new xt(32,128,258,1024,yt),new xt(32,258,258,4096,yt)];function At(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Et=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||42!==e.status&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&113!==e.status&&666!==e.status?1:0},Rt=t=>{if(Et(t))return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=-2,C(e),q},Zt=t=>{const e=Rt(t);var a;return e===q&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=zt[a.level].max_lazy,a.good_match=zt[a.level].good_length,a.nice_match=zt[a.level].nice_length,a.max_chain_length=zt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},Ut=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt||8===i&&1!==r)return lt(t,Q);8===i&&(i=9);const o=new At;return t.state=o,o.strm=t,o.status=42,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<Ut(t,e,ot,15,8,st),deflateInit2:Ut,deflateReset:Zt,deflateResetKeep:Rt,deflateSetHeader:(t,e)=>Et(t)||2!==t.state.wrap?Q:(t.state.gzhead=e,q),deflate:(t,e)=>{if(Et(t)||e>W||e<0)return t?lt(t,Q):Q;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||666===a.status&&e!==X)return lt(t,0===t.avail_out?$:Q);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(ct(t),0===t.avail_out)return a.last_flush=-1,q}else if(0===t.avail_in&&ht(e)<=ht(i)&&e!==X)return lt(t,$);if(666===a.status&&0!==t.avail_in)return lt(t,$);if(42===a.status&&0===a.wrap&&(a.status=113),42===a.status){let e=ot+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=at||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,mt(a,e),0!==a.strstart&&(mt(a,t.adler>>>16),mt(a,65535&t.adler)),t.adler=1,a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(57===a.status)if(t.adler=0,wt(a,31),wt(a,139),wt(a,8),a.gzhead)wt(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),wt(a,255&a.gzhead.time),wt(a,a.gzhead.time>>8&255),wt(a,a.gzhead.time>>16&255),wt(a,a.gzhead.time>>24&255),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(wt(a,255&a.gzhead.extra.length),wt(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=N(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,3),a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,ct(t),0!==a.pending)return a.last_flush=-1,q;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(ct(t),0!==a.pending))return a.last_flush=-1,q;wt(a,255&t.adler),wt(a,t.adler>>8&255),t.adler=0}if(a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(0!==t.avail_in||0!==a.lookahead||e!==P&&666!==a.status){let i=0===a.level?kt(a,e):a.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):zt[a.level].func(a,e);if(3!==i&&4!==i||(a.status=666),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),q;if(2===i&&(e===Y?K(a):e!==W&&(H(a,0,0,!1),e===G&&(dt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),ct(t),0===t.avail_out))return a.last_flush=-1,q}return e!==X?q:a.wrap<=0?J:(2===a.wrap?(wt(a,255&t.adler),wt(a,t.adler>>8&255),wt(a,t.adler>>16&255),wt(a,t.adler>>24&255),wt(a,255&t.total_in),wt(a,t.total_in>>8&255),wt(a,t.total_in>>16&255),wt(a,t.total_in>>24&255)):(mt(a,t.adler>>>16),mt(a,65535&t.adler)),ct(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?q:J)},deflateEnd:t=>{if(Et(t))return Q;const e=t.state.status;return t.state=null,113===e?lt(t,V):q},deflateSetDictionary:(t,e)=>{let a=e.length;if(Et(t))return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=F(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=ft(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,q},deflateInfo:\"pako deflate (from Nodeca project)\"};const Dt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Tt=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if(\"object\"!=typeof a)throw new TypeError(a+\"must be non-object\");for(const e in a)Dt(a,e)&&(t[e]=a[e])}}return t},Ot=t=>{let e=0;for(let a=0,i=t.length;a=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Lt[254]=Lt[254]=1;var Nt=t=>{if(\"function\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},It=(t,e)=>{const a=e||t.length;if(\"function\"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Ft)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a=\"\";for(let i=0;i{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Lt[t[a]]>e?a:e};var Ct=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0};const Ht=Object.prototype.toString,{Z_NO_FLUSH:Mt,Z_SYNC_FLUSH:jt,Z_FULL_FLUSH:Kt,Z_FINISH:Pt,Z_OK:Yt,Z_STREAM_END:Gt,Z_DEFAULT_COMPRESSION:Xt,Z_DEFAULT_STRATEGY:Wt,Z_DEFLATED:qt}=B;function Jt(t){this.options=Tt({level:Xt,method:qt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Wt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=St.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==Yt)throw new Error(I[a]);if(e.header&&St.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t=\"string\"==typeof e.dictionary?Nt(e.dictionary):\"[object ArrayBuffer]\"===Ht.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=St.deflateSetDictionary(this.strm,t),a!==Yt)throw new Error(I[a]);this._dict_set=!0}}function Qt(t,e){const a=new Jt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}Jt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Pt:Mt,\"string\"==typeof t?a.input=Nt(t):\"[object ArrayBuffer]\"===Ht.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===jt||s===Kt)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=St.deflate(a,s),n===Gt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=St.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Yt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},Jt.prototype.onData=function(t){this.chunks.push(t)},Jt.prototype.onEnd=function(t){t===Yt&&(this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Vt={Deflate:Jt,deflate:Qt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Qt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Qt(t,e)},constants:B};var $t=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a>3,a-=k,c-=k<<3,f&=(1<{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,U,S,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0}while(0!==d);for(h=1<>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg=\"\",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whavexe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg=\"incorrect header check\",a.mode=me;break}if((15&h)!==we){t.msg=\"unknown compression method\",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg=\"invalid window size\",a.mode=me;break}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=N(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=N(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg=\"invalid block type\",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg=\"invalid stored block lengths\",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg=\"too many length or distance symbols\",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid code lengths set\",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg=\"invalid bit length repeat\",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg=\"invalid bit length repeat\",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg=\"invalid code -- missing end-of-block\",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid literal/lengths set\",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg=\"invalid distances set\",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg=\"invalid literal/length code\",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg=\"invalid distance code\",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg=\"invalid distance too far back\",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg=\"invalid distance too far back\",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=F(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:\"pako inflate (from Nodeca project)\"};var Se=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Te,Z_FINISH:Oe,Z_OK:Fe,Z_STREAM_END:Le,Z_NEED_DICT:Ne,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Tt({chunkSize:65536,windowBits:15,to:\"\"},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ue.inflateInit2(this.strm,e.windowBits);if(a!==Fe)throw new Error(I[a]);if(this.header=new Se,Ue.inflateGetHeader(this.strm,this.header),e.dictionary&&(\"string\"==typeof e.dictionary?e.dictionary=Nt(e.dictionary):\"[object ArrayBuffer]\"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Ue.inflateSetDictionary(this.strm,e.dictionary),a!==Fe)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Oe:Te,\"[object ArrayBuffer]\"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Ue.inflate(a,r),s===Ne&&n&&(s=Ue.inflateSetDictionary(a,n),s===Fe?s=Ue.inflate(a,r):s===Be&&(s=Ne));a.avail_in>0&&s===Le&&a.state.wrap>0&&0!==t[a.next_in];)Ue.inflateReset(a),s=Ue.inflate(a,r);switch(s){case Ie:case Be:case Ne:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Le))if(\"string\"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Fe||0!==o){if(s===Le)return s=Ue.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Fe&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=je,Xe=B;const We=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const e=this._hasEvents?\",\":\"\";this.deflate.push(e+t,Xe.Z_SYNC_FLUSH),this._hasEvents=!0}finish(){if(this.deflate.push(\"]\",Xe.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this._init(),t}_init(){this._hasEvents=!1,this.deflate=new Ye,this.deflate.push(\"[\",Xe.Z_NO_FLUSH)}},qe={clear:()=>{We.clear()},addEvent:t=>We.addEvent(t),finish:()=>We.finish(),compress:t=>function(t){return Ge(t)}(t)};addEventListener(\"message\",(function(t){const e=t.data.method,a=t.data.id,i=t.data.arg;if(e in qe&&\"function\"==typeof qe[e])try{const t=qe[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n","import type { HistoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from '../util/createPerformanceSpans';\n\ninterface HistoryHandlerData {\n from: string;\n to: string;\n}\n\nfunction handleHistory(handlerData: HistoryHandlerData): ReplayPerformanceEntry {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.\n */\nexport function handleHistorySpanListener(replay: ReplayContainer): (handlerData: HistoryHandlerData) => void {\n return (handlerData: HistoryHandlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n","import type { Event, EventHint } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';\nimport { isRrwebError } from '../util/isRrwebError';\nimport { handleAfterSendEvent } from './handleAfterSendEvent';\nimport { shouldSampleForBufferEvent } from './util/shouldSampleForBufferEvent';\n\n/**\n * Returns a listener to be added to `addGlobalEventProcessor(listener)`.\n */\nexport function handleGlobalEventListener(\n replay: ReplayContainer,\n includeAfterSendEventHandling = false,\n): (event: Event, hint: EventHint) => Event | null {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return (event: Event, hint: EventHint) => {\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors & transactions, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event)) {\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n __DEBUG_BUILD__ && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n };\n}\n","import type { Event, EventHint } from '@sentry/types';\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nexport function isRrwebError(event: Event, hint: EventHint): boolean {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-ignore this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n // Check if any exception originates from rrweb\n return event.exception.values.some(exception => {\n if (!exception.stacktrace || !exception.stacktrace.frames || !exception.stacktrace.frames.length) {\n return false;\n }\n\n return exception.stacktrace.frames.some(frame => frame.filename && frame.filename.includes('/rrweb/src/'));\n });\n}\n","import type { Event } from '@sentry/types';\n\nimport { UNABLE_TO_SEND_REPLAY } from '../../constants';\nimport type { ReplayContainer } from '../../types';\nimport { isSampled } from '../../util/isSampled';\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `hanldleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nexport function shouldSampleForBufferEvent(replay: ReplayContainer, event: Event): boolean {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n","import type { AllPerformanceEntry, ReplayContainer } from '../types';\nimport { dedupePerformanceEntries } from '../util/dedupePerformanceEntries';\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n */\nexport function setupPerformanceObserver(replay: ReplayContainer): PerformanceObserver {\n const performanceObserverHandler = (list: PerformanceObserverEntryList): void => {\n // For whatever reason the observer was returning duplicate navigation\n // entries (the other entry types were not duplicated).\n const newPerformanceEntries = dedupePerformanceEntries(\n replay.performanceEvents,\n list.getEntries() as AllPerformanceEntry[],\n );\n replay.performanceEvents = newPerformanceEntries;\n };\n\n const performanceObserver = new PerformanceObserver(performanceObserverHandler);\n\n [\n 'element',\n 'event',\n 'first-input',\n 'largest-contentful-paint',\n 'layout-shift',\n 'longtask',\n 'navigation',\n 'paint',\n 'resource',\n ].forEach(type => {\n try {\n performanceObserver.observe({\n type,\n buffered: true,\n });\n } catch {\n // This can throw if an entry type is not supported in the browser.\n // Ignore these errors.\n }\n });\n\n return performanceObserver;\n}\n","import type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { getBaseDomBreadcrumb } from './handleDom';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\n/** Handle keyboard events & create breadcrumbs. */\nexport function handleKeyboardEvent(replay: ReplayContainer, event: KeyboardEvent): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nexport function getKeyboardBreadcrumb(event: KeyboardEvent): Breadcrumb | null {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target as HTMLElement) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target as Node, message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target: HTMLElement): boolean {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n","import type { DeprecatedPrivacyOptions, ReplayIntegrationPrivacyOptions } from '../types';\n\ntype GetPrivacyOptions = Required> &\n Omit;\ninterface GetPrivacyReturn {\n maskTextSelector: string;\n unmaskTextSelector: string;\n maskInputSelector: string;\n unmaskInputSelector: string;\n blockSelector: string;\n unblockSelector: string;\n ignoreSelector: string;\n\n blockClass?: RegExp;\n maskTextClass?: RegExp;\n}\n\nfunction getOption(\n selectors: string[],\n defaultSelectors: string[],\n deprecatedClassOption?: string | RegExp,\n deprecatedSelectorOption?: string,\n): string {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nexport function getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}: GetPrivacyOptions): GetPrivacyReturn {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options: GetPrivacyReturn = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n maskInputSelector: maskSelector,\n unmaskInputSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n","import { isNodeEnv } from '@sentry/utils';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n return typeof process !== 'undefined' && (process as ElectronProcess).type === 'renderer';\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { BrowserClientReplayOptions, Integration } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_FLUSH_MAX_DELAY, DEFAULT_FLUSH_MIN_DELAY } from './constants';\nimport { ReplayContainer } from './replay';\nimport type { RecordingOptions, ReplayConfiguration, ReplayPluginOptions, SendBufferedReplayOptions } from './types';\nimport { getPrivacyOptions } from './util/getPrivacyOptions';\nimport { isBrowser } from './util/isBrowser';\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\ntype InitialReplayPluginOptions = Omit &\n Partial>;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n */\nexport class Replay implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Replay';\n\n /**\n * @inheritDoc\n */\n public name: string = Replay.id;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n private readonly _initialOptions: InitialReplayPluginOptions;\n\n private _replay?: ReplayContainer;\n\n public constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n stickySession = true,\n useCompression = true,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10_000,\n\n slowClickTimeout = 7_000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n }: ReplayConfiguration = {}) {\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n\n ...getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n }),\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n protected get _isInitialized(): boolean {\n return _initialized;\n }\n\n /** Update _isInitialized */\n protected set _isInitialized(value: boolean) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n public setupOnce(): void {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // Once upon a time, we tried to create a transaction in `setupOnce` and it would\n // potentially create a transaction before some native SDK integrations have run\n // and applied their own global event processor. An example is:\n // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n //\n // So we call `this._initialize()` in next event loop as a workaround to wait for other\n // global event processors to finish. This is no longer needed, but keeping it\n // here to avoid any future issues.\n setTimeout(() => this._initialize());\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n public startBuffering(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public stop(): Promise {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop();\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public flush(options?: SendBufferedReplayOptions): Promise {\n if (!this._replay || !this._replay.isEnabled()) {\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n public getReplayId(): string | undefined {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n /**\n * Initializes replay.\n */\n protected _initialize(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n private _setup(): void {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions: InitialReplayPluginOptions): ReplayPluginOptions {\n const client = getCurrentHub().getClient();\n const opt = client && (client.getOptions() as BrowserClientReplayOptions);\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers: string[]): string[] {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n","export const SDK_VERSION = '7.56.0';\n","import type { ConsoleLevel } from './logger';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { Integration, Options } from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\nimport { addGlobalEventProcessor } from './scope';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(integration: Integration, integrationIndex: IntegrationIndex): void {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n __DEBUG_BUILD__ && logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n Integration,\n IntegrationClass,\n Outcome,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n SentryError,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport type { IntegrationIndex } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean = false;\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number } = {};\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record = {};\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n __DEBUG_BUILD__ && logger.warn('No DSN provided, client will not do anything.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n __DEBUG_BUILD__ && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n setupIntegration(integration, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n if (this._dsn) {\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n if (this._dsn) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n void this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, _event?: Event): void {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n __DEBUG_BUILD__ && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n\n /** @inheritdoc */\n public on(hook: 'startTransaction' | 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-ignore We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction' | 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n // @ts-ignore we cannot enforce the callback to match the hook\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent(options, event, hint, scope);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (__DEBUG_BUILD__) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n if (this._transport && this._dsn) {\n this.emit('beforeEnvelope', envelope);\n\n return this._transport.send(envelope).then(null, reason => {\n __DEBUG_BUILD__ && logger.error('Error while sending event:', reason);\n });\n } else {\n __DEBUG_BUILD__ && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: string,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n","import type { Scope } from '@sentry/core';\nimport { BaseClient, SDK_VERSION } from '@sentry/core';\nimport type {\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { Breadcrumbs } from './integrations';\nimport { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options & BrowserClientReplayOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint?: EventHint): void {\n // We only want to add the sentry event breadcrumb when the user has the breadcrumb integration installed and\n // activated its `sentry` option.\n // We also do not want to use the `Breadcrumbs` class here directly, because we do not want it to be included in\n // bundles, if it is not used by the SDK.\n // This all sadly is a bit ugly, but we currently don't have a \"pre-send\" hook on the integrations so we do it this\n // way for now.\n const breadcrumbIntegration = this.getIntegrationById(BREADCRUMB_INTEGRATION_ID) as Breadcrumbs | undefined;\n // We check for definedness of `addSentryBreadcrumb` in case users provided their own integration with id\n // \"Breadcrumbs\" that does not have this function.\n if (breadcrumbIntegration && breadcrumbIntegration.addSentryBreadcrumb) {\n breadcrumbIntegration.addSentryBreadcrumb(event);\n }\n\n super.sendEvent(event, hint);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n void this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n __DEBUG_BUILD__ && logger.log('No outcomes to send');\n return;\n }\n\n if (!this._dsn) {\n __DEBUG_BUILD__ && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n void this._sendEnvelope(envelope);\n }\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type { TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, category: string): number {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, category: string, now: number = Date.now()): boolean {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n SentryError,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n __DEBUG_BUILD__ && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n __DEBUG_BUILD__ && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import type { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcessor: EventProcessor = currentEvent => {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n __DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport {\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n Integrations as CoreIntegrations,\n} from '@sentry/core';\nimport type { UserFeedback } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n logger,\n resolvedSyncPromise,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, HttpContext, LinkedErrors, TryCatch } from './integrations';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\nexport const defaultIntegrations = [\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\n];\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nexport function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n __DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n __DEBUG_BUILD__ && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n __DEBUG_BUILD__ && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function flush(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport function close(timeout?: number): PromiseLike {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n __DEBUG_BUILD__ && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\nfunction startSessionOnHub(hub: Hub): void {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n __DEBUG_BUILD__ &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getCurrentHub().getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import type { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { CONSOLE_LEVELS, fill, GLOBAL_OBJ, safeJoin, severityLevelFromString } from '@sentry/utils';\n\n/** Send Console API calls as Sentry Events */\nexport class CaptureConsole implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'CaptureConsole';\n\n /**\n * @inheritDoc\n */\n public name: string = CaptureConsole.id;\n\n /**\n * @inheritDoc\n */\n private readonly _levels: readonly string[] = CONSOLE_LEVELS;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { levels?: string[] } = {}) {\n if (options.levels) {\n this._levels = options.levels;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n this._levels.forEach((level: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if (!(level in (GLOBAL_OBJ as any).console)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n fill((GLOBAL_OBJ as any).console, level, (originalConsoleMethod: () => any) => (...args: any[]): void => {\n const hub = getCurrentHub();\n\n if (hub.getIntegration(CaptureConsole)) {\n hub.withScope(scope => {\n scope.setLevel(severityLevelFromString(level));\n scope.setExtra('arguments', args);\n scope.addEventProcessor(event => {\n event.logger = 'console';\n return event;\n });\n\n let message = safeJoin(args, ' ');\n if (level === 'assert') {\n if (args[0] === false) {\n message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n hub.captureMessage(message);\n }\n } else if (level === 'error' && args[0] instanceof Error) {\n hub.captureException(args[0]);\n } else {\n hub.captureMessage(message);\n }\n });\n }\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(GLOBAL_OBJ.console, args);\n }\n });\n });\n }\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["isBrowserBundle","__SENTRY_BROWSER_BUNDLE__","getSDKSource","isNodeEnv","Object","prototype","toString","call","process","dynamicRequire","mod","request","require","WINDOW","getGlobalObject","dateTimestampSource","nowSeconds","Date","now","platformPerformance","module","performance","_","getNodePerformance","timeOrigin","getBrowserPerformance","timestampSource","undefined","dateTimestampInSeconds","bind","timestampInSeconds","browserPerformanceTimeOrigin","threshold","performanceNow","dateNow","timeOriginDelta","Math","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","isGlobalObj","obj","GLOBAL_OBJ","globalThis","window","self","global","getGlobalSingleton","name","creator","gbl","__SENTRY__","_typeof","_regeneratorRuntime","exports","__esModule","Op","hasOwn","hasOwnProperty","defineProperty","key","desc","value","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","enumerable","configurable","writable","err","wrap","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","fn","arg","type","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","result","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","done","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","methodName","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","runtime","regeneratorRuntime","accidentalStrictMode","Function","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","n","getter","d","a","definition","o","get","g","e","hmd","children","set","prop","r","flarum","core","compat","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","base","_e","truncate","str","max","safeJoin","input","delimiter","Array","isArray","output","String","join","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","InboundFilters","__initStatic","_proto","_options","__init","setupOnce","addGlobalEventProcessor","getCurrentHub","eventProcess","event","hub","getIntegration","client","getClient","clientOptions","getOptions","options","internalOptions","allowUrls","concat","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","_isSentryError","message","_ref","_ref$type","_ref$value","oO","_getPossibleEventMessages","_isIgnoredError","transaction","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","frames","stacktrace","frame","filename","_getLastValidUrl","_extends","assign","target","arguments","source","apply","originalFunctionToString","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","nextStr","currentElem","out","height","len","keyAttrs","maxStringLength","_htmlElementAsString","separator","parentNode","_oO","el","classes","attr","tagName","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","keyAttrPair","split","allowedAttrs","fill","replacementFactory","original","wrapped","markFunctionWrapped","_Oo","addNonEnumerableProperty","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","extractExceptionKeysForMessage","maxLength","sort","includedKeys","serialized","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","memoVal","returnValue","_i","_Object$keys","item","FunctionToString","_len","args","_key","WEBPACK_ERROR_REGEXP","defaultFunctionName","getFunctionName","uuid4","crypto","msCrypto","randomUUID","replace","getRandomByte","getRandomValues","Uint8Array","random","c","getFirstException","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","logger","CONSOLE_LEVELS","enable","disable","States","DEFAULT_ENVIRONMENT","resolvedSyncPromise","SyncPromise","rejectedSyncPromise","reason","executor","__init2","__init3","__init4","__init5","__init6","_resolve","_reject","_state","PENDING","_handlers","onfulfilled","onrejected","_this","_executeHandlers","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","_value","_this6","cachedHandlers","handler","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","clone","scope","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","addScopeListener","callback","addEventProcessor","setUser","_notifyScopeListeners","getUser","getRequestSession","setRequestSession","requestSession","setTags","tags","setTag","_extends2","setExtras","extras","setExtra","extra","_extends3","setFingerprint","fingerprint","setLevel","level","setTransactionName","setContext","setSpan","span","getSpan","getTransaction","setSession","getSession","update","captureContext","updatedScope","contexts","clear","addBreadcrumb","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","hint","trace","getTraceContext","sdkProcessingMetadata","dynamicSamplingContext","getDynamicSamplingContext","transactionName","_applyFingerprint","breadcrumbs","_notifyEventProcessors","getGlobalEventProcessors","setSDKProcessingMetadata","newData","processors","index","processor","final","maybeArray","API_VERSION","Hub","_version","_stack","bindClient","isOlderThan","version","getStackTop","setupIntegrations","pushScope","getScope","getStack","popScope","withScope","captureException","_lastEventId","syntheticException","_withClient","originalException","captureMessage","captureEvent","lastEventId","_this$getStackTop","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","originalConsole","console","wrappedLevels","originalWrappedFunc","consoleSandbox","emit","configureScope","_this$getStackTop2","run","oldHub","makeMain","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2","_ref2$environment","navigator","startingTime","toJSON","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","_this$getStackTop5","sentry","getMainCarrier","extensions","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","ignoreOnError","shouldIgnoreOnError","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","ex","setTimeout","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","TryCatch","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","originalCallback","originalSend","xhr","wrapOptions","originalFunction","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","isNativeFetch","lastHref","SENTRY_XHR_DATA_KEY","handlers","instrumented","instrument","originalConsoleMethod","triggerHandlers","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","document","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","instrumentDOM","xhrproto","originalOpen","_len3","_key3","xhrInfo","toUpperCase","request_headers","match","__sentry_own_request__","onreadystatechangeHandler","readyState","status_code","endTimestamp","startTimestamp","onreadystatechange","_len4","readyStateArgs","_key4","_len5","setRequestHeaderArgs","_key5","header","sentryXhrData","_len6","_key6","body","instrumentXHR","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","chrome","isChromePackagedApp","app","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","location","href","from","_len7","_key7","historyReplacementFunction","originalHistoryFunction","_len8","_key8","instrumentHistory","_oldOnErrorHandler","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","onunhandledrejection","addInstrumentationHandler","_step","_iterator","_createForOfIteratorHelperLoose","resource","debounceTimerID","lastCapturedEvent","debounceDuration","globalListener","isContentEditable","shouldSkipDOMEvent","previous","current","shouldShortcircuitPreviousDebounce","clearTimeout","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","objName","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","numAdded","visitable","visitKey","visitValue","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","__serialized__","eventFromPlainObject","synthetic","GlobalHandlers","_installFunc","_installGlobalOnErrorHandler","_installGlobalOnUnhandledRejectionHandler","stackTraceLimit","installFunc","_getHubAndOptions","getHubAndOptions","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","addMechanismAndCapture","_getHubAndOptions2","ev","ev0","ev0s","ev0sf","colno","parseInt","lineno","getLocationHref","in_app","validSeverityLevels","severityLevelFromString","parseUrl","query","fragment","host","path","protocol","search","hash","relative","BREADCRUMB_INTEGRATION_ID","Breadcrumbs","dom","_consoleBreadcrumb","serializeAttribute","_isEvent","category","_xhrBreadcrumb","_fetchBreadcrumb","_historyBreadcrumb","addSentryBreadcrumb","parsedLoc","parsedFrom","parsedTo","LinkedErrors","_limit","limit","parser","linkedErrors","_walkErrorTree","_handler","HttpContext","referrer","headers","Referer","_assertThisInitialized","ReferenceError","_setPrototypeOf","p","_inheritsLoose","subClass","superClass","SpanRecorder","maxlen","_maxlen","spans","spanRecorder","_defineProperties","props","descriptor","prim","toPrimitive","res","_createClass","Constructor","protoProps","staticProps","Transaction","_Span","transactionContext","_hub","_name","metadata","spanMetadata","_trimEnd","trimEnd","incomingDynamicSamplingContext","_frozenDynamicSamplingContext","_measurements","setName","initSpanRecorder","setMeasurement","unit","setMetadata","newMetadata","sampled","finishedSpans","s","reduce","start_timestamp","transaction_info","measurements","recordDroppedEvent","toContext","updateWithContext","public_key","getDsn","publicKey","maybeSampleRate","sampleRate","sample_rate","user_segment","segment","dsc","trace_id","traceId","setHub","newName","_proto2","Span","spanContext","__init7","spanId","parentSpanId","op","description","instrumenter","substring","startChild","childSpan","setData","setStatus","setHttpStatus","httpStatus","spanStatus","spanStatusfromHttpCode","isSuccess","toTraceparent","sampledString","parent_span_id","span_id","TRACING_DEFAULTS","idleTimeout","finalTimeout","heartbeatInterval","IDLE_TRANSACTION_FINISH_REASONS","IdleTransactionSpanRecorder","_SpanRecorder","_pushActivity","_popActivity","transactionSpanId","IdleTransaction","_Transaction","_idleHub","_idleTimeout","_finalTimeout","_heartbeatInterval","_onScope","_restartIdleTimeout","_finished","_finishReason","activities","_heartbeatCounter","_idleTimeoutCanceledPermanently","_beforeFinishCallbacks","registerBeforeFinishCallback","_pingHeartbeat","cancelIdleTimeout","_temp","restartOnChildSpanChange","_idleTimeoutID","setFinishReason","_beat","heartbeatString","_prevHeartbeatString","_this7","hasTracingEnabled","maybeOptions","enableTracing","getActiveTransaction","maybeHub","errorsInstrumented","errorCallback","activeTransaction","sample","samplingContext","Number","tracesSampler","parentSampled","tracesSampleRate","rate","_startTransaction","_experiments","maxSpans","startIdleTransaction","onScope","tag","TRACEPARENT_REGEXP","RegExp","BAGGAGE_HEADER_NAME","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","dynamicSamplingContextToSentryBaggageHeader","entries","baggageHeader","_ref4","currentIndex","objectKey","objectValue","baggageEntry","encodeURIComponent","newBaggageHeader","objectToBaggageHeader","acc","dscKey","dscValue","baggageHeaderToObject","keyOrValue","decodeURIComponent","trim","_ref3","bindReporter","metric","reportAllChanges","prevValue","delta","forceReport","getNavigationEntry","__WEB_VITALS_POLYFILL__","getEntriesByType","navigation","navigationEntry","entryType","startTime","getNavigationEntryFromPerformanceTiming","getActivationStart","navEntry","activationStart","initMetric","navigationType","prerendering","rating","floor","observe","opts","PerformanceObserver","supportedEntryTypes","po","list","getEntries","buffered","onHidden","cb","once","onHiddenOrPageHide","visibilityState","removeEventListener","firstHiddenTime","getVisibilityWatcher","Infinity","timeStamp","reportedMetricIDs","isMeasurementValue","isFinite","_startChild","ctx","excluded","sourceKeys","indexOf","_objectWithoutPropertiesLoose","_excluded","msToSec","time","getBrowserPerformanceAPI","_lcpEntry","_clsEntry","_performanceCursor","startTrackingWebVitals","onReport","report","visibilityWatcher","handleEntry","handleEntries","processingStart","takeRecords","disconnect","clsCallback","sessionValue","sessionEntries","hadRecentInput","firstSessionEntry","lastSessionEntry","stopListening","onCLS","lcpCallback","lastEntry","capture","onLCP","_addPerformanceNavigationTiming","eventEnd","end","start","DEFAULT_TRACE_PROPAGATION_TARGETS","defaultRequestInstrumentationOptions","traceFetch","traceXHR","tracingOrigins","tracePropagationTargets","DEFAULT_BROWSER_TRACING_OPTIONS","markBackgroundTransactions","routingInstrumentation","customStartTransaction","startTransactionOnPageLoad","startTransactionOnLocationChange","startingUrl","pathname","enableLongTask","BrowserTracing","_collectWebVitals","enableInteractions","_step2","_iterator2","durationThreshold","_getCurrentHub","_this$options","instrumentRouting","shouldCreateSpanForRequest","_createRouteTransaction","onStartRouteTransaction","_registerInteractionListener","_traceFetch$traceXHR$","shouldCreateSpan","shouldAttachHeadersWithTargets","shouldAttachHeaders","__span","contentLength","contentLengthNum","currentScope","currentSpan","_handlerData$fetchDat","sentryBaggageHeader","sentryTraceHeader","newHeaders","append","existingBaggageHeader","baggage","newBaggageHeaders","addTracingHeadersToFetchRequest","fetchCallback","__sentry_xhr_span_id__","setRequestHeader","xhrCallback","instrumentOutgoingRequests","_this$options2","beforeNavigate","isPageloadTransaction","sentryTraceMetaTagValue","getMetaContent","baggageMetaTagValue","traceParentData","traceparent","matches","extractTraceparentData","baggageObject","curr","baggageHeaderToDynamicSamplingContext","expandedContext","modifiedContext","finalContext","_latestRouteName","_latestRouteSource","idleTransaction","responseStartTimestamp","requestStartTimestamp","performanceEntries","requestStart","responseEnd","responseStart","_addRequest","_addNavigationSpans","measureStartTimestamp","measureEndTimestamp","_addMeasureSpans","firstHidden","shouldRecord","resourceName","origin","initiatorType","transferSize","encodedBodySize","decodedBodySize","renderBlockingStatus","_addResourceSpans","connection","effectiveType","rtt","deviceMemory","hardwareConcurrency","_trackNavigator","oldValue","measurementTimestamp","normalizedValue","fidMark","cls","measurementName","element","size","sources","node","_tagMetricInfo","addPerformanceEntries","inflightInteractionTransaction","registerInteractionTransaction","_this3$options","currentTransaction","metaName","selector","metaTag","querySelector","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","Wrapper","asyncGeneratorStep","gen","_next","_throw","_asyncToGenerator","prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","integrations","dist","_options$maxValueLeng","maxValueLength","applyClientOptions","integrationNames","sdk","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","debugIdStackParserCache","filenameDebugIdMap","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","attachments","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","b","normalizeEvent","WeakMap","DSN_REGEX","dsnToString","dsn","withPassword","pass","port","projectId","dsnFromComponents","components","makeDsn","exec","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","createEnvelope","items","forEachEnvelopeItem","envelope","envelopeItem","encodeUTF8","textEncoder","TextEncoder","encode","serializeEnvelope","envHeaders","parts","itemHeaders","payload","stringifiedPayload","buffers","_step3","totalLength","buf","merged","offset","_iterator3","buffer","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","_metadataOrEvent$sdk","createEventEnvelopeHeaders","sdkInfo","tunnel","sent_at","NodeType$1","REPLAY_SESSION_KEY","REPLAY_EVENT_NAME","UNABLE_TO_SEND_REPLAY","RETRY_BASE_INTERVAL","RETRY_MAX_COUNT","NETWORK_BODY_MAX_SIZE","CONSOLE_ARG_MAX_SIZE","REPLAY_MAX_EVENT_BUFFER_SIZE","isShadowRoot","shadowRoot","isInputTypeMasked","maskInputOptions","actualType","maskInputValue","maskInputSelector","unmaskInputSelector","maskInputFn","text","hasAttribute","repeat","NodeType","ORIGINAL_ATTRIBUTE_NAME","getInputType","getInputValue","canvasService","canvasCtx","_id","tagNameRegex","IGNORED_NODE","defaultMaskFn","getCssRulesString","rules","cssRules","getCssRuleString","rule","cssStringified","cssText","isCSSImportRule","styleSheet","_a","validateStringifiedCssRule","URL_IN_CSS_REF","RELATIVE_PATH","DATA_URI","absoluteToStylesheet","quote1","path1","quote2","path2","path3","filePath","maybeQuote","part","EventType","IncrementalSource","MouseInteractions","CanvasContext","MediaInteractions","ReplayerEvents","SRCSET_NOT_SPACES","SRCSET_COMMAS_OR_SPACES","absoluteToDoc","attributeValue","isSVGElement","ownerSVGElement","getHref","transformAttribute","_tagName","maskAllText","unmaskTextSelector","maskTextFn","pos","collectCharacters","regEx","chars","descriptorsStr","inParens","getAbsoluteSrcsetString","attribute","_shouldMaskAttribute","needMaskingText","maskTextClass","maskTextSelector","nodeType","ELEMENT_NODE","closest","classList","contains","eIndex","lowerIfExists","maybeAttr","serializeNodeWithId","blockClass","blockSelector","unblockSelector","_options$skipChild","skipChild","_options$inlineStyles","inlineStylesheet","_options$maskInputOpt2","slimDOMOptions","_options$dataURLOptio2","dataURLOptions","_options$inlineImages","inlineImages","_options$recordCanvas","recordCanvas","onSerialize","onIframeLoad","_options$iframeLoadTi","iframeLoadTimeout","_options$keepIframeSr","keepIframeSrcFn","_options$preserveWhit","preserveWhiteSpace","_serializedNode","rootId","sheet","_options$maskInputOpt","_options$dataURLOptio","__sn","docId","DOCUMENT_NODE","compatMode","Document","childNodes","DOCUMENT_TYPE_NODE","DocumentType","publicId","systemId","needBlock","_isBlockedElement","HTMLFormElement","processedTagName","getValidTagName","attributes","_Array$from","_Array$from$_i","skipAttribute","stylesheet","styleSheets","find","rel","_cssText","innerText","textContent","checked","selected","__context","canvas","getContext","x","width","y","getImageData","originalGetImageData","Uint32Array","min","pixel","is2DCanvasBlank","rr_dataURL","toDataURL","quality","canvasDataURL","blankCanvas","image","crossOrigin","recordInlineImage","naturalWidth","naturalHeight","drawImage","warn","currentSrc","onload","rr_mediaState","paused","rr_mediaCurrentTime","currentTime","scrollLeft","rr_scrollLeft","scrollTop","rr_scrollTop","_n$getBoundingClientR","getBoundingClientRect","rr_width","rr_height","src","contentDocument","rr_src","isSVG","TEXT_NODE","parentTagName","isStyle","isScript","nextSibling","previousSibling","Text","CDATA_SECTION_NODE","CDATA","COMMENT_NODE","Comment","serializeNode","sn","comment","script","as","endsWith","headFavicon","headMetaDescKeywords","headMetaSocial","headMetaRobots","headMetaHttpEquiv","headMetaAuthorship","headMetaVerification","slimDOMExcluded","serializedNode","recordChild","isShadowHost","headWhitespace","bypassOptions","_i2","_Array$from2","serializedChildNode","isElement","_i3","_Array$from3","isShadow","iframeEl","win","fired","blankUrl","timer","onceIframeLoaded","iframeDoc","serializedIframeNode","attributeName","on","passive","DEPARTED_MIRROR_ACCESS_WARNING","_mirror","getId","getNode","removeNodeFromMap","throttle$1","wait","timeout","leading","remaining","trailing","hookSetter","isRevoked","patch","replacement","defineProperties","__rrweb_original__","getWindowHeight","innerHeight","documentElement","clientHeight","getWindowWidth","innerWidth","clientWidth","isBlocked","needUnblock","isIgnored","isAncestorRemoved","mirror","isTouchEvent","changedTouches","isIframeINode","hasShadowRoot","isNodeInLinkedList","receiver","DoubleLinkedList","position","addNode","__ln","removeNode","moveKey","parentId","isINode","MutationBuffer","frozen","locked","texts","removes","mapRemoves","movedMap","addedSet","Set","movedSet","droppedSet","processMutations","mutations","processMutation","adds","addList","getNextId","ns","nextId","pushAdd","_b","_c","_d","shadowHost","getRootNode","rootShadowHost","notInDoc","currentN","iframeManager","addIframe","shadowDomManager","addShadowRoot","iframe","childSn","attachIframe","observeAttachShadow","shift","isParentRemoved","isAncestorInSet","candidate","_node","mutationCb","m","setAttribute","old","style","styleObj","_i4","_Array$from4","pname","newValue","getPropertyValue","newPriority","getPropertyPriority","_i5","_Array$from5","addedNodes","genAdds","removedNodes","nodeId","deepDelete","targetId","childN","freeze","canvasManager","unfreeze","isFrozen","lock","unlock","addsSet","callbackWrapper","__rrweb__","mutationBuffers","getEventTarget","composedPath","initMutationObserver","rootEl","mutationBuffer","mutationObserverCtor","MutationObserver","__rrMutationObserver","angularZoneSymbol","Zone","__symbol__","observer","onMutation","attributeOldValue","characterData","characterDataOldValue","childList","subtree","initScrollObserver","_ref8","scrollCb","updatePosition","scrollEl","scrollingElement","sampling","scroll","wrapEventWithUserTriggeredFlag","v","userTriggered","INPUT_TAGS","lastInputValueMap","getNestedCSSRulePositions","childRule","hasNestedCSSRule","parentRule","CSSGroupingRule","CSSMediaRule","CSSSupportsRule","CSSConditionRule","unshift","parentStyleSheet","recurse","initObservers","hooks","currentWindow","defaultView","mousemoveCb","mouseInteractionCb","viewportResizeCb","inputCb","mediaInteractionCb","styleSheetRuleCb","styleDeclarationCb","canvasMutationCb","fontCb","mutation","mousemove","mouseInteraction","viewportResize","mediaInteaction","styleSheetRule","styleDeclaration","canvasMutation","font","mergeHooks","lastH","lastW","updateDimension","_step4","mutationObserver","mousemoveHandler","_ref5","timeBaseline","callbackThreshold","mousemoveCallback","positions","wrappedCb","totalOffset","timeOffset","_ref6","clientX","clientY","DragEvent","Drag","MouseEvent","MouseMove","TouchMove","h","initMoveObserver","mouseInteractionHandler","_ref7","disableMap","eventKey","getHandler","initMouseInteractionObserver","scrollHandler","viewportResizeHandler","inputHandler","_ref10","ignoreClass","ignoreSelector","userTriggeredOnInput","eventHandler","isTrusted","parentElement","isChecked","cbWithDedup","querySelectorAll","lastInputValue","propertyDescriptor","HTMLInputElement","hookProperties","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","initInputObserver","mediaInteractionHandler","_ref17","volume","muted","media","initMediaInteractionObserver","styleSheetObserver","_ref11","_ref12","CSSStyleSheet","insertRule","thisArg","argumentsList","ownerNode","deleteRule","supportedNestedCSSRuleTypes","canMonkeyPatchNestedCSSRule","unmodifiedFunctions","_ref13","typeKey","_ref14","initStyleSheetObserver","styleDeclarationObserver","_ref15","_ref16","setProperty","CSSStyleDeclaration","priority","removeProperty","remove","initStyleDeclarationObserver","fontObserver","collectFonts","_ref18","fontMap","originalFontFace","FontFace","family","descriptors","fontFace","fontSource","restoreHandler","fonts","initFontObserver","pluginHandlers","_iterator4","plugins","plugin","IframeManager","iframes","_proto3","addLoadListener","loadListener","isAttachIframe","ShadowDomManager","restorePatches","manager","HTMLElement","ownerDocument","_proto4","iframeElement","restorePatch","lookup","charCodeAt","webGLVarMap","saveWebGLVar","isInstanceOfWebGLObject","contextMap","variableListFor","serializeArg","Float32Array","Float64Array","Int32Array","Uint16Array","Int16Array","Int8Array","Uint8ClampedArray","rr_type","ArrayBuffer","base64","arraybuffer","bytes","DataView","byteOffset","byteLength","HTMLImageElement","ImageData","serializeArgs","supportedWebGLConstructorNames","patchGLPrototype","_step6","_loop2","recordArgs","hookHandler","setter","_iterator6","getOwnPropertyNames","wrappedEmit","takeFullSnapshot","CanvasManager","_proto5","pendingCanvasMutations","rafStamps","latestId","invokeId","initCanvasMutationObserver","resetObservers","startRAFTimestamping","startPendingCanvasMutationFlusher","canvasContextReset","HTMLCanvasElement","contextType","initCanvasContextObserver","canvas2DReset","_step5","_loop","CanvasRenderingContext2D","imgd","pix","_iterator5","initCanvas2DMutationObserver","canvasWebGL1and2Reset","WebGLRenderingContext","WebGL","WebGL2RenderingContext","WebGL2","initCanvasWebGLMutationObserver","flushPendingCanvasMutations","setLatestRAFTimestamp","_this8","flushPendingCanvasMutationFor","valuesWithType","rest","t","getOwnPropertySymbols","propertyIsEnumerable","__rest","commands","wrapEvent","child","checkoutEveryNms","checkoutEveryNth","_options$blockClass","_options$blockSelecto","_options$unblockSelec","_options$ignoreClass","_options$ignoreSelect","_options$maskTextClas","_options$maskTextSele","_options$maskInputSel","_options$unmaskTextSe","_options$unmaskInputS","_options$inlineStyles2","_options$maskAllText","maskAllInputs","_maskInputOptions","_slimDOMOptions","packFn","_options$sampling","mousemoveWait","_options$recordCanvas2","_options$userTriggere","_options$collectFonts","_options$inlineImages2","_options$keepIframeSr2","lastFullSnapshotEvent","color","date","month","number","range","tel","week","textarea","select","radio","checkbox","NodeList","DOMTokenList","Node","incrementalSnapshotCount","isCheckout","FullSnapshot","IncrementalSnapshot","Mutation","_step7","_iterator7","eventProcessor","exceedCount","exceedTime","wrappedMutationEmit","wrappedScrollEmit","Scroll","wrappedCanvasMutationEmit","CanvasMutation","Meta","_snapshot","_ref4$blockClass","_ref4$blockSelector","_ref4$unblockSelector","_ref4$maskTextClass","_ref4$maskTextSelecto","_ref4$unmaskTextSelec","_ref4$inlineStyleshee","_ref4$inlineImages","_ref4$recordCanvas","_ref4$maskInputSelect","_ref4$unmaskInputSele","_ref4$maskAllText","_ref4$maskAllInputs","_ref4$slimDOM","slimDOM","_ref4$keepIframeSrcFn","idNodeMap","snapshot","initialOffset","left","pageXOffset","top","pageYOffset","DomContentLoaded","MouseInteraction","ViewportResize","Input","MediaInteraction","StyleSheetRule","StyleDeclaration","Font","Plugin","Load","addBreadcrumbEvent","replay","triggerUserActivity","checkAndHandleExpiredSession","addUpdate","throttledAddEvent","Custom","addCustomEvent","freezePage","getClickTargetNode","getTargetNode","isEventWithTarget","ClickDetector","_proto6","slowClickConfig","_addBreadcrumbEvent","_timeout","_multiClickTimeout","multiClickTimeout","_threshold","_scollTimeout","scrollTimeout","_replay","_ignoreSelector","_lastMutation","_lastScroll","_clicks","addListeners","_this9","nowInSeconds","cleanupWindowOpen","originalWindowOpen","clickHandler","_handleMultiClick","obs","_teardown","removeListeners","_checkClickTimeout","handleClick","SLOW_CLICK_TAGS","ignoreElement","isClickBreadcrumb","_getClick","newClick","clickBreadcrumb","clickCount","_scheduleCheckClicks","click","_this10","_checkClicks","_this11","timedOutClicks","mutationAfter","scrollAfter","actionTime","_i6","_timedOutClicks","_generateBreadcrumbs","hadScroll","hadMutation","isSlowClick","timeAfterClickMs","endReason","route","getCurrentRoute","_this12","createBreadcrumb","ATTRIBUTES_TO_RECORD","getAttributesToRecord","normalizedKey","getBaseDomBreadcrumb","NAVIGATION_ENTRY_KEYS","isNavigationEntryEqual","every","timestampToMs","EventBufferArray","_proto7","events","_totalSize","destroy","addEvent","_addEvent","_callee","eventSize","_context2","EventBufferSizeExceededError","_x","_this13","eventsRet","getEarliestTimestamp","WorkerHandler","worker","_worker","_proto8","ensureReady","_this14","_ensureReadyPromise","_ref19","success","terminate","postMessage","_this15","_getAndIncrementId","_ref20","EventBufferCompressionWorker","_proto9","_earliestTimestamp","_sendEventToWorker","_finishRequest","_finishRequest2","_callee2","_context3","EventBufferProxy","_fallback","_compression","_used","_ensureWorkerIsLoadedPromise","_ensureWorkerIsLoaded","_proto10","_finish","_callee3","_context4","ensureWorkerIsLoaded","_ensureWorkerIsLoaded2","_callee4","_context5","t0","_switchToCompressionWorker","_switchToCompressionWorker2","_callee5","addEventPromises","_iterator8","_step8","_context6","all","hasEvents","_Error","isExpired","initialTime","expiry","targetTime","isSessionExpired","timeouts","maxSessionLife","lastActivity","sessionIdleExpire","isSampled","saveSession","sessionStorage","setItem","segmentId","shouldRefresh","createSession","_ref22","sessionSampleRate","allowBuffering","_ref22$stickySession","stickySession","getSessionSampleType","_ref23","sessionStringFromStorage","getItem","parse","fetchSession","isCustomEvent","_x2","_x3","_x4","_addEvent2","_callee10","replayOptions","eventAfterPossibleCallback","_context11","eventBuffer","isPaused","sessionIdlePause","beforeAddRecordingEvent","isTransactionEvent","handleAfterSendEvent","enforceStatusCode","transport","getTransport","send","__sentry__baseTransport__","isBaseTransportSend","sendResponse","statusCode","traceIds","errorIds","recordingMode","replayId","sendBufferedReplayOrFlush","createPerformanceSpans","_ref24","addNetworkBreadcrumb","isEnabled","_isSentryRequest","OBJ","OBJ_KEY","OBJ_KEY_STR","OBJ_VAL","OBJ_VAL_STR","OBJ_VAL_COMPLETED","ARR","ARR_VAL","ARR_VAL_STR","ARR_VAL_COMPLETED","ALLOWED_PRIMITIVES","_evaluateJsonPos","json","curStep","char","_isEscaped","_handleObj","_handleArr","_handleColon","_handleComma","_handleObjClose","_handleArrClose","_handleQuote","fixJson","incompleteJson","lastPos","lastStep","startPos","lastIndexOf","_maybeFixIncompleteObjValue","_findLastArrayDelimiter","_maybeFixIncompleteArrValue","_fixLastStep","completeJson","evaluateJson","getBodySize","URLSearchParams","FormData","formDataStr","_serializeFormData","Blob","parseContentLengthHeader","getBodyString","makeNetworkReplayBreadcrumb","buildSkippedNetworkRequestOrResponse","bodySize","_meta","warnings","buildNetworkRequestOrResponse","_normalizeNetworkBody","first","last","exceedsSizeLimit","e3","normalizeNetworkBody","normalizedBody","getAllowedHeaders","allowedHeaders","filteredHeaders","formData","urlMatches","urls","fullUrl","baseURI","fixedUrl","URL","getFullUrl","_captureFetchBreadcrumbToReplay","_callee11","_context12","_prepareFetchData","_x8","_x9","_x10","_prepareFetchData2","_callee12","_breadcrumb$data2","_breadcrumb$data2$sta","requestBodySize","responseBodySize","captureDetails","_context13","request_body_size","response_body_size","networkDetailAllowUrls","_getRequestInfo","_getResponseInfo","_ref25","networkCaptureBodies","networkRequestHeaders","getHeadersFromOptions","_getFetchRequestArgBody","_x11","_x12","_x13","_x14","_getResponseInfo2","_callee13","_ref26","networkResponseHeaders","bodyText","_context14","getAllHeaders","_parseFetchBody","_x15","_parseFetchBody2","_callee14","_context15","allHeaders","_captureXhrBreadcrumbToReplay","_callee15","_context16","_prepareXhrData","_breadcrumb$data","_breadcrumb$data$stat","getAllResponseHeaders","_line$split","getResponseHeaders","responseText","handleNetworkBreadcrumbs","_replay$getOptions","_isXhrBreadcrumb","_isXhrHint","reqSize","resSize","getResponseHeader","enrichXhrBreadcrumb","_x16","_x17","_x18","captureXhrBreadcrumbToReplay","_isFetchBreadcrumb","_isFetchHint","enrichFetchBreadcrumb","_x5","_x6","_x7","captureFetchBreadcrumbToReplay","beforeAddNetworkBreadcrumb","handleFetch","handleFetchSpanListener","handleXhr","handleXhrSpanListener","e2","_LAST_BREADCRUMB","hasHooks","addMemoryEntry","_x19","_addMemoryEntry","_callee16","_context17","memoryEntry","memory","jsHeapSizeLimit","totalJSHeapSize","usedJSHeapSize","ENTRY_TYPES","_ENTRY_TYPES","responseStatus","getAbsoluteTime","paint","domComplete","domContentLoadedEventStart","domContentLoadedEventEnd","domInteractive","loadEventStart","loadEventEnd","redirectCount","startTimeOrNavigationActivation","createPerformanceEntry","createReplayEnvelope","replayEvent","recordingData","prepareRecordingData","_ref27","payloadWithSequence","replayHeaders","sequence","prepareReplayEvent","_x20","_prepareReplayEvent","_callee17","_ref28","preparedEvent","_ref36","_context18","_integrations","platform","getSdkMetadata","sendReplayRequest","_x21","_sendReplayRequest","_callee18","_ref29","segment_id","eventContext","preparedRecordingData","initialTimestamp","baseEvent","_context19","replay_start_timestamp","error_ids","trace_ids","replay_id","replay_type","cause","TransportStatusCodeError","_Error2","sendReplay","_x22","_x23","_sendReplay","_callee20","replayData","retryConfig","_context21","count","interval","_retryCount","_callee19","_context20","THROTTLED","ReplayContainer","_proto11","_ref30","maxCount","durationSeconds","counter","isThrottled","_this16","recordingOptions","__init8","__init9","__init10","__init11","__init12","__init13","__init14","__init15","__init16","__init17","__init18","_recordingOptions","_debouncedFlush","callbackReturnValue","timerId","maxTimerId","maxWait","invokeFunc","cancelTimers","debounced","cancel","flush","debounce","_flush","flushMinDelay","flushMaxDelay","_throttledAddEvent","_cleanup","wasThrottled","_this$getOptions","slowClickTimeout","slowClickIgnoreSelectors","clickDetector","performanceEvents","_performanceObserver","_flushLock","_lastActivity","_isEnabled","_isPaused","_hasInitializedCoreListeners","_stopRecording","_context","initialUrl","initializeSampling","_this$_options","errorSampleRate","_loadAndCheckSession","_initializeRecording","_handleException","previousSessionId","startBuffering","startRecording","hadFirstEvent","_isCheckout","setInitialState","useCompressionOption","useCompression","blockAllMedia","networkDetailHasUrls","networkRequestHasHeaders","networkResponseHasHeaders","createOptionsEvent","addSettingsEvent","earliestEvent","delayFlushOnCheckout","conditionalFlush","cancelFlush","flushImmediate","_onMutationHandler","stopRecording","_stop","_callee6","_context7","_removeListeners","force","removeItem","deleteSession","_x24","pause","resume","_sendBufferedReplayOrFlush","_callee7","_ref31$continueRecord","continueRecording","activityTime","hasStoppedRecording","_context8","_updateUserActivity","_updateSessionActivity","_maybeSaveSession","_x25","cbResult","updateUserActivity","getSessionId","oldSessionId","_triggerFullSnapshot","urlPath","_clearContext","_this17","lastTransaction","_ref21","Worker","workerUrl","createObjectURL","createEventBuffer","_addListeners","_getSession3","currentSessionId","_handleVisibilityChange","_handleWindowBlur","_handleWindowFocus","_handleKeyboardEvent","newBreadcrumb","isTruncated","normalizedArgs","normalizedArg","fixedJson","normalizeConsoleBreadcrumb","handleScope","handleScopeListener","_getDomTarget","isClick","getDomTarget","handleDom","altKey","metaKey","ctrlKey","handleDomListener","handleHistory","handleHistorySpanListener","includeAfterSendEventHandling","afterSendHandler","isReplayEvent","isRrwebError","captureExceptions","isErrorEventSampled","shouldSampleForBufferEvent","handleGlobalEventListener","performanceObserver","currentList","newList","_currentList$reduce","existingNavigationEntries","existingLcpEntries","existingEntries","newEntries","newNavigationEntries","newLcpEntry","newPerformanceEntries","setupPerformanceObserver","_this18","_doChangeToForegroundTasks","_doChangeToBackgroundTasks","_this19","_this20","_this21","shiftKey","isInputElement","hasModifierKey","isCharacterKey","getKeyboardBreadcrumb","handleKeyboardEvent","expired","_createCustomBreadcrumb","checkout","_this22","_addPerformanceEntries","createPerformanceEntries","_updateInitialTimestampFromEventBuffer","_popEventContext","_runFlush","_runFlush2","_callee8","_context9","_this23","_ref32","_callee9","_temp2","_ref33$force","_context10","_x26","_this24","mutationLimit","overMutationLimit","mutationBreadcrumbLimit","getOption","selectors","defaultSelectors","deprecatedClassOption","deprecatedSelectorOption","deprecatedSelectors","allSelectors","isBrowser","MEDIA_SELECTORS","DEFAULT_NETWORK_HEADERS","_initialized","Replay","_proto12","_temp3","_ref35","_ref35$flushMinDelay","_ref35$flushMaxDelay","_ref35$stickySession","_ref35$useCompression","_ref35$_experiments","_ref35$maskAllText","_ref35$maskAllInputs","_ref35$blockAllMedia","_ref35$mutationBreadc","_ref35$mutationLimit","_ref35$slowClickTimeo","_ref35$slowClickIgnor","_ref35$networkDetailA","_ref35$networkCapture","_ref35$networkRequest","_ref35$networkRespons","_ref35$mask","mask","_ref35$unmask","unmask","_ref35$block","block","_ref35$unblock","unblock","_ref35$ignore","ignore","maskFn","password","_ref34","maskSelector","unmaskSelector","getPrivacyOptions","_initialOptions","_getMergedNetworkHeaders","_isInitialized","_this25","_setup","_initialize","getReplayId","finalOptions","initialOptions","opt","replaysSessionSampleRate","replaysOnErrorSampleRate","loadReplayOptionsFromClient","SDK_VERSION","SentryError","logLevel","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","_metadata","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","_encodedAuth","installedIntegrations","setupIntegration","integrationIndex","BaseClient","_dsn","_transport","transportOptions","_integrationsInitialized","_numProcessing","_outcomes","_hooks","_process","eventFromException","_captureEvent","promisedEvent","eventFromMessage","sendSession","_isClientDoneProcessing","clientFinished","transportFlushed","close","enabled","getIntegrationById","integrationId","addIntegration","sendEvent","newItem","env","eventType","packages","enhanceEventWithSdkInfo","envelopeHeaders","createEventEnvelope","promise","_sendEnvelope","createSessionEnvelope","_event","sendClientReports","hook","_updateSessionFromEvent","crashed","errored","exceptions","sessionNonTerminal","ticked","clearInterval","_prepareEvent","_processEvent","finalEvent","isTransaction","beforeSendLabel","dataCategory","__sentry__","beforeSend","beforeSendTransaction","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","transactionInfo","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","sdkSource","SENTRY_SDK_SOURCE","_flushOutcomes","breadcrumbIntegration","captureUserFeedback","feedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","discarded_events","DEFAULT_RETRY_AFTER","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","task","$","taskProducer","drain","capturedSetTimeout","makePromiseBuffer","bufferSize","rateLimits","filteredEnvelopeItems","limits","envelopeItemDataCategory","disabledUntil","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","updatedRateLimits","rateLimitHeader","retryAfterHeader","_limit$split","retryAfter","categories","headerDelay","delay","headerDate","parseRetryAfterHeader","updateRateLimits","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","lastFrameFunction","firstFrameFunction","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","Dedupe","currentEvent","previousEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","_previousEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","injectionPoint","Integrations","CaptureConsole","levels","_levels","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"forum.tracing.replay.js","mappings":";wCAYO,SAASA,IAGd,QCU4C,oBAA9BC,2BAA+CA,4BDRsB,qBAAjFC,OAAOC,UAAUC,SAASC,KAAwB,oBAAZC,QAA0BA,QAAU,EAE9E,6CEnBA,IAAIC,EAAUC,EAAAA,KAAAA,QACd,SAASC,IACP,aACAC,EAAOC,QAAUF,EAAsB,WACrC,OAAOE,CACT,EAAGD,EAAOC,QAAQC,YAAa,EAAMF,EAAOC,QAAiB,QAAID,EAAOC,QACxE,IAAIA,EAAU,CAAC,EACbE,EAAKX,OAAOC,UACZW,EAASD,EAAGE,eACZC,EAAiBd,OAAOc,gBAAkB,SAAUC,EAAKC,EAAKC,GAC5DF,EAAIC,GAAOC,EAAKC,KAClB,EACAC,EAAU,mBAAqBC,OAASA,OAAS,CAAC,EAClDC,EAAiBF,EAAQG,UAAY,aACrCC,EAAsBJ,EAAQK,eAAiB,kBAC/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tB0kB,IAAAA,SAAe1kB,GAAqB,GAAbA,EAAKlQ,OACtBoxG,EAAG,CACThhG,WAAY,WACZpQ,GAAIkQ,EAAKlQ,OACRixG,GAAW/gG,EAAKK,WAHnB2gG,EAG6BE,EAGxBx8E,IAAAA,KAAS,6BACZs8E,EAAS5gG,MAAQJ,EAAKI,UAEfskB,IAAAA,KAAS3kB,SAAsC,GAA3B2kB,IAAAA,KAAS3kB,QAAQohG,SAC9CH,EAAW,CACTlxG,GAAI40B,IAAAA,KAAS3kB,QAAQohG,QAG3B,CAEA,OAAOH,CACT,EAEAt8E,IAAAA,aAAiBniB,IAAI,cAAc,WACjCgG,KAAgBmF,QAAQ6yF,OAAOM,cACjC","sources":["webpack://@fof/sentry/../../src/node.ts","webpack://@fof/sentry/../../src/env.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/regeneratorRuntime.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/typeof.js","webpack://@fof/sentry/./node_modules/@babel/runtime/regenerator/index.js","webpack://@fof/sentry/webpack/bootstrap","webpack://@fof/sentry/webpack/runtime/compat get default export","webpack://@fof/sentry/webpack/runtime/define property getters","webpack://@fof/sentry/webpack/runtime/global","webpack://@fof/sentry/webpack/runtime/harmony module decorator","webpack://@fof/sentry/webpack/runtime/hasOwnProperty shorthand","webpack://@fof/sentry/webpack/runtime/make namespace object","webpack://@fof/sentry/external root \"flarum.core.compat['forum/app']\"","webpack://@fof/sentry/../../src/debug-build.ts","webpack://@fof/sentry/../../src/worldwide.ts","webpack://@fof/sentry/../../src/logger.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/extends.js","webpack://@fof/sentry/../../src/is.ts","webpack://@fof/sentry/../../src/browser.ts","webpack://@fof/sentry/../../src/string.ts","webpack://@fof/sentry/../../src/object.ts","webpack://@fof/sentry/../../src/misc.ts","webpack://@fof/sentry/../../src/syncpromise.ts","webpack://@fof/sentry/../../src/eventProcessors.ts","webpack://@fof/sentry/../../src/time.ts","webpack://@fof/sentry/../../src/constants.ts","webpack://@fof/sentry/../../src/session.ts","webpack://@fof/sentry/../../src/stacktrace.ts","webpack://@fof/sentry/../../src/normalize.ts","webpack://@fof/sentry/../../src/memo.ts","webpack://@fof/sentry/../../src/baggage.ts","webpack://@fof/sentry/../../src/tracing.ts","webpack://@fof/sentry/../../../src/utils/spanUtils.ts","webpack://@fof/sentry/../../../src/utils/prepareEvent.ts","webpack://@fof/sentry/../../src/exports.ts","webpack://@fof/sentry/../../../src/utils/getRootSpan.ts","webpack://@fof/sentry/../../../src/tracing/dynamicSamplingContext.ts","webpack://@fof/sentry/../../../src/utils/applyScopeDataToEvent.ts","webpack://@fof/sentry/../../src/scope.ts","webpack://@fof/sentry/../../src/version.ts","webpack://@fof/sentry/../../src/hub.ts","webpack://@fof/sentry/../../src/integration.ts","webpack://@fof/sentry/../../../src/integrations/inboundfilters.ts","webpack://@fof/sentry/../../../src/integrations/functiontostring.ts","webpack://@fof/sentry/../../../src/helpers.ts","webpack://@fof/sentry/../../../../src/integrations/trycatch.ts","webpack://@fof/sentry/../../../src/instrument/_handlers.ts","webpack://@fof/sentry/../../../src/instrument/globalError.ts","webpack://@fof/sentry/../../../src/instrument/globalUnhandledRejection.ts","webpack://@fof/sentry/../../../src/eventbuilder.ts","webpack://@fof/sentry/../../../../src/integrations/globalhandlers.ts","webpack://@fof/sentry/../../../src/instrument/console.ts","webpack://@fof/sentry/../../../src/instrument/dom.ts","webpack://@fof/sentry/../../../src/instrument/xhr.ts","webpack://@fof/sentry/../../src/supports.ts","webpack://@fof/sentry/../../../src/instrument/fetch.ts","webpack://@fof/sentry/../../../src/vendor/supportsHistory.ts","webpack://@fof/sentry/../../../src/instrument/history.ts","webpack://@fof/sentry/../../src/severity.ts","webpack://@fof/sentry/../../src/url.ts","webpack://@fof/sentry/../../../../src/integrations/breadcrumbs.ts","webpack://@fof/sentry/../../src/aggregate-errors.ts","webpack://@fof/sentry/../../../../src/integrations/linkederrors.ts","webpack://@fof/sentry/../../../src/metrics/metric-summary.ts","webpack://@fof/sentry/../../../../src/integrations/httpcontext.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/typeof.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/createClass.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/toPrimitive.js","webpack://@fof/sentry/../../src/semanticAttributes.ts","webpack://@fof/sentry/../../../src/tracing/spanstatus.ts","webpack://@fof/sentry/../../../src/tracing/span.ts","webpack://@fof/sentry/../../../src/utils/hasTracingEnabled.ts","webpack://@fof/sentry/../../../src/tracing/trace.ts","webpack://@fof/sentry/../../../src/tracing/transaction.ts","webpack://@fof/sentry/../../../src/tracing/idletransaction.ts","webpack://@fof/sentry/../../../src/tracing/utils.ts","webpack://@fof/sentry/../../../src/tracing/errors.ts","webpack://@fof/sentry/../../../src/tracing/sampling.ts","webpack://@fof/sentry/../../../src/tracing/hubextensions.ts","webpack://@fof/sentry/../../../src/common/debug-build.ts","webpack://@fof/sentry/../../../../../../src/browser/web-vitals/lib/polyfills/interactionCountPolyfill.ts","webpack://@fof/sentry/../../../src/browser/types.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/bindReporter.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getNavigationEntry.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getActivationStart.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/initMetric.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/generateUniqueID.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/observe.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/onHidden.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getCLS.ts","webpack://@fof/sentry/../../../../../src/browser/web-vitals/lib/getVisibilityWatcher.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getFID.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getINP.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/getLCP.ts","webpack://@fof/sentry/../../../../src/browser/web-vitals/onTTFB.ts","webpack://@fof/sentry/../../../src/browser/instrument.ts","webpack://@fof/sentry/../../src/dsn.ts","webpack://@fof/sentry/../../src/envelope.ts","webpack://@fof/sentry/../../src/span.ts","webpack://@fof/sentry/../../../../src/browser/metrics/utils.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","webpack://@fof/sentry/../../../../src/browser/metrics/index.ts","webpack://@fof/sentry/../../../src/browser/request.ts","webpack://@fof/sentry/../../../src/common/fetch.ts","webpack://@fof/sentry/../../../src/browser/browsertracing.ts","webpack://@fof/sentry/../../../src/browser/router.ts","webpack://@fof/sentry/../../../src/browser/backgroundtab.ts","webpack://@fof/sentry/../../../src/tracing/measurement.ts","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/construct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","webpack://@fof/sentry/./node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","webpack://@fof/sentry/../../../src/buildPolyfills/_optionalChain.ts","webpack://@fof/sentry/../../../src/utils/isSentryRequestUrl.ts","webpack://@fof/sentry/../../src/ratelimit.ts","webpack://@fof/sentry/../../src/isBrowser.ts","webpack://@fof/sentry/../../../src/constants.ts","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js","webpack://@fof/sentry/../../../src/buildPolyfills/_nullishCoalesce.ts","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/index.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js","webpack://@fof/sentry/../../../src/types/rrweb.ts","webpack://@fof/sentry/../../../src/util/timestamp.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/addBreadcrumbEvent.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/domUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/onWindowOpen.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleClick.ts","webpack://@fof/sentry/../../../../../node_modules/@sentry-internal/rrweb-snapshot/es/rrweb-snapshot.js","webpack://@fof/sentry/../../../src/util/createBreadcrumb.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/getAttributesToRecord.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleDom.ts","webpack://@fof/sentry/../../../src/util/createPerformanceEntries.ts","webpack://@fof/sentry/../../../src/coreHandlers/performanceObserver.ts","webpack://@fof/sentry/../../../src/debug-build.ts","webpack://@fof/sentry/../../../src/util/log.ts","webpack://@fof/sentry/../../../src/eventBuffer/error.ts","webpack://@fof/sentry/../../../src/eventBuffer/EventBufferArray.ts","webpack://@fof/sentry/../../../src/eventBuffer/WorkerHandler.ts","webpack://@fof/sentry/../../../src/eventBuffer/EventBufferCompressionWorker.ts","webpack://@fof/sentry/../../../src/eventBuffer/EventBufferProxy.ts","webpack://@fof/sentry/../../../src/util/hasSessionStorage.ts","webpack://@fof/sentry/../../../src/util/isSampled.ts","webpack://@fof/sentry/../../../src/session/Session.ts","webpack://@fof/sentry/../../../src/session/saveSession.ts","webpack://@fof/sentry/../../../src/session/createSession.ts","webpack://@fof/sentry/../../../src/util/isExpired.ts","webpack://@fof/sentry/../../../src/util/isSessionExpired.ts","webpack://@fof/sentry/../../../src/session/shouldRefreshSession.ts","webpack://@fof/sentry/../../../src/session/loadOrCreateSession.ts","webpack://@fof/sentry/../../../src/session/fetchSession.ts","webpack://@fof/sentry/../../../src/util/addEvent.ts","webpack://@fof/sentry/../../../src/util/eventUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleAfterSendEvent.ts","webpack://@fof/sentry/../../../src/util/createPerformanceSpans.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/addNetworkBreadcrumb.ts","webpack://@fof/sentry/../../../src/util/shouldFilterRequest.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/networkUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/fetchUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/xhrUtils.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleNetworkBreadcrumbs.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleFetch.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleXhr.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleScope.ts","webpack://@fof/sentry/../../../src/util/addGlobalListeners.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleHistory.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleGlobalEvent.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/addFeedbackBreadcrumb.ts","webpack://@fof/sentry/../../../src/util/isRrwebError.ts","webpack://@fof/sentry/../../../src/coreHandlers/util/shouldSampleForBufferEvent.ts","webpack://@fof/sentry/../../src/baseclient.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleBeforeSendEvent.ts","webpack://@fof/sentry/../../../src/util/addMemoryEntry.ts","webpack://@fof/sentry/../../../src/util/handleRecordingEmit.ts","webpack://@fof/sentry/../../../src/util/createReplayEnvelope.ts","webpack://@fof/sentry/../../../src/util/prepareRecordingData.ts","webpack://@fof/sentry/../../../src/util/prepareReplayEvent.ts","webpack://@fof/sentry/../../../src/util/sendReplayRequest.ts","webpack://@fof/sentry/../../../src/util/sendReplay.ts","webpack://@fof/sentry/../../../src/util/throttle.ts","webpack://@fof/sentry/../../../src/replay.ts","webpack://@fof/sentry/../../../src/util/debounce.ts","webpack://@fof/sentry/../../../src/session/clearSession.ts","webpack://@fof/sentry/../../../src/eventBuffer/index.ts","webpack://@fof/sentry/../../../../replay-worker/build/npm/esm/index.js","webpack://@fof/sentry/../../../../replay-worker/build/npm/esm/worker.ts","webpack://@fof/sentry/../../../src/coreHandlers/handleKeyboardEvent.ts","webpack://@fof/sentry/../../../src/util/getPrivacyOptions.ts","webpack://@fof/sentry/../../../src/integration.ts","webpack://@fof/sentry/../../../src/util/maskAttribute.ts","webpack://@fof/sentry/../../src/error.ts","webpack://@fof/sentry/../../src/api.ts","webpack://@fof/sentry/../../../src/metrics/envelope.ts","webpack://@fof/sentry/../../../src/metrics/utils.ts","webpack://@fof/sentry/../../../src/client.ts","webpack://@fof/sentry/../../../src/utils/sdkMetadata.ts","webpack://@fof/sentry/../../../src/userfeedback.ts","webpack://@fof/sentry/../../src/clientreport.ts","webpack://@fof/sentry/../../../src/transports/base.ts","webpack://@fof/sentry/../../src/promisebuffer.ts","webpack://@fof/sentry/../../../../src/transports/utils.ts","webpack://@fof/sentry/../../../../src/transports/fetch.ts","webpack://@fof/sentry/../../../src/stack-parsers.ts","webpack://@fof/sentry/../../../../src/integrations/dedupe.ts","webpack://@fof/sentry/../../../src/sdk.ts","webpack://@fof/sentry/../../../src/captureconsole.ts","webpack://@fof/sentry/./src/forum/index.js"],"sourcesContent":["/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\nimport { isBrowserBundle } from './env';\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-expect-error __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\n","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = (module) => {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: () => {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = flarum.core.compat['forum/app'];","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","export const DEFAULT_ENVIRONMENT = 'production';\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // 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)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n for (const key of Object.keys(currBaggageObject)) {\n acc[key] = currBaggageObject[key];\n }\n return acc;\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext?: Partial,\n): string | undefined {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n","import type { PropagationContext, TraceparentData } from '@sentry/types';\n\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { uuid4 } from './misc';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent?: string): TraceparentData | undefined {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create tracing context from incoming headers.\n *\n * @deprecated Use `propagationContextFromHeaders` instead.\n */\n// TODO(v8): Remove this function\nexport function tracingContextFromHeaders(\n sentryTrace: Parameters[0],\n baggage: Parameters[0],\n): {\n traceparentData: ReturnType;\n dynamicSamplingContext: ReturnType;\n propagationContext: PropagationContext;\n} {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceparentData,\n dynamicSamplingContext: undefined,\n propagationContext: {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n },\n };\n } else {\n return {\n traceparentData,\n dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n propagationContext: {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n },\n };\n }\n}\n\n/**\n * Create a propagation context from incoming headers.\n */\nexport function propagationContextFromHeaders(\n sentryTrace: string | undefined,\n baggage: string | number | boolean | string[] | null | undefined,\n): PropagationContext {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n };\n } else {\n return {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n };\n }\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n traceId: string = uuid4(),\n spanId: string = uuid4().substring(16),\n sampled?: boolean,\n): string {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial | EventHint): hint is Partial {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","export const SDK_VERSION = '7.119.1';\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n IntegrationFnResult,\n Options,\n} from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { addGlobalEventProcessor } from './eventProcessors';\nimport { getClient } from './exports';\nimport { getCurrentHub } from './hub';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Pick): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1) {\n // eslint-disable-next-line deprecation/deprecation\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (client.on && typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (client.addEventProcessor && typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client || !client.addIntegration) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Convert a new integration function to the legacy class syntax.\n * In v8, we can remove this and instead export the integration functions directly.\n *\n * @deprecated This will be removed in v8!\n */\nexport function convertIntegrationFnToClass(\n name: string,\n fn: Fn,\n): IntegrationClass {\n return Object.assign(\n function ConvertedIntegration(...args: Parameters): Integration {\n return fn(...args);\n },\n { id: name },\n ) as unknown as IntegrationClass;\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration(fn: Fn): (...args: Parameters) => IntegrationFnResult {\n return fn;\n}\n","import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/,\n /^Cannot redefine property: googletag$/,\n];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options: Partial = {}) => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\n/**\n * Inbound filters configurable by the user.\n * @deprecated Use `inboundFiltersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const InboundFilters = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n inboundFiltersIntegration,\n) as IntegrationClass void }> & {\n new (\n options?: Partial<{\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n }>,\n ): Integration;\n};\n\nfunction _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if (DEBUG_BUILD && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","import type { Client, Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\nimport { getClient } from '../exports';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nlet originalFunctionToString: () => void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * @deprecated Use `functionToStringIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const FunctionToString = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n functionToStringIntegration,\n) as IntegrationClass void }>;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type FunctionToString = typeof FunctionToString;\n","import type { browserTracingIntegration } from '@sentry-internal/tracing';\nimport { BrowserTracing } from '@sentry-internal/tracing';\nimport { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Integration, Mechanism, WrappedFunction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n *\n * @deprecated This type will be removed in the next major version of the Sentry SDK. `showReportDialog` will still be around, however the `eventId` option will now be required.\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n /** Callback after reportDialog closed */\n onClose?(this: void): void;\n}\n\n/**\n * This is a slim shim of `browserTracingIntegration` for the CDN bundles.\n * Since the actual functional integration uses a different code from `BrowserTracing`,\n * we want to avoid shipping both of them in the CDN bundles, as that would blow up the size.\n * Instead, we provide a functional integration with the same API, but the old implementation.\n * This means that it's not possible to register custom routing instrumentation, but that's OK for now.\n * We also don't expose the utilities for this anyhow in the CDN bundles.\n * For users that need custom routing in CDN bundles, they have to continue using `new BrowserTracing()` until v8.\n */\nexport function bundleBrowserTracingIntegration(\n options: Parameters[0] = {},\n): Integration {\n // Migrate some options from the old integration to the new one\n // eslint-disable-next-line deprecation/deprecation\n const opts: ConstructorParameters[0] = options;\n\n if (typeof options.markBackgroundSpan === 'boolean') {\n opts.markBackgroundTransactions = options.markBackgroundSpan;\n }\n\n if (typeof options.instrumentPageLoad === 'boolean') {\n opts.startTransactionOnPageLoad = options.instrumentPageLoad;\n }\n\n if (typeof options.instrumentNavigation === 'boolean') {\n opts.startTransactionOnLocationChange = options.instrumentNavigation;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return new BrowserTracing(opts);\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'TryCatch';\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\nconst _browserApiErrorsIntegration = ((options: Partial = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n * @deprecated Use `browserApiErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const TryCatch = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n browserApiErrorsIntegration,\n) as IntegrationClass & {\n new (options?: {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n }): Integration;\n};\n\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: VoidFunction,): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n","import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import { getClient } from '@sentry/core';\nimport type {\n Event,\n EventHint,\n Exception,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isParameterizedString,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const client = getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n message: ParameterizedString,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception: Record,\n { isUnhandledRejection }: { isUnhandledRejection?: boolean },\n): string {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n try {\n const prototype: Prototype | null = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { captureEvent, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Primitive,\n StackParser,\n} from '@sentry/types';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record;\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options: Partial = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\n/**\n * Global handlers.\n * @deprecated Use `globalHandlersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const GlobalHandlers = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n globalHandlersIntegration,\n) as IntegrationClass void }> & {\n new (options?: Partial): Integration;\n};\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e as unknown);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = error as any;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n return e.reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n return e.detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable max-lines */\nimport { addBreadcrumb, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event as SentryEvent,\n HandlerDataConsole,\n HandlerDataDom,\n HandlerDataFetch,\n HandlerDataHistory,\n HandlerDataXhr,\n Integration,\n IntegrationClass,\n IntegrationFn,\n} from '@sentry/types';\nimport type {\n Breadcrumb,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n SENTRY_XHR_DATA_KEY,\n addClickKeypressInstrumentationHandler,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n getComponentName,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options: Partial = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry && client.on) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Default Breadcrumbs instrumentations\n *\n * @deprecated Use `breadcrumbsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Breadcrumbs = convertIntegrationFnToClass(INTEGRATION_NAME, breadcrumbsIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (\n options?: Partial<{\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n }>,\n ): Integration;\n};\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client: Client): (handlerData: HandlerDataConsole) => void {\n return function _consoleBreadcrumb(handlerData: HandlerDataConsole): void {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record).target;\n}\n","import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Aggregrate linked errors in an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n","import type { MeasurementUnit, Span } from '@sentry/types';\nimport type { MetricSummary } from '@sentry/types';\nimport type { Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { getActiveSpan } from '../tracing';\nimport type { MetricType } from './types';\n\n/**\n * key: bucketKey\n * value: [exportKey, MetricSummary]\n */\ntype MetricSummaryStorage = Map;\n\nlet SPAN_METRIC_SUMMARY: WeakMap | undefined;\n\nfunction getMetricStorageForSpan(span: Span): MetricSummaryStorage | undefined {\n return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined;\n}\n\n/**\n * Fetches the metric summary if it exists for the passed span\n */\nexport function getMetricSummaryJsonForSpan(span: Span): Record> | undefined {\n const storage = getMetricStorageForSpan(span);\n\n if (!storage) {\n return undefined;\n }\n const output: Record> = {};\n\n for (const [, [exportKey, summary]] of storage) {\n if (!output[exportKey]) {\n output[exportKey] = [];\n }\n\n output[exportKey].push(dropUndefinedKeys(summary));\n }\n\n return output;\n}\n\n/**\n * Updates the metric summary on the currently active span\n */\nexport function updateMetricSummaryOnActiveSpan(\n metricType: MetricType,\n sanitizedName: string,\n value: number,\n unit: MeasurementUnit,\n tags: Record,\n bucketKey: string,\n): void {\n const span = getActiveSpan();\n if (span) {\n const storage = getMetricStorageForSpan(span) || new Map();\n\n const exportKey = `${metricType}:${sanitizedName}@${unit}`;\n const bucketItem = storage.get(bucketKey);\n\n if (bucketItem) {\n const [, summary] = bucketItem;\n storage.set(bucketKey, [\n exportKey,\n {\n min: Math.min(summary.min, value),\n max: Math.max(summary.max, value),\n count: (summary.count += 1),\n sum: (summary.sum += value),\n tags: summary.tags,\n },\n ]);\n } else {\n storage.set(bucketKey, [\n exportKey,\n {\n min: value,\n max: value,\n count: 1,\n sum: value,\n tags,\n },\n ]);\n }\n\n if (!SPAN_METRIC_SUMMARY) {\n SPAN_METRIC_SUMMARY = new WeakMap();\n }\n\n SPAN_METRIC_SUMMARY.set(span, storage);\n }\n}\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'HttpContext';\n\nconst _httpContextIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const httpContextIntegration = defineIntegration(_httpContextIntegration);\n\n/**\n * HttpContext integration collects information about HTTP request headers.\n * @deprecated Use `httpContextIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const HttpContext = convertIntegrationFnToClass(INTEGRATION_NAME, httpContextIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event) => void }\n>;\n","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);\n }\n}\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/**\n * The id of the profile that this span occured in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id';\n","import type { Span } from '@sentry/types';\n\n/** The status of an Span.\n *\n * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type\n */\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function getSpanStatusFromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @deprecated Use {@link spanStatusFromHttpCode} instead.\n * This export will be removed in v8 as the signature contains a typo.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport const spanStatusfromHttpCode = getSpanStatusFromHttpCode;\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nexport function setHttpStatus(span: Span, httpStatus: number): void {\n // TODO (v8): Remove these calls\n // Relay does not require us to send the status code as a tag\n // For now, just because users might expect it to land as a tag we keep sending it.\n // Same with data.\n // In v8, we replace both, simply with\n // span.setAttribute('http.response.status_code', httpStatus);\n\n // eslint-disable-next-line deprecation/deprecation\n span.setTag('http.status_code', String(httpStatus));\n // eslint-disable-next-line deprecation/deprecation\n span.setData('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n","/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Measurements,\n Primitive,\n Span as SpanInterface,\n SpanAttributeValue,\n SpanAttributes,\n SpanContext,\n SpanContextData,\n SpanJSON,\n SpanOrigin,\n SpanTimeInput,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport {\n SEMANTIC_ATTRIBUTE_PROFILE_ID,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n} from '../semanticAttributes';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport {\n TRACE_FLAG_NONE,\n TRACE_FLAG_SAMPLED,\n spanTimeInputToSeconds,\n spanToJSON,\n spanToTraceContext,\n spanToTraceHeader,\n} from '../utils/spanUtils';\nimport type { SpanStatusType } from './spanstatus';\nimport { setHttpStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n this.spans = [];\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n // eslint-disable-next-line deprecation/deprecation\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * Tags for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public tags: { [key: string]: Primitive };\n\n /**\n * Data for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any };\n\n /**\n * List of spans that were finalized\n *\n * @deprecated This property will no longer be public. Span recording will be handled internally.\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n * @deprecated Use top level `Sentry.getRootSpan()` instead\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n *\n * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class.\n * the instrumenter can only be sentry or otel so we can check the span instance\n * to verify which one it is and remove this field entirely.\n *\n * @deprecated This field will be removed.\n */\n public instrumenter: Instrumenter;\n\n protected _traceId: string;\n protected _spanId: string;\n protected _parentSpanId?: string | undefined;\n protected _sampled: boolean | undefined;\n protected _name?: string | undefined;\n protected _attributes: SpanAttributes;\n /** Epoch timestamp in seconds when the span started. */\n protected _startTime: number;\n /** Epoch timestamp in seconds when the span ended. */\n protected _endTime?: number | undefined;\n /** Internal keeper of the status */\n protected _status?: SpanStatusType | string | undefined;\n protected _exclusiveTime?: number;\n\n protected _measurements: Measurements;\n\n private _logMessage?: string;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext: SpanContext = {}) {\n this._traceId = spanContext.traceId || uuid4();\n this._spanId = spanContext.spanId || uuid4().substring(16);\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags ? { ...spanContext.tags } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data ? { ...spanContext.data } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.instrumenter = spanContext.instrumenter || 'sentry';\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n\n if (spanContext.parentSpanId) {\n this._parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this._sampled = spanContext.sampled;\n }\n if (spanContext.status) {\n this._status = spanContext.status;\n }\n if (spanContext.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n if (spanContext.exclusiveTime !== undefined) {\n this._exclusiveTime = spanContext.exclusiveTime;\n }\n this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {};\n }\n\n // This rule conflicts with another eslint rule :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * An alias for `description` of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name || '';\n }\n\n /**\n * Update the name of the span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set name(name: string) {\n this.updateName(name);\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get description(): string | undefined {\n return this._name;\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set description(description: string | undefined) {\n this._name = description;\n }\n\n /**\n * The ID of the trace.\n * @deprecated Use `spanContext().traceId` instead.\n */\n public get traceId(): string {\n return this._traceId;\n }\n\n /**\n * The ID of the trace.\n * @deprecated You cannot update the traceId of a span after span creation.\n */\n public set traceId(traceId: string) {\n this._traceId = traceId;\n }\n\n /**\n * The ID of the span.\n * @deprecated Use `spanContext().spanId` instead.\n */\n public get spanId(): string {\n return this._spanId;\n }\n\n /**\n * The ID of the span.\n * @deprecated You cannot update the spanId of a span after span creation.\n */\n public set spanId(spanId: string) {\n this._spanId = spanId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `startSpan` functions instead.\n */\n public set parentSpanId(string) {\n this._parentSpanId = string;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).parent_span_id` instead.\n */\n public get parentSpanId(): string | undefined {\n return this._parentSpanId;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated Use `isRecording()` instead.\n */\n public get sampled(): boolean | undefined {\n return this._sampled;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated You cannot update the sampling decision of a span after span creation.\n */\n public set sampled(sampled: boolean | undefined) {\n this._sampled = sampled;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public get attributes(): SpanAttributes {\n return this._attributes;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `setAttributes()` instead.\n */\n public set attributes(attributes: SpanAttributes) {\n this._attributes = attributes;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get startTimestamp(): number {\n return this._startTime;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated In v8, you will not be able to update the span start time after creation.\n */\n public set startTimestamp(startTime: number) {\n this._startTime = startTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get endTimestamp(): number | undefined {\n return this._endTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Set the end time via `span.end()` instead.\n */\n public set endTimestamp(endTime: number | undefined) {\n this._endTime = endTime;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `spanToJSON().status` instead to get the status.\n */\n public get status(): SpanStatusType | string | undefined {\n return this._status;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `.setStatus()` instead to set or update the status.\n */\n public set status(status: SpanStatusType | string | undefined) {\n this._status = status;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `spanToJSON().op` to read the op instead.\n */\n public get op(): string | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op')\n * to update the span instead.\n */\n public set op(op: string | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op);\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `spanToJSON().origin` to read the origin instead.\n */\n public get origin(): SpanOrigin | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined;\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `startSpan()` functions to set the origin instead.\n */\n public set origin(origin: SpanOrigin | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /** @inheritdoc */\n public spanContext(): SpanContextData {\n const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n return {\n spanId,\n traceId,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n };\n }\n\n /**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * Also the `sampled` decision will be inherited.\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startChild(\n spanContext?: Pick>,\n ): SpanInterface {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this._spanId,\n sampled: this._sampled,\n traceId: this._traceId,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder = this.spanRecorder;\n // eslint-disable-next-line deprecation/deprecation\n if (childSpan.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder.add(childSpan);\n }\n\n const rootSpan = getRootSpan(this);\n // TODO: still set span.transaction here until we have a more permanent solution\n // Probably similarly to the weakmap we hold in node-experimental\n // eslint-disable-next-line deprecation/deprecation\n childSpan.transaction = rootSpan as Transaction;\n\n if (DEBUG_BUILD && rootSpan) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = spanToJSON(childSpan).description || '< unknown name >';\n const idStr = rootSpan.spanContext().spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n logger.log(logMessage);\n this._logMessage = logMessage;\n }\n\n return childSpan;\n }\n\n /**\n * Sets the tag attribute on the current span.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key Tag key\n * @param value Tag value\n * @deprecated Use `setAttribute()` instead.\n */\n public setTag(key: string, value: Primitive): this {\n // eslint-disable-next-line deprecation/deprecation\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * Sets the data attribute on the current span\n * @param key Data key\n * @param value Data value\n * @deprecated Use `setAttribute()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setData(key: string, value: any): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /** @inheritdoc */\n public setAttribute(key: string, value: SpanAttributeValue | undefined): void {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n } else {\n this._attributes[key] = value;\n }\n }\n\n /** @inheritdoc */\n public setAttributes(attributes: SpanAttributes): void {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top-level `setHttpStatus()` instead.\n */\n public setHttpStatus(httpStatus: number): this {\n setHttpStatus(this, httpStatus);\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @deprecated Use `.updateName()` instead.\n */\n public setName(name: string): void {\n this.updateName(name);\n }\n\n /**\n * @inheritDoc\n */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).status === 'ok'` instead.\n */\n public isSuccess(): boolean {\n return this._status === 'ok';\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `.end()` instead.\n */\n public finish(endTimestamp?: number): void {\n return this.end(endTimestamp);\n }\n\n /** @inheritdoc */\n public end(endTimestamp?: SpanTimeInput): void {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n const rootSpan = getRootSpan(this);\n if (\n DEBUG_BUILD &&\n // Don't call this for transactions\n rootSpan &&\n rootSpan.spanContext().spanId !== this._spanId\n ) {\n const logMessage = this._logMessage;\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public toTraceparent(): string {\n return spanToTraceHeader(this);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON()` or access the fields directly instead.\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n endTimestamp: this._endTime,\n // eslint-disable-next-line deprecation/deprecation\n op: this.op,\n parentSpanId: this._parentSpanId,\n sampled: this._sampled,\n spanId: this._spanId,\n startTimestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n traceId: this._traceId,\n });\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Update the fields directly instead.\n */\n public updateWithContext(spanContext: SpanContext): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data || {};\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n this._endTime = spanContext.endTimestamp;\n // eslint-disable-next-line deprecation/deprecation\n this.op = spanContext.op;\n this._parentSpanId = spanContext.parentSpanId;\n this._sampled = spanContext.sampled;\n this._spanId = spanContext.spanId || this._spanId;\n this._startTime = spanContext.startTimestamp || this._startTime;\n this._status = spanContext.status;\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags || {};\n this._traceId = spanContext.traceId || this._traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceContext()` util function instead.\n */\n public getTraceContext(): TraceContext {\n return spanToTraceContext(this);\n }\n\n /**\n * Get JSON representation of this span.\n *\n * @hidden\n * @internal This method is purely for internal purposes and should not be used outside\n * of SDK code. If you need to get a JSON representation of a span,\n * use `spanToJSON(span)` instead.\n */\n public getSpanJSON(): SpanJSON {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined,\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n exclusive_time: this._exclusiveTime,\n measurements: Object.keys(this._measurements).length > 0 ? this._measurements : undefined,\n });\n }\n\n /** @inheritdoc */\n public isRecording(): boolean {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * Convert the object to JSON.\n * @deprecated Use `spanToJSON(span)` instead.\n */\n public toJSON(): SpanJSON {\n return this.getSpanJSON();\n }\n\n /**\n * Get the merged data for this span.\n * For now, this combines `data` and `attributes` together,\n * until eventually we can ingest `attributes` directly.\n */\n private _getData():\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n }\n | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const { data, _attributes: attributes } = this;\n\n const hasData = Object.keys(data).length > 0;\n const hasAttributes = Object.keys(attributes).length > 0;\n\n if (!hasData && !hasAttributes) {\n return undefined;\n }\n\n if (hasData && hasAttributes) {\n return {\n ...data,\n ...attributes,\n };\n }\n\n return hasData ? data : attributes;\n }\n}\n","import type { Options } from '@sentry/types';\n\nimport { getClient } from '../exports';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n","import type { Scope, Span, SpanTimeInput, StartSpanOptions, TransactionContext } from '@sentry/types';\n\nimport { addNonEnumerableProperty, dropUndefinedKeys, logger, tracingContextFromHeaders } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '.';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getCurrentScope, withScope } from '../exports';\nimport type { Hub } from '../hub';\nimport { runWithAsyncContext } from '../hub';\nimport { getIsolationScope } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport type { Scope as ScopeClass } from '../scope';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n *\n * This function is meant to be used internally and may break at any time. Use at your own risk.\n *\n * @internal\n * @private\n *\n * @deprecated Use `startSpan` instead.\n */\nexport function trace(\n context: TransactionContext,\n callback: (span?: Span) => T,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onError: (error: unknown, span?: Span) => void = () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n afterFinish: () => void = () => {},\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const scope = getCurrentScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const spanContext = normalizeContext(context);\n const activeSpan = createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: false,\n scope,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n error => {\n activeSpan && activeSpan.setStatus('internal_error');\n onError(error, activeSpan);\n },\n () => {\n activeSpan && activeSpan.end();\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(parentSpan);\n afterFinish();\n },\n );\n}\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpan(context: StartSpanOptions, callback: (span: Span | undefined) => T): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet\n if (activeSpan) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n () => activeSpan && activeSpan.end(),\n );\n });\n });\n}\n\n/**\n * @deprecated Use {@link startSpan} instead.\n */\nexport const startActiveSpan = startSpan;\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. You'll have to call `span.end()` manually.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpanManual(\n context: StartSpanOptions,\n callback: (span: Span | undefined, finish: () => void) => T,\n): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n function finishAndSetSpan(): void {\n activeSpan && activeSpan.end();\n }\n\n return handleCallbackErrors(\n () => callback(activeSpan, finishAndSetSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n if (activeSpan && activeSpan.isRecording()) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startInactiveSpan(context: StartSpanOptions): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const spanContext = normalizeContext(context);\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const parentSpan = context.scope\n ? // eslint-disable-next-line deprecation/deprecation\n context.scope.getSpan()\n : getActiveSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return undefined;\n }\n\n const scope = context.scope || getCurrentScope();\n\n // Even though we don't actually want to make this span active on the current scope,\n // we need to make it active on a temporary scope that we use for event processing\n // as otherwise, it won't pick the correct span for the event when processing it\n const temporaryScope = (scope as ScopeClass).clone();\n\n return createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope: temporaryScope,\n });\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentScope().getSpan();\n}\n\ninterface ContinueTrace {\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers,\n * or in the browser from `` and `` HTML tags.\n *\n * @deprecated Use the version of this function taking a callback as second parameter instead:\n *\n * ```\n * Sentry.continueTrace(sentryTrace: '...', baggage: '...' }, () => {\n * // ...\n * })\n * ```\n *\n */\n ({\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n }): Partial;\n\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from ``\n * and `` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n *\n * Deprecation notice: In the next major version of the SDK the provided callback will not receive a transaction\n * context argument.\n */\n (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n // TODO(v8): Remove parameter from this callback.\n callback: (transactionContext: Partial) => V,\n ): V;\n}\n\nexport const continueTrace: ContinueTrace = (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n callback?: (transactionContext: Partial) => V,\n): V | Partial => {\n // TODO(v8): Change this function so it doesn't do anything besides setting the propagation context on the current scope:\n /*\n return withScope((scope) => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n return callback();\n })\n */\n\n const currentScope = getCurrentScope();\n\n // eslint-disable-next-line deprecation/deprecation\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n currentScope.setPropagationContext(propagationContext);\n\n if (DEBUG_BUILD && traceparentData) {\n logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`);\n }\n\n const transactionContext: Partial = {\n ...traceparentData,\n metadata: dropUndefinedKeys({\n dynamicSamplingContext,\n }),\n };\n\n if (!callback) {\n return transactionContext;\n }\n\n return runWithAsyncContext(() => {\n return callback(transactionContext);\n });\n};\n\nfunction createChildSpanOrTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n {\n parentSpan,\n spanContext,\n forceTransaction,\n scope,\n }: {\n parentSpan: Span | undefined;\n spanContext: TransactionContext;\n forceTransaction?: boolean;\n scope: Scope;\n },\n): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const isolationScope = getIsolationScope();\n\n let span: Span | undefined;\n if (parentSpan && !forceTransaction) {\n // eslint-disable-next-line deprecation/deprecation\n span = parentSpan.startChild(spanContext);\n } else if (parentSpan) {\n // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n const sampled = spanIsSampled(parentSpan);\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n } else {\n const { traceId, dsc, parentSpanId, sampled } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n }\n\n // We always set this as active span on the scope\n // In the case of this being an inactive span, we ensure to pass a detached scope in here in the first place\n // But by having this here, we can ensure that the lookup through `getCapturedScopesOnSpan` results in the correct scope & span combo\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to TransactionContext.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n *\n * Eventually the StartSpanOptions will be more aligned with OpenTelemetry.\n */\nfunction normalizeContext(context: StartSpanOptions): TransactionContext {\n if (context.startTime) {\n const ctx: TransactionContext & { startTime?: SpanTimeInput } = { ...context };\n ctx.startTimestamp = spanTimeInputToSeconds(context.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return context;\n}\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\ntype SpanWithScopes = Span & {\n [SCOPE_ON_START_SPAN_FIELD]?: Scope;\n [ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: Scope;\n};\n\nfunction setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n */\nexport function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {\n return {\n scope: (span as SpanWithScopes)[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: (span as SpanWithScopes)[ISOLATION_SCOPE_ON_START_SPAN_FIELD],\n };\n}\n","import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n MeasurementUnit,\n SpanTimeInput,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionEvent,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes';\nimport { spanTimeInputToSeconds, spanToJSON, spanToTraceContext } from '../utils/spanUtils';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { Span as SpanClass, SpanRecorder } from './span';\nimport { getCapturedScopesOnSpan } from './trace';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n /**\n * The reference to the current hub.\n */\n // eslint-disable-next-line deprecation/deprecation\n public _hub: Hub;\n\n protected _name: string;\n\n private _contexts: Contexts;\n\n private _trimEnd?: boolean | undefined;\n\n // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility.\n private _frozenDynamicSamplingContext: Readonly> | undefined;\n\n private _metadata: Partial;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n *\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n // eslint-disable-next-line deprecation/deprecation\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n this._contexts = {};\n\n // eslint-disable-next-line deprecation/deprecation\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this._metadata = {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.metadata,\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n // TODO (v8): Replace this with another way to set the root span\n // eslint-disable-next-line deprecation/deprecation\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n // This sadly conflicts with the getter/setter ordering :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * Getter for `name` property.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name;\n }\n\n /**\n * Setter for `name` property, which also sets `source` as custom.\n * @deprecated Use `updateName()` and `setMetadata()` instead.\n */\n public set name(newName: string) {\n // eslint-disable-next-line deprecation/deprecation\n this.setName(newName);\n }\n\n /**\n * Get the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public get metadata(): TransactionMetadata {\n // We merge attributes in for backwards compatibility\n return {\n // Defaults\n // eslint-disable-next-line deprecation/deprecation\n source: 'custom',\n spanMetadata: {},\n\n // Legacy metadata\n ...this._metadata,\n\n // From attributes\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && {\n source: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] as TransactionMetadata['source'],\n }),\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && {\n sampleRate: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] as TransactionMetadata['sampleRate'],\n }),\n };\n }\n\n /**\n * Update the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public set metadata(metadata: TransactionMetadata) {\n this._metadata = metadata;\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /**\n * Setter for `name` property, which also sets `source` on the metadata.\n *\n * @deprecated Use `.updateName()` and `.setAttribute()` instead.\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n\n /** @inheritdoc */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Set the context of a transaction event.\n * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction.\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top-level `setMeasurement()` instead.\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * Store metadata on this transaction.\n * @deprecated Use attributes or store data on the scope instead.\n */\n public setMetadata(newMetadata: Partial): void {\n this._metadata = { ...this._metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const timestampInS = spanTimeInputToSeconds(endTimestamp);\n const transaction = this._finishTransaction(timestampInS);\n if (!transaction) {\n return undefined;\n }\n // eslint-disable-next-line deprecation/deprecation\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n // eslint-disable-next-line deprecation/deprecation\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this._name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n // eslint-disable-next-line deprecation/deprecation\n super.updateWithContext(transactionContext);\n\n this._name = transactionContext.name || '';\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n *\n * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead.\n */\n public getDynamicSamplingContext(): Readonly> {\n return getDynamicSamplingContextFromSpan(this);\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n // eslint-disable-next-line deprecation/deprecation\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n\n /**\n * Get the profile id of the transaction.\n */\n public getProfileId(): string | undefined {\n if (this._contexts !== undefined && this._contexts['profile'] !== undefined) {\n return this._contexts['profile'].profile_id as string;\n }\n return undefined;\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n protected _finishTransaction(endTimestamp?: number): TransactionEvent | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this._endTime !== undefined) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && logger.warn('Transaction has no name, falling back to ``.');\n this._name = '';\n }\n\n // just sets the end timestamp\n super.end(endTimestamp);\n\n // eslint-disable-next-line deprecation/deprecation\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this._sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n DEBUG_BUILD && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const finishedSpans = this.spanRecorder\n ? // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans.filter(span => span !== this && spanToJSON(span).timestamp)\n : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n const endTimes = finishedSpans.map(span => spanToJSON(span).timestamp).filter(Boolean) as number[];\n this._endTime = endTimes.reduce((prev, current) => {\n return prev > current ? prev : current;\n });\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n // eslint-disable-next-line deprecation/deprecation\n const { metadata } = this;\n // eslint-disable-next-line deprecation/deprecation\n const { source } = metadata;\n\n const transaction: TransactionEvent = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: spanToTraceContext(this),\n },\n // TODO: Pass spans serialized via `spanToJSON()` here instead in v8.\n spans: finishedSpans,\n start_timestamp: this._startTime,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n capturedSpanScope,\n capturedSpanIsolationScope,\n ...dropUndefinedKeys({\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n }),\n },\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n DEBUG_BUILD && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`);\n\n return transaction;\n }\n}\n","/* eslint-disable max-lines */\nimport type { SpanTimeInput, TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanContext().spanId !== this.transactionSpanId) {\n // We patch span.end() to pop an activity after setting an endTimestamp.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalEnd = span.end;\n span.end = (...rest: unknown[]) => {\n this._popActivity(span.spanContext().spanId);\n return originalEnd.apply(span, rest);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (spanToJSON(span).timestamp === undefined) {\n this._pushActivity(span.spanContext().spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record;\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number];\n\n private _autoFinishAllowed: boolean;\n\n /**\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n public constructor(\n transactionContext: TransactionContext,\n // eslint-disable-next-line deprecation/deprecation\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n /**\n * When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval`\n * option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option)\n * will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is\n * reached, no matter what this option is configured to.\n *\n * Defaults to `false`.\n */\n delayAutoFinishUntilSignal: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n this.activities = {};\n this._heartbeatCounter = 0;\n this._finished = false;\n this._idleTimeoutCanceledPermanently = false;\n this._beforeFinishCallbacks = [];\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];\n this._autoFinishAllowed = !delayAutoFinishUntilSignal;\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n DEBUG_BUILD && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`);\n // eslint-disable-next-line deprecation/deprecation\n _idleHub.getScope().setSpan(this);\n }\n\n if (!delayAutoFinishUntilSignal) {\n this._restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.end();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const endTimestampInS = spanTimeInputToSeconds(endTimestamp);\n\n this._finished = true;\n this.activities = {};\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.op === 'ui.action.click') {\n this.setAttribute(FINISH_REASON_TAG, this._finishReason);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.spanRecorder) {\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestampInS);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanContext().spanId === this.spanContext().spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!spanToJSON(span).timestamp) {\n span.setStatus('cancelled');\n span.end(endTimestampInS);\n DEBUG_BUILD &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const { start_timestamp: startTime, timestamp: endTime } = spanToJSON(span);\n const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(span, undefined, 2);\n if (!spanStartedBeforeTransactionFinish) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);\n }\n }\n\n return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;\n });\n\n DEBUG_BUILD && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n DEBUG_BUILD && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this._idleHub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n if (scope.getTransaction() === this) {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(undefined);\n }\n }\n\n return super.end(endTimestamp);\n }\n\n /**\n * Register a callback function that gets executed before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n DEBUG_BUILD && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.\n */\n public sendAutoFinishSignal(): void {\n if (!this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Received finish signal for idle transaction.');\n this._restartIdleTimeout();\n this._autoFinishAllowed = true;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.end(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n DEBUG_BUILD && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n DEBUG_BUILD && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n if (this._autoFinishAllowed) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n if (this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.end();\n }\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n DEBUG_BUILD && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n","import type { Transaction } from '@sentry/types';\nimport { extractTraceparentData as _extractTraceparentData } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * Grabs active transaction off scope.\n *\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveTransaction(maybeHub?: Hub): T | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = maybeHub || getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const scope = hub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n *\n * @deprecated Import this function from `@sentry/utils` instead\n */\nexport const extractTraceparentData = _extractTraceparentData;\n","import {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n logger,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SpanStatusType } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n DEBUG_BUILD && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n","import type { Options, SamplingContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '../semanticAttributes';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanToJSON } from '../utils/spanUtils';\nimport type { Transaction } from './transaction';\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * This method muttes the given `transaction` and will set the `sampled` value on it.\n * It returns the same transaction, for convenience.\n */\nexport function sampleTransaction(\n transaction: T,\n options: Pick,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.sampled !== undefined) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled));\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n // eslint-disable-next-line deprecation/deprecation\n if (!transaction.sampled) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanToJSON(transaction).description}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nexport function isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n","import type { ClientOptions, CustomSamplingContext, TransactionContext } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { spanToTraceHeader } from '../utils/spanUtils';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { sampleTransaction } from './sampling';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\n// eslint-disable-next-line deprecation/deprecation\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': spanToTraceHeader(span),\n }\n : {};\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n // eslint-disable-next-line deprecation/deprecation\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n DEBUG_BUILD &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n // eslint-disable-next-line deprecation/deprecation\n transactionContext.sampled = false;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new Transaction(transactionContext, this);\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n delayAutoFinishUntilSignal: boolean = false,\n): IdleTransaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new IdleTransaction(\n transactionContext,\n hub,\n idleTimeout,\n finalTimeout,\n heartbeatInterval,\n onScope,\n delayAutoFinishUntilSignal,\n );\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric } from '../../types';\nimport { observe } from '../observe';\n\ndeclare global {\n interface Performance {\n interactionCount: number;\n }\n}\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries: Metric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(e => {\n if (e.interactionId) {\n minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId);\n maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId);\n\n interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;\n }\n });\n};\n\nlet po: PerformanceObserver | undefined;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nexport const getInteractionCount = (): number => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nexport const initInteractionCountPolyfill = (): void => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } as PerformanceObserverInit);\n};\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ &\n // document is not available in all browser environments (webworkers). We make it optional so you have to explicitly check for it\n Omit &\n Partial>;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if ((WINDOW.document && WINDOW.document.prerendering) || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document!.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (\n onReport: ReportCallback,\n options: { reportAllChanges?: boolean } = {},\n): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, options.reportAllChanges);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): void => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n if (WINDOW.document && WINDOW.document.visibilityState) {\n firstHiddenTime = WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n }\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { getInteractionCount, initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { INPMetric } from './types/inp';\n\ninterface Interaction {\n id: number;\n latency: number;\n entries: PerformanceEventTiming[];\n}\n\n/**\n * Returns the interaction count since the last bfcache restore (or for the\n * full page lifecycle if there were no bfcache restores).\n */\nconst getInteractionCountForNavigation = (): number => {\n return getInteractionCount();\n};\n\n// To prevent unnecessary memory usage on pages with lots of interactions,\n// store at most 10 of the longest interactions to consider as INP candidates.\nconst MAX_INTERACTIONS_TO_CONSIDER = 10;\n\n// A list of longest interactions on the page (by latency) sorted so the\n// longest one is first. The list is as most MAX_INTERACTIONS_TO_CONSIDER long.\nconst longestInteractionList: Interaction[] = [];\n\n// A mapping of longest interactions by their interaction ID.\n// This is used for faster lookup.\nconst longestInteractionMap: { [interactionId: string]: Interaction } = {};\n\n/**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\nconst processEntry = (entry: PerformanceEventTiming): void => {\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const existingInteraction = longestInteractionMap[entry.interactionId!];\n\n // Only process the entry if it's possibly one of the ten longest,\n // or if it's part of an existing interaction.\n if (\n existingInteraction ||\n longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n entry.duration > minLongestInteraction.latency\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (existingInteraction) {\n existingInteraction.entries.push(entry);\n existingInteraction.latency = Math.max(existingInteraction.latency, entry.duration);\n } else {\n const interaction = {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n id: entry.interactionId!,\n latency: entry.duration,\n entries: [entry],\n };\n longestInteractionMap[interaction.id] = interaction;\n longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n longestInteractionList.sort((a, b) => b.latency - a.latency);\n longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete longestInteractionMap[i.id];\n });\n }\n};\n\n/**\n * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\nconst estimateP98LongestInteraction = (): Interaction => {\n const candidateInteractionIndex = Math.min(\n longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return longestInteractionList[candidateInteractionIndex];\n};\n\n/**\n * Calculates the [INP](https://web.dev/responsiveness/) value for the current\n * page and calls the `callback` function once the value is ready, along with\n * the `event` performance entries reported for that interaction. The reported\n * value is a `DOMHighResTimeStamp`.\n *\n * A custom `durationThreshold` configuration option can optionally be passed to\n * control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 are\n * reported as 0. Note that this will not affect your 75th percentile INP value\n * unless that value is also less than 40 (well below the recommended\n * [good](https://web.dev/inp/#what-is-a-good-inp-score) threshold).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** INP should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onINP = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/inp/#what's-a-%22good%22-inp-value\n // const thresholds = [200, 500];\n\n // TODO(philipwalton): remove once the polyfill is no longer needed.\n initInteractionCountPolyfill();\n\n const metric = initMetric('INP');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntries = (entries: INPMetric['entries']): void => {\n entries.forEach(entry => {\n if (entry.interactionId) {\n processEntry(entry);\n }\n\n // Entries of type `first-input` don't currently have an `interactionId`,\n // so to consider them in INP we have to first check that an existing\n // entry doesn't match the `duration` and `startTime`.\n // Note that this logic assumes that `event` entries are dispatched\n // before `first-input` entries. This is true in Chrome but it is not\n // true in Firefox; however, Firefox doesn't support interactionId, so\n // it's not an issue at the moment.\n // TODO(philipwalton): remove once crbug.com/1325826 is fixed.\n if (entry.entryType === 'first-input') {\n const noMatchingEntry = !longestInteractionList.some(interaction => {\n return interaction.entries.some(prevEntry => {\n return entry.duration === prevEntry.duration && entry.startTime === prevEntry.startTime;\n });\n });\n if (noMatchingEntry) {\n processEntry(entry);\n }\n }\n });\n\n const inp = estimateP98LongestInteraction();\n\n if (inp && inp.latency !== metric.value) {\n metric.value = inp.latency;\n metric.entries = inp.entries;\n report();\n }\n };\n\n const po = observe('event', handleEntries, {\n // Event Timing entries have their durations rounded to the nearest 8ms,\n // so a duration of 40ms would be any event that spans 2.5 or more frames\n // at 60Hz. This threshold is chosen to strike a balance between usefulness\n // and performance. Running this callback for any interaction that spans\n // just one or two frames is likely not worth the insight that could be\n // gained.\n durationThreshold: opts.durationThreshold || 40,\n } as PerformanceObserverInit);\n\n report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n if (po) {\n // Also observe entries of type `first-input`. This is useful in cases\n // where the first interaction is less than the `durationThreshold`.\n po.observe({ type: 'first-input', buffered: true });\n\n onHidden(() => {\n handleEntries(po.takeRecords() as INPMetric['entries']);\n\n // If the interaction count shows that there were interactions but\n // none were captured by the PerformanceObserver, report a latency of 0.\n if (metric.value < 0 && getInteractionCountForNavigation() > 0) {\n metric.value = 0;\n metric.entries = [];\n }\n\n report(true);\n });\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, stopListening, { once: true, capture: true });\n }\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getNavigationEntry } from './lib/getNavigationEntry';\nimport { initMetric } from './lib/initMetric';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { TTFBMetric } from './types/ttfb';\n\n/**\n * Runs in the next task after the page is done loading and/or prerendering.\n * @param callback\n */\nconst whenReady = (callback: () => void): void => {\n if (!WINDOW.document) {\n return;\n }\n\n if (WINDOW.document.prerendering) {\n addEventListener('prerenderingchange', () => whenReady(callback), true);\n } else if (WINDOW.document.readyState !== 'complete') {\n addEventListener('load', () => whenReady(callback), true);\n } else {\n // Queue a task so the callback runs after `loadEventEnd`.\n setTimeout(callback, 0);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/time-to-first-byte/) value for the\n * current page and calls the `callback` function once the page has loaded,\n * along with the relevant `navigation` performance entry used to determine the\n * value. The reported value is a `DOMHighResTimeStamp`.\n *\n * Note, this function waits until after the page is loaded to call `callback`\n * in order to ensure all properties of the `navigation` entry are populated.\n * This is useful if you want to report on other metrics exposed by the\n * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For\n * example, the TTFB metric starts from the page's [time\n * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it\n * includes time spent on DNS lookup, connection negotiation, network latency,\n * and server processing time.\n */\nexport const onTTFB = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/ttfb/#what-is-a-good-ttfb-score\n // const thresholds = [800, 1800];\n\n const metric = initMetric('TTFB');\n const report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n whenReady(() => {\n const navEntry = getNavigationEntry() as TTFBMetric['entries'][number];\n\n if (navEntry) {\n // The activationStart reference is used because TTFB should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the first byte is received, this time should be clamped at 0.\n metric.value = Math.max(navEntry.responseStart - getActivationStart(), 0);\n\n // In some cases the value reported is negative or is larger\n // than the current page time. Ignore these cases:\n // https://github.com/GoogleChrome/web-vitals/issues/137\n // https://github.com/GoogleChrome/web-vitals/issues/162\n if (metric.value < 0 || metric.value > performance.now()) return;\n\n metric.entries = [navEntry];\n\n report(true);\n }\n });\n};\n","import { getFunctionName, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { onCLS } from './web-vitals/getCLS';\nimport { onFID } from './web-vitals/getFID';\nimport { onINP } from './web-vitals/getINP';\nimport { onLCP } from './web-vitals/getLCP';\nimport { observe } from './web-vitals/lib/observe';\nimport { onTTFB } from './web-vitals/onTTFB';\n\ntype InstrumentHandlerTypePerformanceObserver =\n | 'longtask'\n | 'event'\n | 'navigation'\n | 'paint'\n | 'resource'\n | 'first-input';\n\ntype InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid' | 'ttfb' | 'inp';\n\n// We provide this here manually instead of relying on a global, as this is not available in non-browser environements\n// And we do not want to expose such types\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): Record;\n}\ninterface PerformanceEventTiming extends PerformanceEntry {\n processingStart: number;\n processingEnd: number;\n duration: number;\n cancelable?: boolean;\n target?: unknown | null;\n interactionId?: number;\n}\n\ninterface Metric {\n /**\n * The name of the metric (in acronym form).\n */\n name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';\n\n /**\n * The current value of the metric.\n */\n value: number;\n\n /**\n * The rating as to whether the metric value is within the \"good\",\n * \"needs improvement\", or \"poor\" thresholds of the metric.\n */\n rating: 'good' | 'needs-improvement' | 'poor';\n\n /**\n * The delta between the current value and the last-reported value.\n * On the first report, `delta` and `value` will always be the same.\n */\n delta: number;\n\n /**\n * A unique ID representing this particular metric instance. This ID can\n * be used by an analytics tool to dedupe multiple values sent for the same\n * metric instance, or to group multiple deltas together and calculate a\n * total. It can also be used to differentiate multiple different metric\n * instances sent from the same page, which can happen if the page is\n * restored from the back/forward cache (in that case new metrics object\n * get created).\n */\n id: string;\n\n /**\n * Any performance entries relevant to the metric value calculation.\n * The array may also be empty if the metric value was not based on any\n * entries (e.g. a CLS value of 0 given no layout shifts).\n */\n entries: PerformanceEntry[];\n\n /**\n * The type of navigation\n *\n * Navigation Timing API (or `undefined` if the browser doesn't\n * support that API). For pages that are restored from the bfcache, this\n * value will be 'back-forward-cache'.\n */\n navigationType: 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender';\n}\n\ntype InstrumentHandlerType = InstrumentHandlerTypeMetric | InstrumentHandlerTypePerformanceObserver;\n\ntype StopListening = undefined | void | (() => void);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentHandlerCallback = (data: any) => void;\n\ntype CleanupHandlerCallback = () => void;\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\nlet _previousCls: Metric | undefined;\nlet _previousFid: Metric | undefined;\nlet _previousLcp: Metric | undefined;\nlet _previousTtfb: Metric | undefined;\nlet _previousInp: Metric | undefined;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nexport function addClsInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nexport function addLcpInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nexport function addTtfbInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addFidInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addInpInstrumentationHandler(\n callback: (data: { metric: Omit & { entries: PerformanceEventTiming[] } }) => void,\n): CleanupHandlerCallback {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\nexport function addPerformanceInstrumentationHandler(\n type: 'event' | 'first-input',\n callback: (data: { entries: ((PerformanceEntry & { target?: unknown | null }) | PerformanceEventTiming)[] }) => void,\n): CleanupHandlerCallback;\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback;\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls(): StopListening {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentFid(): void {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp(): StopListening {\n return onLCP(metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n });\n}\n\nfunction instrumentTtfb(): StopListening {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp(): void {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type: InstrumentHandlerTypeMetric,\n callback: InstrumentHandlerCallback,\n instrumentFn: () => StopListening,\n previousValue: Metric | undefined,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n let stopListening: StopListening | undefined;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type: InstrumentHandlerTypePerformanceObserver): void {\n const options: PerformanceObserverInit = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type: InstrumentHandlerType,\n callback: InstrumentHandlerCallback,\n stopListening: StopListening,\n): CleanupHandlerCallback {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import type { DsnComponents, SpanEnvelope, SpanItem } from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Create envelope from Span item.\n */\nexport function createSpanEnvelope(spans: Span[], dsn?: DsnComponents): SpanEnvelope {\n const headers: SpanEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const items = spans.map(createSpanItem);\n return createEnvelope(headers, items);\n}\n\nfunction createSpanItem(span: Span): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n return [spanHeaders, span];\n}\n","import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n *\n * Note: this will not be possible anymore in v8,\n * unless we do some special handling for browser here...\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n // eslint-disable-next-line deprecation/deprecation\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.startTimestamp = startTimestamp;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport {\n Span,\n getActiveTransaction,\n getClient,\n hasTracingEnabled,\n isValidSampleRate,\n setMeasurement,\n} from '@sentry/core';\nimport type { ClientOptions, Measurements, SpanContext, TransactionContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getComponentName, htmlTreeAsString, logger, parseUrl } from '@sentry/utils';\n\nimport { spanToJSON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport {\n addClsInstrumentationHandler,\n addFidInstrumentationHandler,\n addInpInstrumentationHandler,\n addLcpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n addTtfbInstrumentationHandler,\n} from '../instrument';\nimport { WINDOW } from '../types';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport type {\n InteractionRouteNameMapping,\n NavigatorDeviceMemory,\n NavigatorNetworkInformation,\n} from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\nimport { createSpanEnvelope } from '@sentry/core';\nimport { getNavigationEntry } from '../web-vitals/lib/getNavigationEntry';\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals.\n * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured.\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n const fidCallback = _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n const ttfbCallback = _trackTtfb();\n\n return (): void => {\n fidCallback();\n clsCallback();\n lcpCallback();\n ttfbCallback();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n });\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const span: SpanContext = {\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n };\n\n const componentName = getComponentName(entry.target);\n if (componentName) {\n span.attributes = { 'ui.component_name': componentName };\n }\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild(span);\n }\n }\n });\n}\n\n/**\n * Start tracking INP webvital events.\n */\nexport function startTrackingINP(\n interactionIdtoRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n const inpCallback = _trackINP(interactionIdtoRouteNameMapping, interactionsSampleRate);\n\n return (): void => {\n inpCallback();\n };\n }\n\n return () => undefined;\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): () => void {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n }, true);\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): () => void {\n return addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n }, true);\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): () => void {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n DEBUG_BUILD && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\nfunction _trackTtfb(): () => void {\n return addTtfbInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' };\n });\n}\n\nconst INP_ENTRY_MAP: Record = {\n click: 'click',\n pointerdown: 'click',\n pointerup: 'click',\n mousedown: 'click',\n mouseup: 'click',\n touchstart: 'click',\n touchend: 'click',\n mouseover: 'hover',\n mouseout: 'hover',\n mouseenter: 'hover',\n mouseleave: 'hover',\n pointerover: 'hover',\n pointerout: 'hover',\n pointerenter: 'hover',\n pointerleave: 'hover',\n dragstart: 'drag',\n dragend: 'drag',\n drag: 'drag',\n dragenter: 'drag',\n dragleave: 'drag',\n dragover: 'drag',\n drop: 'drag',\n keydown: 'press',\n keyup: 'press',\n keypress: 'press',\n input: 'press',\n};\n\n/** Starts tracking the Interaction to Next Paint on the current page. */\nfunction _trackINP(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n return addInpInstrumentationHandler(({ metric }) => {\n if (metric.value === undefined) {\n return;\n }\n const entry = metric.entries.find(\n entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name] !== undefined,\n );\n const client = getClient();\n if (!entry || !client) {\n return;\n }\n const interactionType = INP_ENTRY_MAP[entry.name];\n const options = client.getOptions();\n /** Build the INP span, create an envelope from the span, and then send the envelope */\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(metric.value);\n const interaction =\n entry.interactionId !== undefined ? interactionIdToRouteNameMapping[entry.interactionId] : undefined;\n if (interaction === undefined) {\n return;\n }\n const { routeName, parentContext, activeTransaction, user, replayId } = interaction;\n const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const profileId = activeTransaction !== undefined ? activeTransaction.getProfileId() : undefined;\n const span = new Span({\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n op: `ui.interaction.${interactionType}`,\n name: htmlTreeAsString(entry.target),\n attributes: {\n release: options.release,\n environment: options.environment,\n transaction: routeName,\n ...(userDisplay !== undefined && userDisplay !== '' ? { user: userDisplay } : {}),\n ...(profileId !== undefined ? { profile_id: profileId } : {}),\n ...(replayId !== undefined ? { replay_id: replayId } : {}),\n },\n exclusiveTime: metric.value,\n measurements: {\n inp: { value: metric.value, unit: 'millisecond' },\n },\n });\n\n /** Check to see if the span should be sampled */\n const sampleRate = getSampleRate(parentContext, options, interactionsSampleRate);\n\n if (!sampleRate) {\n return;\n }\n\n if (Math.random() < (sampleRate as number | boolean)) {\n const envelope = span ? createSpanEnvelope([span], client.getDsn()) : undefined;\n const transport = client && client.getTransport();\n if (transport && envelope) {\n transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending interaction:', reason);\n });\n }\n return;\n }\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n DEBUG_BUILD && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n const { op, start_timestamp: transactionStartTime } = spanToJSON(transaction);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n _addResourceSpans(transaction, entry, entry.name as string, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (op === 'pageload') {\n _addTtfbRequestTimeToMeasurements(_measurements);\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || !transactionStartTime || timeOrigin >= transactionStartTime) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transactionStartTime) * 1000);\n const delta = normalizedValue - oldValue;\n\n DEBUG_BUILD && logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n setMeasurement(measurementName, _measurements[measurementName].value, _measurements[measurementName].unit);\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n origin: 'auto.resource.browser.metrics',\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record, timeOrigin: number): void {\n if (entry.responseEnd) {\n // It is possible that we are collecting these metrics when the page hasn't finished loading yet, for example when the HTML slowly streams in.\n // In this case, ie. when the document request hasn't finished yet, `entry.responseEnd` will be 0.\n // In order not to produce faulty spans, where the end timestamp is before the start timestamp, we will only collect\n // these spans when the responseEnd value is available. The backend (Relay) would drop the entire transaction if it contained faulty spans.\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n }\n}\n\nexport interface ResourceEntry extends Record {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceUrl: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n const parsedUrl = parseUrl(resourceUrl);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record = {};\n setResourceEntrySizeData(data, entry, 'transferSize', 'http.response_transfer_size');\n setResourceEntrySizeData(data, entry, 'encodedBodySize', 'http.response_content_length');\n setResourceEntrySizeData(data, entry, 'decodedBodySize', 'http.decoded_response_content_length');\n\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n if (parsedUrl.protocol) {\n data['url.scheme'] = parsedUrl.protocol.split(':').pop(); // the protocol returned by parseUrl includes a :, but OTEL spec does not, so we remove it.\n }\n\n if (parsedUrl.host) {\n data['server.address'] = parsedUrl.host;\n }\n\n data['url.same_origin'] = resourceUrl.includes(WINDOW.location.origin);\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceUrl.replace(WINDOW.location.origin, ''),\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n origin: 'auto.resource.browser.metrics',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nfunction setResourceEntrySizeData(\n data: Record,\n entry: ResourceEntry,\n key: keyof Pick,\n dataKey: 'http.response_transfer_size' | 'http.response_content_length' | 'http.decoded_response_content_length',\n): void {\n const entryVal = entry[key];\n if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {\n data[dataKey] = entryVal;\n }\n}\n\n/**\n * Add ttfb request time information to measurements.\n *\n * ttfb information is added via vendored web vitals library.\n */\nfunction _addTtfbRequestTimeToMeasurements(_measurements: Measurements): void {\n const navEntry = getNavigationEntry();\n if (!navEntry) {\n return;\n }\n\n const { responseStart, requestStart } = navEntry;\n\n if (requestStart <= responseStart) {\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB Request Time');\n _measurements['ttfb.requestTime'] = {\n value: responseStart - requestStart,\n unit: 'millisecond',\n };\n }\n}\n\n/** Taken from @sentry/core sampling.ts */\nfunction getSampleRate(\n transactionContext: TransactionContext | undefined,\n options: ClientOptions,\n interactionsSampleRate: number,\n): number | boolean {\n if (!hasTracingEnabled(options)) {\n return false;\n }\n let sampleRate;\n if (transactionContext !== undefined && typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler({\n transactionContext,\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n location: WINDOW.location,\n });\n } else if (transactionContext !== undefined && transactionContext.sampled !== undefined) {\n sampleRate = transactionContext.sampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n } else {\n sampleRate = 1;\n }\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding interaction span because of invalid sample rate.');\n return false;\n }\n if (sampleRate === true) {\n return interactionsSampleRate;\n } else if (sampleRate === false) {\n return 0;\n }\n return sampleRate * interactionsSampleRate;\n}\n","/* eslint-disable max-lines */\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToJSON,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, Span } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n SENTRY_XHR_DATA_KEY,\n addFetchInstrumentationHandler,\n addXhrInstrumentationHandler,\n browserPerformanceTimeOrigin,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n parseUrl,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nimport { instrumentFetchRequest } from '../common/fetch';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport { WINDOW } from './types';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * @deprecated Use the top-level `tracePropagationTargets` option in `Sentry.init` instead.\n * This option will be removed in v8.\n *\n * Default: ['localhost', /^\\//] @see {DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * If true, Sentry will capture http timings and add them to the corresponding http spans.\n *\n * Default: true\n */\n enableHTTPTimings: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial): void {\n const {\n traceFetch,\n traceXHR,\n // eslint-disable-next-line deprecation/deprecation\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record = {};\n\n if (traceFetch) {\n addFetchInstrumentationHandler(handlerData => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n // We cannot use `window.location` in the generic fetch instrumentation,\n // but we need it for reliable `server.address` attribute.\n // so we extend this in here\n if (createdSpan) {\n const fullUrl = getFullURL(handlerData.fetchData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n createdSpan.setAttributes({\n 'http.url': fullUrl,\n 'server.address': host,\n });\n }\n\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry as PerformanceResourceTiming).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span: Span): void {\n const { url } = spanToJSON(span).data || {};\n\n if (!url || typeof url !== 'string') {\n return;\n }\n\n const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setAttribute(...data));\n // In the next tick, clean this handler up\n // We have to wait here because otherwise this cleans itself up before it is fully done\n setTimeout(cleanup);\n }\n });\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nexport function extractNetworkProtocol(nextHopProtocol: string): { name: string; version: string } {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/');\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1];\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time: number = 0): number {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming: PerformanceResourceTiming): [string, string | number][] {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData: [string, string | number][] = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nexport function xhrCallback(\n handlerData: HandlerDataXhr,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): Span | undefined {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span && sentryXhrData.status_code !== undefined) {\n setHttpStatus(span, sentryXhrData.status_code);\n span.end();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const isolationScope = getIsolationScope();\n\n const fullUrl = getFullURL(sentryXhrData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${sentryXhrData.method} ${sentryXhrData.url}`,\n onlyIfParent: true,\n attributes: {\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n 'http.url': fullUrl,\n url: sentryXhrData.url,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n const client = getClient();\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) {\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n\n return span;\n}\n\nfunction setHeaderOnXhr(\n xhr: SentryWrappedXMLHttpRequest,\n sentryTraceHeader: string,\n sentryBaggageHeader: string | undefined,\n): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n // By adding a base URL to new URL(), this will also work for relative urls\n // If `url` is a full URL, the base URL is ignored anyhow\n const parsed = new URL(url, WINDOW.location.origin);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n","import {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { Client, HandlerDataFetch, Scope, Span, SpanOrigin } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n isInstanceOf,\n parseUrl,\n} from '@sentry/utils';\n\ntype PolymorphicRequestHeaders =\n | Record\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\n/**\n * Create and track fetch request spans for usage in combination with `addInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n handlerData: HandlerDataFetch,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n spanOrigin: SpanOrigin = 'auto.http.browser',\n): Span | undefined {\n if (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const client = getClient();\n\n const { method, url } = handlerData.fetchData;\n\n const fullUrl = getFullURL(url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${method} ${url}`,\n onlyIfParent: true,\n attributes: {\n url,\n type: 'fetch',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n client: Client,\n scope: Scope,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n requestSpan?: Span,\n): PolymorphicRequestHeaders | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const span = requestSpan || scope.getSpan();\n\n const isolationScope = getIsolationScope();\n\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n const headers =\n options.headers ||\n (typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : undefined);\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n\nfunction endSpan(span: Span, handlerData: HandlerDataFetch): void {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength =\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.end();\n}\n","/* eslint-disable max-lines */\nimport type { Hub, IdleTransaction } from '@sentry/core';\nimport { getClient, getCurrentScope } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n TRACING_DEFAULTS,\n addTracingExtensions,\n getActiveTransaction,\n startIdleTransaction,\n} from '@sentry/core';\nimport type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';\nimport { getDomElement, logger, propagationContextFromHeaders } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport {\n addPerformanceEntries,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nimport { WINDOW } from './types';\nimport type { InteractionRouteNameMapping } from './web-vitals/types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * If true, Sentry will capture INP web vitals as standalone spans .\n *\n * Default: false\n */\n enableInp: boolean;\n\n /**\n * Sample rate to determine interaction span sampling.\n * interactionsSampleRate is applied on top of the global tracesSampleRate.\n * ie a tracesSampleRate of 0.1 and interactionsSampleRate of 0.5 will result in a 0.05 sample rate for interactions.\n *\n * Default: 1\n */\n interactionsSampleRate: number;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableLongTask: boolean;\n enableInteractions: boolean;\n // eslint-disable-next-line deprecation/deprecation\n onStartRouteTransaction: (t: Transaction | undefined, ctx: TransactionContext, getCurrentHub: () => Hub) => void;\n }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(this: void, context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation(\n this: void,\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n enableInp: false,\n interactionsSampleRate: 1,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */\nconst MAX_INTERACTIONS = 10;\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n *\n * @deprecated Use `browserTracingIntegration()` instead.\n */\nexport class BrowserTracing implements Integration {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n // eslint-disable-next-line deprecation/deprecation\n private _getCurrentHub?: () => Hub;\n\n private _collectWebVitals: () => void;\n\n private _hasSetTracePropagationTargets: boolean;\n private _interactionIdToRouteNameMapping: InteractionRouteNameMapping;\n private _latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n };\n\n public constructor(_options?: Partial) {\n this.name = BROWSER_TRACING_INTEGRATION_ID;\n this._hasSetTracePropagationTargets = false;\n\n addTracingExtensions();\n\n if (DEBUG_BUILD) {\n this._hasSetTracePropagationTargets = !!(\n _options &&\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n );\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */\n this._interactionIdToRouteNameMapping = {};\n\n if (this.options.enableInp) {\n startTrackingINP(this._interactionIdToRouteNameMapping, this.options.interactionsSampleRate);\n }\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n\n this._latestRoute = {\n name: undefined,\n context: undefined,\n };\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const clientOptions = client && client.getOptions();\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n _experiments,\n } = this.options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;\n if (DEBUG_BUILD && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n instrumentRouting(\n (context: TransactionContext) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n if (this.options.enableInp) {\n this._registerInpInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n let expandedContext: TransactionContext;\n if (isPageloadTransaction) {\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined;\n const { traceId, dsc, parentSpanId, sampled } = propagationContextFromHeaders(sentryTrace, baggage);\n expandedContext = {\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...context,\n metadata: {\n // eslint-disable-next-line deprecation/deprecation\n ...context.metadata,\n dynamicSamplingContext: dsc,\n },\n trimEnd: true,\n };\n } else {\n expandedContext = {\n trimEnd: true,\n ...context,\n };\n }\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? // eslint-disable-next-line deprecation/deprecation\n { ...finalContext.metadata, source: 'custom' }\n : // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata;\n\n this._latestRoute.name = finalContext.name;\n this._latestRoute.context = finalContext;\n\n // eslint-disable-next-line deprecation/deprecation\n if (finalContext.sampled === false) {\n DEBUG_BUILD && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n DEBUG_BUILD && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n isPageloadTransaction, // should wait for finish signal if it's a pageload transaction\n );\n\n if (isPageloadTransaction) {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n if (['interactive', 'complete'].includes(WINDOW.document!.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n });\n\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n }\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n /** Start listener for interaction transactions */\n private _registerInteractionListener(): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n // eslint-disable-next-line deprecation/deprecation\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.end();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: this._latestRoute.name,\n op,\n trimEnd: true,\n data: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: this._latestRoute.context\n ? getSource(this._latestRoute.context)\n : undefined || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n }\n });\n }\n\n /** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */\n private _registerInpInteractionListener(): void {\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const client = getClient();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay =\n client !== undefined && client.getIntegrationByName !== undefined\n ? (client.getIntegrationByName('Replay') as Integration & { getReplayId: () => string })\n : undefined;\n const replayId = replay !== undefined ? replay.getReplayId() : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n const currentScope = getCurrentScope();\n const user = currentScope !== undefined ? currentScope.getUser() : undefined;\n entries.forEach(entry => {\n if (isPerformanceEventTiming(entry)) {\n const interactionId = entry.interactionId;\n if (interactionId === undefined) {\n return;\n }\n const existingInteraction = this._interactionIdToRouteNameMapping[interactionId];\n const duration = entry.duration;\n const startTime = entry.startTime;\n const keys = Object.keys(this._interactionIdToRouteNameMapping);\n const minInteractionId =\n keys.length > 0\n ? keys.reduce((a, b) => {\n return this._interactionIdToRouteNameMapping[a].duration <\n this._interactionIdToRouteNameMapping[b].duration\n ? a\n : b;\n })\n : undefined;\n // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time.\n // This is also checked in the web-vitals library.\n if (entry.entryType === 'first-input') {\n const matchingEntry = keys\n .map(key => this._interactionIdToRouteNameMapping[key])\n .some(interaction => {\n return interaction.duration === duration && interaction.startTime === startTime;\n });\n if (matchingEntry) {\n return;\n }\n }\n // Interactions with an id of 0 and are not first-input are not valid.\n if (!interactionId) {\n return;\n }\n // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses.\n if (existingInteraction) {\n existingInteraction.duration = Math.max(existingInteraction.duration, duration);\n } else if (\n keys.length < MAX_INTERACTIONS ||\n minInteractionId === undefined ||\n duration > this._interactionIdToRouteNameMapping[minInteractionId].duration\n ) {\n // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry.\n const routeName = this._latestRoute.name;\n const parentContext = this._latestRoute.context;\n if (routeName && parentContext) {\n if (minInteractionId && Object.keys(this._interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._interactionIdToRouteNameMapping[minInteractionId];\n }\n this._interactionIdToRouteNameMapping[interactionId] = {\n routeName,\n duration,\n parentContext,\n user,\n activeTransaction,\n replayId,\n startTime,\n };\n }\n }\n }\n });\n };\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n }\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\nfunction getSource(context: TransactionContext): TransactionSource | undefined {\n const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromData = context.data && context.data[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromMetadata = context.metadata && context.metadata.source;\n\n return sourceFromAttributes || sourceFromData || sourceFromMetadata;\n}\n\nfunction isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n","import type { Transaction, TransactionContext } from '@sentry/types';\nimport { addHistoryInstrumentationHandler, browserPerformanceTimeOrigin, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!WINDOW || !WINDOW.location) {\n DEBUG_BUILD && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = WINDOW.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n origin: 'auto.pageload.browser',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.end();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n origin: 'auto.navigation.browser',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n","import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction, spanToJSON } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document!.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n const { op, status } = spanToJSON(activeTransaction);\n\n DEBUG_BUILD &&\n logger.log(`[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${op}`);\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!status) {\n activeTransaction.setStatus(statusType);\n }\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.end();\n }\n });\n } else {\n DEBUG_BUILD && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n","import type { MeasurementUnit } from '@sentry/types';\n\nimport { getActiveTransaction } from './utils';\n\n/**\n * Adds a measurement to the current active transaction.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit): void {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction();\n if (transaction) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setMeasurement(name, value, unit);\n }\n}\n","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type { GenericFunction } from './types';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nexport function _optionalChain(ops: unknown[]): unknown {\n let lastAccessLHS: unknown = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] as string;\n const fn = ops[i + 1] as (intermediateValue: unknown) => unknown;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args: unknown[]) => (value as GenericFunction).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n","import type { Client, DsnComponents, Hub } from '@sentry/types';\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n *\n * TODO(v8): Remove Hub fallback type\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function isSentryRequestUrl(url: string, hubOrClient: Hub | Client | undefined): boolean {\n const client =\n hubOrClient && isHub(hubOrClient)\n ? // eslint-disable-next-line deprecation/deprecation\n hubOrClient.getClient()\n : hubOrClient;\n const dsn = client && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url: string, tunnel: string | undefined): boolean {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url: string, dsn: DsnComponents | undefined): boolean {\n return dsn ? url.includes(dsn.host) : false;\n}\n\nfunction removeTrailingSlash(str: string): string {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction isHub(hubOrClient: Hub | Client | undefined): hubOrClient is Hub {\n // eslint-disable-next-line deprecation/deprecation\n return (hubOrClient as Hub).getClient !== undefined;\n}\n","import type { DataCategory, TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = Date.now()): boolean {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import { isNodeEnv } from './node';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n return (\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (GLOBAL_OBJ as any).process !== undefined && ((GLOBAL_OBJ as any).process as ElectronProcess).type === 'renderer'\n );\n}\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nexport const REPLAY_SESSION_KEY = 'sentryReplaySession';\nexport const REPLAY_EVENT_NAME = 'replay_event';\nexport const RECORDING_EVENT_NAME = 'replay_recording';\nexport const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nexport const SESSION_IDLE_PAUSE_DURATION = 300_000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nexport const SESSION_IDLE_EXPIRE_DURATION = 900_000; // 15 minutes in ms\n\n/** Default flush delays */\nexport const DEFAULT_FLUSH_MIN_DELAY = 5_000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nexport const DEFAULT_FLUSH_MAX_DELAY = 5_500;\n\n/* How long to wait for error checkouts */\nexport const BUFFER_CHECKOUT_TIME = 60_000;\n\nexport const RETRY_BASE_INTERVAL = 5000;\nexport const RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nexport const NETWORK_BODY_MAX_SIZE = 150_000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nexport const CONSOLE_ARG_MAX_SIZE = 5_000;\n\n/* Min. time to wait before we consider something a slow click. */\nexport const SLOW_CLICK_THRESHOLD = 3_000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nexport const SLOW_CLICK_SCROLL_TIMEOUT = 300;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nexport const REPLAY_MAX_EVENT_BUFFER_SIZE = 20_000_000; // ~20MB\n\n/** Replays must be min. 5s long before we send them. */\nexport const MIN_REPLAY_DURATION = 4_999;\n/* The max. allowed value that the minReplayDuration can be set to. */\nexport const MIN_REPLAY_DURATION_LIMIT = 15_000;\n\n/** The max. length of a replay. */\nexport const MAX_REPLAY_DURATION = 3_600_000; // 60 minutes in ms;\n\n/** Default attributes to be ignored when `maskAllText` is enabled */\nexport const DEFAULT_IGNORED_ATTRIBUTES = ['title', 'placeholder'];\n","var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute };\n","import { distanceToMatch, IGNORED_NODE, isShadowRoot, createMatchPredicate } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\r\n const options = { capture: true, passive: true };\r\n target.addEventListener(type, fn, options);\r\n return () => target.removeEventListener(type, fn, options);\r\n}\r\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\r\n '\\r\\n' +\r\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\r\n '\\r\\n' +\r\n 'or you can use record.mirror to access the mirror instance during recording.';\r\nlet _mirror = {\r\n map: {},\r\n getId() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return -1;\r\n },\r\n getNode() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return null;\r\n },\r\n removeNodeFromMap() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n has() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return false;\r\n },\r\n reset() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n};\r\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\r\n _mirror = new Proxy(_mirror, {\r\n get(target, prop, receiver) {\r\n if (prop === 'map') {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n }\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\nfunction throttle(func, wait, options = {}) {\r\n let timeout = null;\r\n let previous = 0;\r\n return function (...args) {\r\n const now = Date.now();\r\n if (!previous && options.leading === false) {\r\n previous = now;\r\n }\r\n const remaining = wait - (now - previous);\r\n const context = this;\r\n if (remaining <= 0 || remaining > wait) {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n }\r\n previous = now;\r\n func.apply(context, args);\r\n }\r\n else if (!timeout && options.trailing !== false) {\r\n timeout = setTimeout(() => {\r\n previous = options.leading === false ? 0 : Date.now();\r\n timeout = null;\r\n func.apply(context, args);\r\n }, remaining);\r\n }\r\n };\r\n}\r\nfunction hookSetter(target, key, d, isRevoked, win = window) {\r\n const original = win.Object.getOwnPropertyDescriptor(target, key);\r\n win.Object.defineProperty(target, key, isRevoked\r\n ? d\r\n : {\r\n set(value) {\r\n setTimeout(() => {\r\n d.set.call(this, value);\r\n }, 0);\r\n if (original && original.set) {\r\n original.set.call(this, value);\r\n }\r\n },\r\n });\r\n return () => hookSetter(target, key, original || {}, true);\r\n}\r\nfunction patch(source, name, replacement) {\r\n try {\r\n if (!(name in source)) {\r\n return () => {\r\n };\r\n }\r\n const original = source[name];\r\n const wrapped = replacement(original);\r\n if (typeof wrapped === 'function') {\r\n wrapped.prototype = wrapped.prototype || {};\r\n Object.defineProperties(wrapped, {\r\n __rrweb_original__: {\r\n enumerable: false,\r\n value: original,\r\n },\r\n });\r\n }\r\n source[name] = wrapped;\r\n return () => {\r\n source[name] = original;\r\n };\r\n }\r\n catch {\r\n return () => {\r\n };\r\n }\r\n}\r\nlet nowTimestamp = Date.now;\r\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\r\n nowTimestamp = () => new Date().getTime();\r\n}\r\nfunction getWindowScroll(win) {\r\n const doc = win.document;\r\n return {\r\n left: doc.scrollingElement\r\n ? doc.scrollingElement.scrollLeft\r\n : win.pageXOffset !== undefined\r\n ? win.pageXOffset\r\n : doc?.documentElement.scrollLeft ||\r\n doc?.body?.parentElement?.scrollLeft ||\r\n doc?.body?.scrollLeft ||\r\n 0,\r\n top: doc.scrollingElement\r\n ? doc.scrollingElement.scrollTop\r\n : win.pageYOffset !== undefined\r\n ? win.pageYOffset\r\n : doc?.documentElement.scrollTop ||\r\n doc?.body?.parentElement?.scrollTop ||\r\n doc?.body?.scrollTop ||\r\n 0,\r\n };\r\n}\r\nfunction getWindowHeight() {\r\n return (window.innerHeight ||\r\n (document.documentElement && document.documentElement.clientHeight) ||\r\n (document.body && document.body.clientHeight));\r\n}\r\nfunction getWindowWidth() {\r\n return (window.innerWidth ||\r\n (document.documentElement && document.documentElement.clientWidth) ||\r\n (document.body && document.body.clientWidth));\r\n}\r\nfunction closestElementOfNode(node) {\r\n if (!node) {\r\n return null;\r\n }\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n return el;\r\n}\r\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\r\n if (!node) {\r\n return false;\r\n }\r\n const el = closestElementOfNode(node);\r\n if (!el) {\r\n return false;\r\n }\r\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\r\n if (!checkAncestors) {\r\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\r\n return blockedPredicate(el) && !isUnblocked;\r\n }\r\n const blockDistance = distanceToMatch(el, blockedPredicate);\r\n let unblockDistance = -1;\r\n if (blockDistance < 0) {\r\n return false;\r\n }\r\n if (unblockSelector) {\r\n unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector));\r\n }\r\n if (blockDistance > -1 && unblockDistance < 0) {\r\n return true;\r\n }\r\n return blockDistance < unblockDistance;\r\n}\r\nfunction isSerialized(n, mirror) {\r\n return mirror.getId(n) !== -1;\r\n}\r\nfunction isIgnored(n, mirror) {\r\n return mirror.getId(n) === IGNORED_NODE;\r\n}\r\nfunction isAncestorRemoved(target, mirror) {\r\n if (isShadowRoot(target)) {\r\n return false;\r\n }\r\n const id = mirror.getId(target);\r\n if (!mirror.has(id)) {\r\n return true;\r\n }\r\n if (target.parentNode &&\r\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\r\n return false;\r\n }\r\n if (!target.parentNode) {\r\n return true;\r\n }\r\n return isAncestorRemoved(target.parentNode, mirror);\r\n}\r\nfunction legacy_isTouchEvent(event) {\r\n return Boolean(event.changedTouches);\r\n}\r\nfunction polyfill(win = window) {\r\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\r\n win.NodeList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\r\n win.DOMTokenList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if (!Node.prototype.contains) {\r\n Node.prototype.contains = (...args) => {\r\n let node = args[0];\r\n if (!(0 in args)) {\r\n throw new TypeError('1 argument is required');\r\n }\r\n do {\r\n if (this === node) {\r\n return true;\r\n }\r\n } while ((node = node && node.parentNode));\r\n return false;\r\n };\r\n }\r\n}\r\nfunction queueToResolveTrees(queue) {\r\n const queueNodeMap = {};\r\n const putIntoMap = (m, parent) => {\r\n const nodeInTree = {\r\n value: m,\r\n parent,\r\n children: [],\r\n };\r\n queueNodeMap[m.node.id] = nodeInTree;\r\n return nodeInTree;\r\n };\r\n const queueNodeTrees = [];\r\n for (const mutation of queue) {\r\n const { nextId, parentId } = mutation;\r\n if (nextId && nextId in queueNodeMap) {\r\n const nextInTree = queueNodeMap[nextId];\r\n if (nextInTree.parent) {\r\n const idx = nextInTree.parent.children.indexOf(nextInTree);\r\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\r\n }\r\n else {\r\n const idx = queueNodeTrees.indexOf(nextInTree);\r\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\r\n }\r\n continue;\r\n }\r\n if (parentId in queueNodeMap) {\r\n const parentInTree = queueNodeMap[parentId];\r\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\r\n continue;\r\n }\r\n queueNodeTrees.push(putIntoMap(mutation, null));\r\n }\r\n return queueNodeTrees;\r\n}\r\nfunction iterateResolveTree(tree, cb) {\r\n cb(tree.value);\r\n for (let i = tree.children.length - 1; i >= 0; i--) {\r\n iterateResolveTree(tree.children[i], cb);\r\n }\r\n}\r\nfunction isSerializedIframe(n, mirror) {\r\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\r\n}\r\nfunction isSerializedStylesheet(n, mirror) {\r\n return Boolean(n.nodeName === 'LINK' &&\r\n n.nodeType === n.ELEMENT_NODE &&\r\n n.getAttribute &&\r\n n.getAttribute('rel') === 'stylesheet' &&\r\n mirror.getMeta(n));\r\n}\r\nfunction getBaseDimension(node, rootIframe) {\r\n const frameElement = node.ownerDocument?.defaultView?.frameElement;\r\n if (!frameElement || frameElement === rootIframe) {\r\n return {\r\n x: 0,\r\n y: 0,\r\n relativeScale: 1,\r\n absoluteScale: 1,\r\n };\r\n }\r\n const frameDimension = frameElement.getBoundingClientRect();\r\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\r\n const relativeScale = frameDimension.height / frameElement.clientHeight;\r\n return {\r\n x: frameDimension.x * frameBaseDimension.relativeScale +\r\n frameBaseDimension.x,\r\n y: frameDimension.y * frameBaseDimension.relativeScale +\r\n frameBaseDimension.y,\r\n relativeScale,\r\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\r\n };\r\n}\r\nfunction hasShadowRoot(n) {\r\n return Boolean(n?.shadowRoot);\r\n}\r\nfunction getNestedRule(rules, position) {\r\n const rule = rules[position[0]];\r\n if (position.length === 1) {\r\n return rule;\r\n }\r\n else {\r\n return getNestedRule(rule.cssRules[position[1]].cssRules, position.slice(2));\r\n }\r\n}\r\nfunction getPositionsAndIndex(nestedIndex) {\r\n const positions = [...nestedIndex];\r\n const index = positions.pop();\r\n return { positions, index };\r\n}\r\nfunction uniqueTextMutations(mutations) {\r\n const idSet = new Set();\r\n const uniqueMutations = [];\r\n for (let i = mutations.length; i--;) {\r\n const mutation = mutations[i];\r\n if (!idSet.has(mutation.id)) {\r\n uniqueMutations.push(mutation);\r\n idSet.add(mutation.id);\r\n }\r\n }\r\n return uniqueMutations;\r\n}\r\nclass StyleSheetMirror {\r\n constructor() {\r\n this.id = 1;\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n }\r\n getId(stylesheet) {\r\n return this.styleIDMap.get(stylesheet) ?? -1;\r\n }\r\n has(stylesheet) {\r\n return this.styleIDMap.has(stylesheet);\r\n }\r\n add(stylesheet, id) {\r\n if (this.has(stylesheet))\r\n return this.getId(stylesheet);\r\n let newId;\r\n if (id === undefined) {\r\n newId = this.id++;\r\n }\r\n else\r\n newId = id;\r\n this.styleIDMap.set(stylesheet, newId);\r\n this.idStyleMap.set(newId, stylesheet);\r\n return newId;\r\n }\r\n getStyle(id) {\r\n return this.idStyleMap.get(id) || null;\r\n }\r\n reset() {\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n this.id = 1;\r\n }\r\n generateId() {\r\n return this.id++;\r\n }\r\n}\r\nfunction getShadowHost(n) {\r\n let shadowHost = null;\r\n if (n.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\r\n n.getRootNode().host)\r\n shadowHost = n.getRootNode().host;\r\n return shadowHost;\r\n}\r\nfunction getRootShadowHost(n) {\r\n let rootShadowHost = n;\r\n let shadowHost;\r\n while ((shadowHost = getShadowHost(rootShadowHost)))\r\n rootShadowHost = shadowHost;\r\n return rootShadowHost;\r\n}\r\nfunction shadowHostInDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n const shadowHost = getRootShadowHost(n);\r\n return doc.contains(shadowHost);\r\n}\r\nfunction inDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n return doc.contains(n) || shadowHostInDom(n);\r\n}\r\nconst cachedImplementations = {};\r\nfunction getImplementation(name) {\r\n const cached = cachedImplementations[name];\r\n if (cached) {\r\n return cached;\r\n }\r\n const document = window.document;\r\n let impl = window[name];\r\n if (document && typeof document.createElement === 'function') {\r\n try {\r\n const sandbox = document.createElement('iframe');\r\n sandbox.hidden = true;\r\n document.head.appendChild(sandbox);\r\n const contentWindow = sandbox.contentWindow;\r\n if (contentWindow && contentWindow[name]) {\r\n impl =\r\n contentWindow[name];\r\n }\r\n document.head.removeChild(sandbox);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return (cachedImplementations[name] = impl.bind(window));\r\n}\r\nfunction onRequestAnimationFrame(...rest) {\r\n return getImplementation('requestAnimationFrame')(...rest);\r\n}\r\nfunction setTimeout(...rest) {\r\n return getImplementation('setTimeout')(...rest);\r\n}\r\nfunction clearTimeout(...rest) {\r\n return getImplementation('clearTimeout')(...rest);\r\n}\n\nexport { StyleSheetMirror, _mirror, clearTimeout, closestElementOfNode, getBaseDimension, getNestedRule, getPositionsAndIndex, getRootShadowHost, getShadowHost, getWindowHeight, getWindowScroll, getWindowWidth, hasShadowRoot, hookSetter, inDom, isAncestorRemoved, isBlocked, isIgnored, isSerialized, isSerializedIframe, isSerializedStylesheet, iterateResolveTree, legacy_isTouchEvent, nowTimestamp, on, onRequestAnimationFrame, patch, polyfill, queueToResolveTrees, setTimeout, shadowHostInDom, throttle, uniqueTextMutations };\n","// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Polyfill for the nullish coalescing operator (`??`).\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nexport function _nullishCoalesce(lhs: unknown, rhsFn: () => unknown): unknown {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}\n\n// Sucrase version:\n// function _nullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return rhsFn();\n// }\n// }\n","var EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {\n ReplayerEvents2[\"Start\"] = \"start\";\n ReplayerEvents2[\"Pause\"] = \"pause\";\n ReplayerEvents2[\"Resume\"] = \"resume\";\n ReplayerEvents2[\"Resize\"] = \"resize\";\n ReplayerEvents2[\"Finish\"] = \"finish\";\n ReplayerEvents2[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents2[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents2[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents2[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents2[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents2[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents2[\"EventCast\"] = \"event-cast\";\n ReplayerEvents2[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents2[\"Flush\"] = \"flush\";\n ReplayerEvents2[\"StateChange\"] = \"state-change\";\n ReplayerEvents2[\"PlayBack\"] = \"play-back\";\n ReplayerEvents2[\"Destroy\"] = \"destroy\";\n return ReplayerEvents2;\n})(ReplayerEvents || {});\n\nexport { CanvasContext, EventType, IncrementalSource, MouseInteractions, PointerTypes, ReplayerEvents };\n","import { isShadowRoot, isNativeShadowDom, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue, ignoreAttribute, transformAttribute, toLowerCase, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isSerialized, isAncestorRemoved, closestElementOfNode, hasShadowRoot, inDom, getShadowHost, isSerializedIframe, isSerializedStylesheet } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\r\n return '__ln' in n;\r\n}\r\nclass DoubleLinkedList {\r\n constructor() {\r\n this.length = 0;\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n get(position) {\r\n if (position >= this.length) {\r\n throw new Error('Position outside of list range');\r\n }\r\n let current = this.head;\r\n for (let index = 0; index < position; index++) {\r\n current = current?.next || null;\r\n }\r\n return current;\r\n }\r\n addNode(n) {\r\n const node = {\r\n value: n,\r\n previous: null,\r\n next: null,\r\n };\r\n n.__ln = node;\r\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\r\n const current = n.previousSibling.__ln.next;\r\n node.next = current;\r\n node.previous = n.previousSibling.__ln;\r\n n.previousSibling.__ln.next = node;\r\n if (current) {\r\n current.previous = node;\r\n }\r\n }\r\n else if (n.nextSibling &&\r\n isNodeInLinkedList(n.nextSibling) &&\r\n n.nextSibling.__ln.previous) {\r\n const current = n.nextSibling.__ln.previous;\r\n node.previous = current;\r\n node.next = n.nextSibling.__ln;\r\n n.nextSibling.__ln.previous = node;\r\n if (current) {\r\n current.next = node;\r\n }\r\n }\r\n else {\r\n if (this.head) {\r\n this.head.previous = node;\r\n }\r\n node.next = this.head;\r\n this.head = node;\r\n }\r\n if (node.next === null) {\r\n this.tail = node;\r\n }\r\n this.length++;\r\n }\r\n removeNode(n) {\r\n const current = n.__ln;\r\n if (!this.head) {\r\n return;\r\n }\r\n if (!current.previous) {\r\n this.head = current.next;\r\n if (this.head) {\r\n this.head.previous = null;\r\n }\r\n else {\r\n this.tail = null;\r\n }\r\n }\r\n else {\r\n current.previous.next = current.next;\r\n if (current.next) {\r\n current.next.previous = current.previous;\r\n }\r\n else {\r\n this.tail = current.previous;\r\n }\r\n }\r\n if (n.__ln) {\r\n delete n.__ln;\r\n }\r\n this.length--;\r\n }\r\n}\r\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\r\nclass MutationBuffer {\r\n constructor() {\r\n this.frozen = false;\r\n this.locked = false;\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.mapRemoves = [];\r\n this.movedMap = {};\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.processMutations = (mutations) => {\r\n mutations.forEach(this.processMutation);\r\n this.emit();\r\n };\r\n this.emit = () => {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const adds = [];\r\n const addedIds = new Set();\r\n const addList = new DoubleLinkedList();\r\n const getNextId = (n) => {\r\n let ns = n;\r\n let nextId = IGNORED_NODE;\r\n while (nextId === IGNORED_NODE) {\r\n ns = ns && ns.nextSibling;\r\n nextId = ns && this.mirror.getId(ns);\r\n }\r\n return nextId;\r\n };\r\n const pushAdd = (n) => {\r\n if (!n.parentNode || !inDom(n)) {\r\n return;\r\n }\r\n const parentId = isShadowRoot(n.parentNode)\r\n ? this.mirror.getId(getShadowHost(n))\r\n : this.mirror.getId(n.parentNode);\r\n const nextId = getNextId(n);\r\n if (parentId === -1 || nextId === -1) {\r\n return addList.addNode(n);\r\n }\r\n const sn = serializeNodeWithId(n, {\r\n doc: this.doc,\r\n mirror: this.mirror,\r\n blockClass: this.blockClass,\r\n blockSelector: this.blockSelector,\r\n maskAllText: this.maskAllText,\r\n unblockSelector: this.unblockSelector,\r\n maskTextClass: this.maskTextClass,\r\n unmaskTextClass: this.unmaskTextClass,\r\n maskTextSelector: this.maskTextSelector,\r\n unmaskTextSelector: this.unmaskTextSelector,\r\n skipChild: true,\r\n newlyAddedElement: true,\r\n inlineStylesheet: this.inlineStylesheet,\r\n maskInputOptions: this.maskInputOptions,\r\n maskAttributeFn: this.maskAttributeFn,\r\n maskTextFn: this.maskTextFn,\r\n maskInputFn: this.maskInputFn,\r\n slimDOMOptions: this.slimDOMOptions,\r\n dataURLOptions: this.dataURLOptions,\r\n recordCanvas: this.recordCanvas,\r\n inlineImages: this.inlineImages,\r\n onSerialize: (currentN) => {\r\n if (isSerializedIframe(currentN, this.mirror)) {\r\n this.iframeManager.addIframe(currentN);\r\n }\r\n if (isSerializedStylesheet(currentN, this.mirror)) {\r\n this.stylesheetManager.trackLinkElement(currentN);\r\n }\r\n if (hasShadowRoot(n)) {\r\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n this.iframeManager.attachIframe(iframe, childSn);\r\n this.shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (link, childSn) => {\r\n this.stylesheetManager.attachLinkElement(link, childSn);\r\n },\r\n });\r\n if (sn) {\r\n adds.push({\r\n parentId,\r\n nextId,\r\n node: sn,\r\n });\r\n addedIds.add(sn.id);\r\n }\r\n };\r\n while (this.mapRemoves.length) {\r\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\r\n }\r\n for (const n of this.movedSet) {\r\n if (isParentRemoved(this.removes, n, this.mirror) &&\r\n !this.movedSet.has(n.parentNode)) {\r\n continue;\r\n }\r\n pushAdd(n);\r\n }\r\n for (const n of this.addedSet) {\r\n if (!isAncestorInSet(this.droppedSet, n) &&\r\n !isParentRemoved(this.removes, n, this.mirror)) {\r\n pushAdd(n);\r\n }\r\n else if (isAncestorInSet(this.movedSet, n)) {\r\n pushAdd(n);\r\n }\r\n else {\r\n this.droppedSet.add(n);\r\n }\r\n }\r\n let candidate = null;\r\n while (addList.length) {\r\n let node = null;\r\n if (candidate) {\r\n const parentId = this.mirror.getId(candidate.value.parentNode);\r\n const nextId = getNextId(candidate.value);\r\n if (parentId !== -1 && nextId !== -1) {\r\n node = candidate;\r\n }\r\n }\r\n if (!node) {\r\n let tailNode = addList.tail;\r\n while (tailNode) {\r\n const _node = tailNode;\r\n tailNode = tailNode.previous;\r\n if (_node) {\r\n const parentId = this.mirror.getId(_node.value.parentNode);\r\n const nextId = getNextId(_node.value);\r\n if (nextId === -1)\r\n continue;\r\n else if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n else {\r\n const unhandledNode = _node.value;\r\n if (unhandledNode.parentNode &&\r\n unhandledNode.parentNode.nodeType ===\r\n Node.DOCUMENT_FRAGMENT_NODE) {\r\n const shadowHost = unhandledNode.parentNode\r\n .host;\r\n const parentId = this.mirror.getId(shadowHost);\r\n if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (!node) {\r\n while (addList.head) {\r\n addList.removeNode(addList.head.value);\r\n }\r\n break;\r\n }\r\n candidate = node.previous;\r\n addList.removeNode(node.value);\r\n pushAdd(node.value);\r\n }\r\n const payload = {\r\n texts: this.texts\r\n .map((text) => ({\r\n id: this.mirror.getId(text.node),\r\n value: text.value,\r\n }))\r\n .filter((text) => !addedIds.has(text.id))\r\n .filter((text) => this.mirror.has(text.id)),\r\n attributes: this.attributes\r\n .map((attribute) => {\r\n const { attributes } = attribute;\r\n if (typeof attributes.style === 'string') {\r\n const diffAsStr = JSON.stringify(attribute.styleDiff);\r\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\r\n if (diffAsStr.length < attributes.style.length) {\r\n if ((diffAsStr + unchangedAsStr).split('var(').length ===\r\n attributes.style.split('var(').length) {\r\n attributes.style = attribute.styleDiff;\r\n }\r\n }\r\n }\r\n return {\r\n id: this.mirror.getId(attribute.node),\r\n attributes: attributes,\r\n };\r\n })\r\n .filter((attribute) => !addedIds.has(attribute.id))\r\n .filter((attribute) => this.mirror.has(attribute.id)),\r\n removes: this.removes,\r\n adds,\r\n };\r\n if (!payload.texts.length &&\r\n !payload.attributes.length &&\r\n !payload.removes.length &&\r\n !payload.adds.length) {\r\n return;\r\n }\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.movedMap = {};\r\n this.mutationCb(payload);\r\n };\r\n this.processMutation = (m) => {\r\n if (isIgnored(m.target, this.mirror)) {\r\n return;\r\n }\r\n switch (m.type) {\r\n case 'characterData': {\r\n const value = m.target.textContent;\r\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) &&\r\n value !== m.oldValue) {\r\n this.texts.push({\r\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value\r\n ? this.maskTextFn\r\n ? this.maskTextFn(value, closestElementOfNode(m.target))\r\n : value.replace(/[\\S]/g, '*')\r\n : value,\r\n node: m.target,\r\n });\r\n }\r\n break;\r\n }\r\n case 'attributes': {\r\n const target = m.target;\r\n let attributeName = m.attributeName;\r\n let value = m.target.getAttribute(attributeName);\r\n if (attributeName === 'value') {\r\n const type = getInputType(target);\r\n const tagName = target.tagName;\r\n value = getInputValue(target, tagName, type);\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions: this.maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked);\r\n value = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value,\r\n maskInputFn: this.maskInputFn,\r\n });\r\n }\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n value === m.oldValue) {\r\n return;\r\n }\r\n let item = this.attributeMap.get(m.target);\r\n if (target.tagName === 'IFRAME' &&\r\n attributeName === 'src' &&\r\n !this.keepIframeSrcFn(value)) {\r\n if (!target.contentDocument) {\r\n attributeName = 'rr_src';\r\n }\r\n else {\r\n return;\r\n }\r\n }\r\n if (!item) {\r\n item = {\r\n node: m.target,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(m.target, item);\r\n }\r\n if (attributeName === 'type' &&\r\n target.tagName === 'INPUT' &&\r\n (m.oldValue || '').toLowerCase() === 'password') {\r\n target.setAttribute('data-rr-is-password', 'true');\r\n }\r\n if (!ignoreAttribute(target.tagName, attributeName)) {\r\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn);\r\n if (attributeName === 'style') {\r\n if (!this.unattachedDoc) {\r\n try {\r\n this.unattachedDoc =\r\n document.implementation.createHTMLDocument();\r\n }\r\n catch (e) {\r\n this.unattachedDoc = this.doc;\r\n }\r\n }\r\n const old = this.unattachedDoc.createElement('span');\r\n if (m.oldValue) {\r\n old.setAttribute('style', m.oldValue);\r\n }\r\n for (const pname of Array.from(target.style)) {\r\n const newValue = target.style.getPropertyValue(pname);\r\n const newPriority = target.style.getPropertyPriority(pname);\r\n if (newValue !== old.style.getPropertyValue(pname) ||\r\n newPriority !== old.style.getPropertyPriority(pname)) {\r\n if (newPriority === '') {\r\n item.styleDiff[pname] = newValue;\r\n }\r\n else {\r\n item.styleDiff[pname] = [newValue, newPriority];\r\n }\r\n }\r\n else {\r\n item._unchangedStyles[pname] = [newValue, newPriority];\r\n }\r\n }\r\n for (const pname of Array.from(old.style)) {\r\n if (target.style.getPropertyValue(pname) === '') {\r\n item.styleDiff[pname] = false;\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 'childList': {\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) {\r\n return;\r\n }\r\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\r\n m.removedNodes.forEach((n) => {\r\n const nodeId = this.mirror.getId(n);\r\n const parentId = isShadowRoot(m.target)\r\n ? this.mirror.getId(m.target.host)\r\n : this.mirror.getId(m.target);\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n isIgnored(n, this.mirror) ||\r\n !isSerialized(n, this.mirror)) {\r\n return;\r\n }\r\n if (this.addedSet.has(n)) {\r\n deepDelete(this.addedSet, n);\r\n this.droppedSet.add(n);\r\n }\r\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\r\n else if (isAncestorRemoved(m.target, this.mirror)) ;\r\n else if (this.movedSet.has(n) &&\r\n this.movedMap[moveKey(nodeId, parentId)]) {\r\n deepDelete(this.movedSet, n);\r\n }\r\n else {\r\n this.removes.push({\r\n parentId,\r\n id: nodeId,\r\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\r\n ? true\r\n : undefined,\r\n });\r\n }\r\n this.mapRemoves.push(n);\r\n });\r\n break;\r\n }\r\n }\r\n };\r\n this.genAdds = (n, target) => {\r\n if (this.processedNodeManager.inOtherBuffer(n, this))\r\n return;\r\n if (this.addedSet.has(n) || this.movedSet.has(n))\r\n return;\r\n if (this.mirror.hasNode(n)) {\r\n if (isIgnored(n, this.mirror)) {\r\n return;\r\n }\r\n this.movedSet.add(n);\r\n let targetId = null;\r\n if (target && this.mirror.hasNode(target)) {\r\n targetId = this.mirror.getId(target);\r\n }\r\n if (targetId && targetId !== -1) {\r\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\r\n }\r\n }\r\n else {\r\n this.addedSet.add(n);\r\n this.droppedSet.delete(n);\r\n }\r\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\r\n n.childNodes.forEach((childN) => this.genAdds(childN));\r\n if (hasShadowRoot(n)) {\r\n n.shadowRoot.childNodes.forEach((childN) => {\r\n this.processedNodeManager.add(childN, this);\r\n this.genAdds(childN, n);\r\n });\r\n }\r\n }\r\n };\r\n }\r\n init(options) {\r\n [\r\n 'mutationCb',\r\n 'blockClass',\r\n 'blockSelector',\r\n 'unblockSelector',\r\n 'maskAllText',\r\n 'maskTextClass',\r\n 'unmaskTextClass',\r\n 'maskTextSelector',\r\n 'unmaskTextSelector',\r\n 'inlineStylesheet',\r\n 'maskInputOptions',\r\n 'maskAttributeFn',\r\n 'maskTextFn',\r\n 'maskInputFn',\r\n 'keepIframeSrcFn',\r\n 'recordCanvas',\r\n 'inlineImages',\r\n 'slimDOMOptions',\r\n 'dataURLOptions',\r\n 'doc',\r\n 'mirror',\r\n 'iframeManager',\r\n 'stylesheetManager',\r\n 'shadowDomManager',\r\n 'canvasManager',\r\n 'processedNodeManager',\r\n ].forEach((key) => {\r\n this[key] = options[key];\r\n });\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n this.canvasManager.freeze();\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n this.canvasManager.unfreeze();\r\n this.emit();\r\n }\r\n isFrozen() {\r\n return this.frozen;\r\n }\r\n lock() {\r\n this.locked = true;\r\n this.canvasManager.lock();\r\n }\r\n unlock() {\r\n this.locked = false;\r\n this.canvasManager.unlock();\r\n this.emit();\r\n }\r\n reset() {\r\n this.shadowDomManager.reset();\r\n this.canvasManager.reset();\r\n }\r\n}\r\nfunction deepDelete(addsSet, n) {\r\n addsSet.delete(n);\r\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\r\n}\r\nfunction isParentRemoved(removes, n, mirror) {\r\n if (removes.length === 0)\r\n return false;\r\n return _isParentRemoved(removes, n, mirror);\r\n}\r\nfunction _isParentRemoved(removes, n, mirror) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n const parentId = mirror.getId(parentNode);\r\n if (removes.some((r) => r.id === parentId)) {\r\n return true;\r\n }\r\n return _isParentRemoved(removes, parentNode, mirror);\r\n}\r\nfunction isAncestorInSet(set, n) {\r\n if (set.size === 0)\r\n return false;\r\n return _isAncestorInSet(set, n);\r\n}\r\nfunction _isAncestorInSet(set, n) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n if (set.has(parentNode)) {\r\n return true;\r\n }\r\n return _isAncestorInSet(set, parentNode);\r\n}\n\nexport { MutationBuffer as default };\n","let errorHandler;\r\nfunction registerErrorHandler(handler) {\r\n errorHandler = handler;\r\n}\r\nfunction unregisterErrorHandler() {\r\n errorHandler = undefined;\r\n}\r\nconst callbackWrapper = (cb) => {\r\n if (!errorHandler) {\r\n return cb;\r\n }\r\n const rrwebWrapped = ((...rest) => {\r\n try {\r\n return cb(...rest);\r\n }\r\n catch (error) {\r\n if (errorHandler && errorHandler(error) === true) {\r\n return () => {\r\n };\r\n }\r\n throw error;\r\n }\r\n });\r\n return rrwebWrapped;\r\n};\n\nexport { callbackWrapper, registerErrorHandler, unregisterErrorHandler };\n","import { toLowerCase, toUpperCase, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isBlocked, getWindowScroll, hookSetter, patch, setTimeout, legacy_isTouchEvent, nowTimestamp, getWindowHeight, getWindowWidth } from '../utils.js';\nimport { MouseInteractions, IncrementalSource, PointerTypes } from '../../../types/dist/rrweb-types.js';\nimport MutationBuffer from './mutation.js';\nimport { callbackWrapper } from './error-handler.js';\n\nconst mutationBuffers = [];\r\nfunction getEventTarget(event) {\r\n try {\r\n if ('composedPath' in event) {\r\n const path = event.composedPath();\r\n if (path.length) {\r\n return path[0];\r\n }\r\n }\r\n else if ('path' in event && event.path.length) {\r\n return event.path[0];\r\n }\r\n }\r\n catch {\r\n }\r\n return event && event.target;\r\n}\r\nfunction initMutationObserver(options, rootEl) {\r\n const mutationBuffer = new MutationBuffer();\r\n mutationBuffers.push(mutationBuffer);\r\n mutationBuffer.init(options);\r\n let mutationObserverCtor = window.MutationObserver ||\r\n window.__rrMutationObserver;\r\n const angularZoneSymbol = window?.Zone?.__symbol__?.('MutationObserver');\r\n if (angularZoneSymbol &&\r\n window[angularZoneSymbol]) {\r\n mutationObserverCtor = window[angularZoneSymbol];\r\n }\r\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\r\n if (options.onMutation && options.onMutation(mutations) === false) {\r\n return;\r\n }\r\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\r\n }));\r\n observer.observe(rootEl, {\r\n attributes: true,\r\n attributeOldValue: true,\r\n characterData: true,\r\n characterDataOldValue: true,\r\n childList: true,\r\n subtree: true,\r\n });\r\n return observer;\r\n}\r\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\r\n if (sampling.mousemove === false) {\r\n return () => {\r\n };\r\n }\r\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\r\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\r\n ? sampling.mousemoveCallback\r\n : 500;\r\n let positions = [];\r\n let timeBaseline;\r\n const wrappedCb = throttle(callbackWrapper((source) => {\r\n const totalOffset = Date.now() - timeBaseline;\r\n mousemoveCb(positions.map((p) => {\r\n p.timeOffset -= totalOffset;\r\n return p;\r\n }), source);\r\n positions = [];\r\n timeBaseline = null;\r\n }), callbackThreshold);\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n const { clientX, clientY } = legacy_isTouchEvent(evt)\r\n ? evt.changedTouches[0]\r\n : evt;\r\n if (!timeBaseline) {\r\n timeBaseline = nowTimestamp();\r\n }\r\n positions.push({\r\n x: clientX,\r\n y: clientY,\r\n id: mirror.getId(target),\r\n timeOffset: nowTimestamp() - timeBaseline,\r\n });\r\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\r\n ? IncrementalSource.Drag\r\n : evt instanceof MouseEvent\r\n ? IncrementalSource.MouseMove\r\n : IncrementalSource.TouchMove);\r\n }), threshold, {\r\n trailing: false,\r\n }));\r\n const handlers = [\r\n on('mousemove', updatePosition, doc),\r\n on('touchmove', updatePosition, doc),\r\n on('drag', updatePosition, doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n if (sampling.mouseInteraction === false) {\r\n return () => {\r\n };\r\n }\r\n const disableMap = sampling.mouseInteraction === true ||\r\n sampling.mouseInteraction === undefined\r\n ? {}\r\n : sampling.mouseInteraction;\r\n const handlers = [];\r\n let currentPointerType = null;\r\n const getHandler = (eventKey) => {\r\n return (event) => {\r\n const target = getEventTarget(event);\r\n if (isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n let pointerType = null;\r\n let thisEventKey = eventKey;\r\n if ('pointerType' in event) {\r\n switch (event.pointerType) {\r\n case 'mouse':\r\n pointerType = PointerTypes.Mouse;\r\n break;\r\n case 'touch':\r\n pointerType = PointerTypes.Touch;\r\n break;\r\n case 'pen':\r\n pointerType = PointerTypes.Pen;\r\n break;\r\n }\r\n if (pointerType === PointerTypes.Touch) {\r\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\r\n thisEventKey = 'TouchStart';\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\r\n thisEventKey = 'TouchEnd';\r\n }\r\n }\r\n else if (pointerType === PointerTypes.Pen) ;\r\n }\r\n else if (legacy_isTouchEvent(event)) {\r\n pointerType = PointerTypes.Touch;\r\n }\r\n if (pointerType !== null) {\r\n currentPointerType = pointerType;\r\n if ((thisEventKey.startsWith('Touch') &&\r\n pointerType === PointerTypes.Touch) ||\r\n (thisEventKey.startsWith('Mouse') &&\r\n pointerType === PointerTypes.Mouse)) {\r\n pointerType = null;\r\n }\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\r\n pointerType = currentPointerType;\r\n currentPointerType = null;\r\n }\r\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\r\n if (!e) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n const { clientX, clientY } = e;\r\n callbackWrapper(mouseInteractionCb)({\r\n type: MouseInteractions[thisEventKey],\r\n id,\r\n x: clientX,\r\n y: clientY,\r\n ...(pointerType !== null && { pointerType }),\r\n });\r\n };\r\n };\r\n Object.keys(MouseInteractions)\r\n .filter((key) => Number.isNaN(Number(key)) &&\r\n !key.endsWith('_Departed') &&\r\n disableMap[key] !== false)\r\n .forEach((eventKey) => {\r\n let eventName = toLowerCase(eventKey);\r\n const handler = getHandler(eventKey);\r\n if (window.PointerEvent) {\r\n switch (MouseInteractions[eventKey]) {\r\n case MouseInteractions.MouseDown:\r\n case MouseInteractions.MouseUp:\r\n eventName = eventName.replace('mouse', 'pointer');\r\n break;\r\n case MouseInteractions.TouchStart:\r\n case MouseInteractions.TouchEnd:\r\n return;\r\n }\r\n }\r\n handlers.push(on(eventName, handler, doc));\r\n });\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n if (target === doc && doc.defaultView) {\r\n const scrollLeftTop = getWindowScroll(doc.defaultView);\r\n scrollCb({\r\n id,\r\n x: scrollLeftTop.left,\r\n y: scrollLeftTop.top,\r\n });\r\n }\r\n else {\r\n scrollCb({\r\n id,\r\n x: target.scrollLeft,\r\n y: target.scrollTop,\r\n });\r\n }\r\n }), sampling.scroll || 100));\r\n return on('scroll', updatePosition, doc);\r\n}\r\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\r\n let lastH = -1;\r\n let lastW = -1;\r\n const updateDimension = callbackWrapper(throttle(callbackWrapper(() => {\r\n const height = getWindowHeight();\r\n const width = getWindowWidth();\r\n if (lastH !== height || lastW !== width) {\r\n viewportResizeCb({\r\n width: Number(width),\r\n height: Number(height),\r\n });\r\n lastH = height;\r\n lastW = width;\r\n }\r\n }), 200));\r\n return on('resize', updateDimension, win);\r\n}\r\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\r\nconst lastInputValueMap = new WeakMap();\r\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, }) {\r\n function eventHandler(event) {\r\n let target = getEventTarget(event);\r\n const userTriggered = event.isTrusted;\r\n const tagName = target && toUpperCase(target.tagName);\r\n if (tagName === 'OPTION')\r\n target = target.parentElement;\r\n if (!target ||\r\n !tagName ||\r\n INPUT_TAGS.indexOf(tagName) < 0 ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const el = target;\r\n if (el.classList.contains(ignoreClass) ||\r\n (ignoreSelector && el.matches(ignoreSelector))) {\r\n return;\r\n }\r\n const type = getInputType(target);\r\n let text = getInputValue(el, tagName, type);\r\n let isChecked = false;\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked);\r\n if (type === 'radio' || type === 'checkbox') {\r\n isChecked = target.checked;\r\n }\r\n text = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value: text,\r\n maskInputFn,\r\n });\r\n cbWithDedup(target, userTriggeredOnInput\r\n ? { text, isChecked, userTriggered }\r\n : { text, isChecked });\r\n const name = target.name;\r\n if (type === 'radio' && name && isChecked) {\r\n doc\r\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\r\n .forEach((el) => {\r\n if (el !== target) {\r\n const text = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value: getInputValue(el, tagName, type),\r\n maskInputFn,\r\n });\r\n cbWithDedup(el, userTriggeredOnInput\r\n ? { text, isChecked: !isChecked, userTriggered: false }\r\n : { text, isChecked: !isChecked });\r\n }\r\n });\r\n }\r\n }\r\n function cbWithDedup(target, v) {\r\n const lastInputValue = lastInputValueMap.get(target);\r\n if (!lastInputValue ||\r\n lastInputValue.text !== v.text ||\r\n lastInputValue.isChecked !== v.isChecked) {\r\n lastInputValueMap.set(target, v);\r\n const id = mirror.getId(target);\r\n callbackWrapper(inputCb)({\r\n ...v,\r\n id,\r\n });\r\n }\r\n }\r\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\r\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\r\n const currentWindow = doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n }\r\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\r\n const hookProperties = [\r\n [currentWindow.HTMLInputElement.prototype, 'value'],\r\n [currentWindow.HTMLInputElement.prototype, 'checked'],\r\n [currentWindow.HTMLSelectElement.prototype, 'value'],\r\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\r\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\r\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\r\n ];\r\n if (propertyDescriptor && propertyDescriptor.set) {\r\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\r\n set() {\r\n callbackWrapper(eventHandler)({\r\n target: this,\r\n isTrusted: false,\r\n });\r\n },\r\n }, false, currentWindow)));\r\n }\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction getNestedCSSRulePositions(rule) {\r\n const positions = [];\r\n function recurse(childRule, pos) {\r\n if ((hasNestedCSSRule('CSSGroupingRule') &&\r\n childRule.parentRule instanceof CSSGroupingRule) ||\r\n (hasNestedCSSRule('CSSMediaRule') &&\r\n childRule.parentRule instanceof CSSMediaRule) ||\r\n (hasNestedCSSRule('CSSSupportsRule') &&\r\n childRule.parentRule instanceof CSSSupportsRule) ||\r\n (hasNestedCSSRule('CSSConditionRule') &&\r\n childRule.parentRule instanceof CSSConditionRule)) {\r\n const rules = Array.from(childRule.parentRule.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n else if (childRule.parentStyleSheet) {\r\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n return pos;\r\n }\r\n return recurse(rule, positions);\r\n}\r\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\r\n let id, styleId;\r\n if (!sheet)\r\n return {};\r\n if (sheet.ownerNode)\r\n id = mirror.getId(sheet.ownerNode);\r\n else\r\n styleId = styleMirror.getId(sheet);\r\n return {\r\n styleId,\r\n id,\r\n };\r\n}\r\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {\r\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\r\n return () => {\r\n };\r\n }\r\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\r\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [{ rule, index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\r\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [{ index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n let replace;\r\n if (win.CSSStyleSheet.prototype.replace) {\r\n replace = win.CSSStyleSheet.prototype.replace;\r\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replace: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n let replaceSync;\r\n if (win.CSSStyleSheet.prototype.replaceSync) {\r\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\r\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replaceSync: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n const supportedNestedCSSRuleTypes = {};\r\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\r\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\r\n }\r\n else {\r\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\r\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\r\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\r\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\r\n }\r\n }\r\n const unmodifiedFunctions = {};\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n unmodifiedFunctions[typeKey] = {\r\n insertRule: type.prototype.insertRule,\r\n deleteRule: type.prototype.deleteRule,\r\n };\r\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [\r\n {\r\n rule,\r\n index: [\r\n ...getNestedCSSRulePositions(thisArg),\r\n index || 0,\r\n ],\r\n },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [\r\n { index: [...getNestedCSSRulePositions(thisArg), index] },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleSheet.prototype.insertRule = insertRule;\r\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\r\n replace && (win.CSSStyleSheet.prototype.replace = replace);\r\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\r\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\r\n });\r\n });\r\n}\r\nfunction initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {\r\n let hostId = null;\r\n if (host.nodeName === '#document')\r\n hostId = mirror.getId(host);\r\n else\r\n hostId = mirror.getId(host.host);\r\n const patchTarget = host.nodeName === '#document'\r\n ? host.defaultView?.Document\r\n : host.ownerDocument?.defaultView?.ShadowRoot;\r\n const originalPropertyDescriptor = patchTarget?.prototype\r\n ? Object.getOwnPropertyDescriptor(patchTarget?.prototype, 'adoptedStyleSheets')\r\n : undefined;\r\n if (hostId === null ||\r\n hostId === -1 ||\r\n !patchTarget ||\r\n !originalPropertyDescriptor)\r\n return () => {\r\n };\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get() {\r\n return originalPropertyDescriptor.get?.call(this);\r\n },\r\n set(sheets) {\r\n const result = originalPropertyDescriptor.set?.call(this, sheets);\r\n if (hostId !== null && hostId !== -1) {\r\n try {\r\n stylesheetManager.adoptStyleSheets(sheets, hostId);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return result;\r\n },\r\n });\r\n return callbackWrapper(() => {\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get: originalPropertyDescriptor.get,\r\n set: originalPropertyDescriptor.set,\r\n });\r\n });\r\n}\r\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\r\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\r\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property, value, priority] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return setProperty.apply(thisArg, [property, value, priority]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n set: {\r\n property,\r\n value,\r\n priority,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return removeProperty.apply(thisArg, [property]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n remove: {\r\n property,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\r\n });\r\n}\r\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, doc, }) {\r\n const handler = callbackWrapper((type) => throttle(callbackWrapper((event) => {\r\n const target = getEventTarget(event);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const { currentTime, volume, muted, playbackRate } = target;\r\n mediaInteractionCb({\r\n type,\r\n id: mirror.getId(target),\r\n currentTime,\r\n volume,\r\n muted,\r\n playbackRate,\r\n });\r\n }), sampling.media || 500));\r\n const handlers = [\r\n on('play', handler(0), doc),\r\n on('pause', handler(1), doc),\r\n on('seeked', handler(2), doc),\r\n on('volumechange', handler(3), doc),\r\n on('ratechange', handler(4), doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initFontObserver({ fontCb, doc }) {\r\n const win = doc.defaultView;\r\n if (!win) {\r\n return () => {\r\n };\r\n }\r\n const handlers = [];\r\n const fontMap = new WeakMap();\r\n const originalFontFace = win.FontFace;\r\n win.FontFace = function FontFace(family, source, descriptors) {\r\n const fontFace = new originalFontFace(family, source, descriptors);\r\n fontMap.set(fontFace, {\r\n family,\r\n buffer: typeof source !== 'string',\r\n descriptors,\r\n fontSource: typeof source === 'string'\r\n ? source\r\n : JSON.stringify(Array.from(new Uint8Array(source))),\r\n });\r\n return fontFace;\r\n };\r\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\r\n return function (fontFace) {\r\n setTimeout(callbackWrapper(() => {\r\n const p = fontMap.get(fontFace);\r\n if (p) {\r\n fontCb(p);\r\n fontMap.delete(fontFace);\r\n }\r\n }), 0);\r\n return original.apply(this, [fontFace]);\r\n };\r\n });\r\n handlers.push(() => {\r\n win.FontFace = originalFontFace;\r\n });\r\n handlers.push(restoreHandler);\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initSelectionObserver(param) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, selectionCb, } = param;\r\n let collapsed = true;\r\n const updateSelection = callbackWrapper(() => {\r\n const selection = doc.getSelection();\r\n if (!selection || (collapsed && selection?.isCollapsed))\r\n return;\r\n collapsed = selection.isCollapsed || false;\r\n const ranges = [];\r\n const count = selection.rangeCount || 0;\r\n for (let i = 0; i < count; i++) {\r\n const range = selection.getRangeAt(i);\r\n const { startContainer, startOffset, endContainer, endOffset } = range;\r\n const blocked = isBlocked(startContainer, blockClass, blockSelector, unblockSelector, true) ||\r\n isBlocked(endContainer, blockClass, blockSelector, unblockSelector, true);\r\n if (blocked)\r\n continue;\r\n ranges.push({\r\n start: mirror.getId(startContainer),\r\n startOffset,\r\n end: mirror.getId(endContainer),\r\n endOffset,\r\n });\r\n }\r\n selectionCb({ ranges });\r\n });\r\n updateSelection();\r\n return on('selectionchange', updateSelection);\r\n}\r\nfunction initCustomElementObserver({ doc, customElementCb, }) {\r\n const win = doc.defaultView;\r\n if (!win || !win.customElements)\r\n return () => { };\r\n const restoreHandler = patch(win.customElements, 'define', function (original) {\r\n return function (name, constructor, options) {\r\n try {\r\n customElementCb({\r\n define: {\r\n name,\r\n },\r\n });\r\n }\r\n catch (e) {\r\n }\r\n return original.apply(this, [name, constructor, options]);\r\n };\r\n });\r\n return restoreHandler;\r\n}\r\nfunction initObservers(o, _hooks = {}) {\r\n const currentWindow = o.doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n };\r\n }\r\n const mutationObserver = initMutationObserver(o, o.doc);\r\n const mousemoveHandler = initMoveObserver(o);\r\n const mouseInteractionHandler = initMouseInteractionObserver(o);\r\n const scrollHandler = initScrollObserver(o);\r\n const viewportResizeHandler = initViewportResizeObserver(o, {\r\n win: currentWindow,\r\n });\r\n const inputHandler = initInputObserver(o);\r\n const mediaInteractionHandler = initMediaInteractionObserver(o);\r\n const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\r\n const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\r\n const styleDeclarationObserver = initStyleDeclarationObserver(o, {\r\n win: currentWindow,\r\n });\r\n const fontObserver = o.collectFonts\r\n ? initFontObserver(o)\r\n : () => {\r\n };\r\n const selectionObserver = initSelectionObserver(o);\r\n const customElementObserver = initCustomElementObserver(o);\r\n const pluginHandlers = [];\r\n for (const plugin of o.plugins) {\r\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\r\n }\r\n return callbackWrapper(() => {\r\n mutationBuffers.forEach((b) => b.reset());\r\n mutationObserver.disconnect();\r\n mousemoveHandler();\r\n mouseInteractionHandler();\r\n scrollHandler();\r\n viewportResizeHandler();\r\n inputHandler();\r\n mediaInteractionHandler();\r\n styleSheetObserver();\r\n adoptedStyleSheetObserver();\r\n styleDeclarationObserver();\r\n fontObserver();\r\n selectionObserver();\r\n customElementObserver();\r\n pluginHandlers.forEach((h) => h());\r\n });\r\n}\r\nfunction hasNestedCSSRule(prop) {\r\n return typeof window[prop] !== 'undefined';\r\n}\r\nfunction canMonkeyPatchNestedCSSRule(prop) {\r\n return Boolean(typeof window[prop] !== 'undefined' &&\r\n window[prop].prototype &&\r\n 'insertRule' in window[prop].prototype &&\r\n 'deleteRule' in window[prop].prototype);\r\n}\n\nexport { INPUT_TAGS, initAdoptedStyleSheetObserver, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n","class CrossOriginIframeMirror {\r\n constructor(generateIdFn) {\r\n this.generateIdFn = generateIdFn;\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n }\r\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\r\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\r\n let id = idToRemoteIdMap.get(remoteId);\r\n if (!id) {\r\n id = this.generateIdFn();\r\n idToRemoteIdMap.set(remoteId, id);\r\n remoteIdToIdMap.set(id, remoteId);\r\n }\r\n return id;\r\n }\r\n getIds(iframe, remoteId) {\r\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\r\n }\r\n getRemoteId(iframe, id, map) {\r\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\r\n if (typeof id !== 'number')\r\n return id;\r\n const remoteId = remoteIdToIdMap.get(id);\r\n if (!remoteId)\r\n return -1;\r\n return remoteId;\r\n }\r\n getRemoteIds(iframe, ids) {\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\r\n }\r\n reset(iframe) {\r\n if (!iframe) {\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n return;\r\n }\r\n this.iframeIdToRemoteIdMap.delete(iframe);\r\n this.iframeRemoteIdToIdMap.delete(iframe);\r\n }\r\n getIdToRemoteIdMap(iframe) {\r\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\r\n if (!idToRemoteIdMap) {\r\n idToRemoteIdMap = new Map();\r\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\r\n }\r\n return idToRemoteIdMap;\r\n }\r\n getRemoteIdToIdMap(iframe) {\r\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\r\n if (!remoteIdToIdMap) {\r\n remoteIdToIdMap = new Map();\r\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\r\n }\r\n return remoteIdToIdMap;\r\n }\r\n}\n\nexport { CrossOriginIframeMirror as default };\n","import { genId, NodeType } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport CrossOriginIframeMirror from './cross-origin-iframe-mirror.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\n\nclass IframeManagerNoop {\r\n constructor() {\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n }\r\n addIframe() {\r\n }\r\n addLoadListener() {\r\n }\r\n attachIframe() {\r\n }\r\n}\r\nclass IframeManager {\r\n constructor(options) {\r\n this.iframes = new WeakMap();\r\n this.crossOriginIframeMap = new WeakMap();\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n this.mutationCb = options.mutationCb;\r\n this.wrappedEmit = options.wrappedEmit;\r\n this.stylesheetManager = options.stylesheetManager;\r\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\r\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\r\n this.mirror = options.mirror;\r\n if (this.recordCrossOriginIframes) {\r\n window.addEventListener('message', this.handleMessage.bind(this));\r\n }\r\n }\r\n addIframe(iframeEl) {\r\n this.iframes.set(iframeEl, true);\r\n if (iframeEl.contentWindow)\r\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\r\n }\r\n addLoadListener(cb) {\r\n this.loadListener = cb;\r\n }\r\n attachIframe(iframeEl, childSn) {\r\n this.mutationCb({\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: childSn,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n });\r\n this.loadListener?.(iframeEl);\r\n if (iframeEl.contentDocument &&\r\n iframeEl.contentDocument.adoptedStyleSheets &&\r\n iframeEl.contentDocument.adoptedStyleSheets.length > 0)\r\n this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));\r\n }\r\n handleMessage(message) {\r\n const crossOriginMessageEvent = message;\r\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\r\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\r\n return;\r\n const iframeSourceWindow = message.source;\r\n if (!iframeSourceWindow)\r\n return;\r\n const iframeEl = this.crossOriginIframeMap.get(message.source);\r\n if (!iframeEl)\r\n return;\r\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\r\n if (transformedEvent)\r\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\r\n }\r\n transformCrossOriginEvent(iframeEl, e) {\r\n switch (e.type) {\r\n case EventType.FullSnapshot: {\r\n this.crossOriginIframeMirror.reset(iframeEl);\r\n this.crossOriginIframeStyleMirror.reset(iframeEl);\r\n this.replaceIdOnNode(e.data.node, iframeEl);\r\n const rootId = e.data.node.id;\r\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\r\n this.patchRootIdOnNode(e.data.node, rootId);\r\n return {\r\n timestamp: e.timestamp,\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: e.data.node,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n },\r\n };\r\n }\r\n case EventType.Meta:\r\n case EventType.Load:\r\n case EventType.DomContentLoaded: {\r\n return false;\r\n }\r\n case EventType.Plugin: {\r\n return e;\r\n }\r\n case EventType.Custom: {\r\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\r\n return e;\r\n }\r\n case EventType.IncrementalSnapshot: {\r\n switch (e.data.source) {\r\n case IncrementalSource.Mutation: {\r\n e.data.adds.forEach((n) => {\r\n this.replaceIds(n, iframeEl, [\r\n 'parentId',\r\n 'nextId',\r\n 'previousId',\r\n ]);\r\n this.replaceIdOnNode(n.node, iframeEl);\r\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\r\n rootId && this.patchRootIdOnNode(n.node, rootId);\r\n });\r\n e.data.removes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\r\n });\r\n e.data.attributes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n e.data.texts.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.Drag:\r\n case IncrementalSource.TouchMove:\r\n case IncrementalSource.MouseMove: {\r\n e.data.positions.forEach((p) => {\r\n this.replaceIds(p, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.ViewportResize: {\r\n return false;\r\n }\r\n case IncrementalSource.MediaInteraction:\r\n case IncrementalSource.MouseInteraction:\r\n case IncrementalSource.Scroll:\r\n case IncrementalSource.CanvasMutation:\r\n case IncrementalSource.Input: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n return e;\r\n }\r\n case IncrementalSource.StyleSheetRule:\r\n case IncrementalSource.StyleDeclaration: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\r\n return e;\r\n }\r\n case IncrementalSource.Font: {\r\n return e;\r\n }\r\n case IncrementalSource.Selection: {\r\n e.data.ranges.forEach((range) => {\r\n this.replaceIds(range, iframeEl, ['start', 'end']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.AdoptedStyleSheet: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\r\n e.data.styles?.forEach((style) => {\r\n this.replaceStyleIds(style, iframeEl, ['styleId']);\r\n });\r\n return e;\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n replace(iframeMirror, obj, iframeEl, keys) {\r\n for (const key of keys) {\r\n if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')\r\n continue;\r\n if (Array.isArray(obj[key])) {\r\n obj[key] = iframeMirror.getIds(iframeEl, obj[key]);\r\n }\r\n else {\r\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\r\n }\r\n }\r\n return obj;\r\n }\r\n replaceIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\r\n }\r\n replaceStyleIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\r\n }\r\n replaceIdOnNode(node, iframeEl) {\r\n this.replaceIds(node, iframeEl, ['id', 'rootId']);\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.replaceIdOnNode(child, iframeEl);\r\n });\r\n }\r\n }\r\n patchRootIdOnNode(node, rootId) {\r\n if (node.type !== NodeType.Document && !node.rootId)\r\n node.rootId = rootId;\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.patchRootIdOnNode(child, rootId);\r\n });\r\n }\r\n }\r\n}\n\nexport { IframeManager, IframeManagerNoop };\n","import { createMirror, snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, on, nowTimestamp, getWindowWidth, getWindowHeight, getWindowScroll, isSerializedIframe, isSerializedStylesheet, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\nimport { IframeManagerNoop, IframeManager } from './iframe-manager.js';\nimport { ShadowDomManagerNoop, ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManagerNoop } from './observers/canvas/canvas-manager.js';\nexport { CanvasManager } from './observers/canvas/canvas-manager.js';\nimport { StylesheetManager } from './stylesheet-manager.js';\nimport ProcessedNodeManager from './processed-node-manager.js';\nimport { callbackWrapper, unregisterErrorHandler, registerErrorHandler } from './error-handler.js';\n\nlet wrappedEmit;\r\nlet _wrappedEmit;\r\nlet _takeFullSnapshot;\r\nconst mirror = createMirror();\r\nfunction record(options = {}) {\r\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\r\n ? options.recordAfter\r\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, onMutation, getCanvasManager, } = options;\r\n registerErrorHandler(errorHandler);\r\n const inEmittingFrame = recordCrossOriginIframes\r\n ? window.parent === window\r\n : true;\r\n let passEmitsToParent = false;\r\n if (!inEmittingFrame) {\r\n try {\r\n if (window.parent.document) {\r\n passEmitsToParent = false;\r\n }\r\n }\r\n catch (e) {\r\n passEmitsToParent = true;\r\n }\r\n }\r\n if (inEmittingFrame && !emit) {\r\n throw new Error('emit function is required');\r\n }\r\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\r\n sampling.mousemove = mousemoveWait;\r\n }\r\n mirror.reset();\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n radio: true,\r\n checkbox: true,\r\n }\r\n : _maskInputOptions !== undefined\r\n ? _maskInputOptions\r\n : {};\r\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\r\n ? {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaVerification: true,\r\n headMetaAuthorship: _slimDOMOptions === 'all',\r\n headMetaDescKeywords: _slimDOMOptions === 'all',\r\n }\r\n : _slimDOMOptions\r\n ? _slimDOMOptions\r\n : {};\r\n polyfill();\r\n let lastFullSnapshotEvent;\r\n let incrementalSnapshotCount = 0;\r\n const eventProcessor = (e) => {\r\n for (const plugin of plugins || []) {\r\n if (plugin.eventProcessor) {\r\n e = plugin.eventProcessor(e);\r\n }\r\n }\r\n if (packFn &&\r\n !passEmitsToParent) {\r\n e = packFn(e);\r\n }\r\n return e;\r\n };\r\n wrappedEmit = (r, isCheckout) => {\r\n const e = r;\r\n e.timestamp = nowTimestamp();\r\n if (mutationBuffers[0]?.isFrozen() &&\r\n e.type !== EventType.FullSnapshot &&\r\n !(e.type === EventType.IncrementalSnapshot &&\r\n e.data.source === IncrementalSource.Mutation)) {\r\n mutationBuffers.forEach((buf) => buf.unfreeze());\r\n }\r\n if (inEmittingFrame) {\r\n emit?.(eventProcessor(e), isCheckout);\r\n }\r\n else if (passEmitsToParent) {\r\n const message = {\r\n type: 'rrweb',\r\n event: eventProcessor(e),\r\n origin: window.location.origin,\r\n isCheckout,\r\n };\r\n window.parent.postMessage(message, '*');\r\n }\r\n if (e.type === EventType.FullSnapshot) {\r\n lastFullSnapshotEvent = e;\r\n incrementalSnapshotCount = 0;\r\n }\r\n else if (e.type === EventType.IncrementalSnapshot) {\r\n if (e.data.source === IncrementalSource.Mutation &&\r\n e.data.isAttachIframe) {\r\n return;\r\n }\r\n incrementalSnapshotCount++;\r\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\r\n const exceedTime = checkoutEveryNms &&\r\n lastFullSnapshotEvent &&\r\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\r\n if (exceedCount || exceedTime) {\r\n takeFullSnapshot(true);\r\n }\r\n }\r\n };\r\n _wrappedEmit = wrappedEmit;\r\n const wrappedMutationEmit = (m) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n ...m,\r\n },\r\n });\r\n };\r\n const wrappedScrollEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Scroll,\r\n ...p,\r\n },\r\n });\r\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n });\r\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.AdoptedStyleSheet,\r\n ...a,\r\n },\r\n });\r\n const stylesheetManager = new StylesheetManager({\r\n mutationCb: wrappedMutationEmit,\r\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\r\n });\r\n const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === 'boolean' && __RRWEB_EXCLUDE_IFRAME__\r\n ? new IframeManagerNoop()\r\n : new IframeManager({\r\n mirror,\r\n mutationCb: wrappedMutationEmit,\r\n stylesheetManager: stylesheetManager,\r\n recordCrossOriginIframes,\r\n wrappedEmit,\r\n });\r\n for (const plugin of plugins || []) {\r\n if (plugin.getMirror)\r\n plugin.getMirror({\r\n nodeMirror: mirror,\r\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\r\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,\r\n });\r\n }\r\n const processedNodeManager = new ProcessedNodeManager();\r\n const canvasManager = _getCanvasManager(getCanvasManager, {\r\n mirror,\r\n win: window,\r\n mutationCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n }),\r\n recordCanvas,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maxCanvasSize,\r\n sampling: sampling['canvas'],\r\n dataURLOptions,\r\n errorHandler,\r\n });\r\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === 'boolean' &&\r\n __RRWEB_EXCLUDE_SHADOW_DOM__\r\n ? new ShadowDomManagerNoop()\r\n : new ShadowDomManager({\r\n mutationCb: wrappedMutationEmit,\r\n scrollCb: wrappedScrollEmit,\r\n bypassOptions: {\r\n onMutation,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n dataURLOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n recordCanvas,\r\n inlineImages,\r\n sampling,\r\n slimDOMOptions,\r\n iframeManager,\r\n stylesheetManager,\r\n canvasManager,\r\n keepIframeSrcFn,\r\n processedNodeManager,\r\n },\r\n mirror,\r\n });\r\n const takeFullSnapshot = (isCheckout = false) => {\r\n wrappedEmit({\r\n type: EventType.Meta,\r\n data: {\r\n href: window.location.href,\r\n width: getWindowWidth(),\r\n height: getWindowHeight(),\r\n },\r\n }, isCheckout);\r\n stylesheetManager.reset();\r\n shadowDomManager.init();\r\n mutationBuffers.forEach((buf) => buf.lock());\r\n const node = snapshot(document, {\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskAllInputs: maskInputOptions,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n slimDOM: slimDOMOptions,\r\n dataURLOptions,\r\n recordCanvas,\r\n inlineImages,\r\n onSerialize: (n) => {\r\n if (isSerializedIframe(n, mirror)) {\r\n iframeManager.addIframe(n);\r\n }\r\n if (isSerializedStylesheet(n, mirror)) {\r\n stylesheetManager.trackLinkElement(n);\r\n }\r\n if (hasShadowRoot(n)) {\r\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n iframeManager.attachIframe(iframe, childSn);\r\n shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (linkEl, childSn) => {\r\n stylesheetManager.attachLinkElement(linkEl, childSn);\r\n },\r\n keepIframeSrcFn,\r\n });\r\n if (!node) {\r\n return console.warn('Failed to snapshot the document');\r\n }\r\n wrappedEmit({\r\n type: EventType.FullSnapshot,\r\n data: {\r\n node,\r\n initialOffset: getWindowScroll(window),\r\n },\r\n });\r\n mutationBuffers.forEach((buf) => buf.unlock());\r\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\r\n stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));\r\n };\r\n _takeFullSnapshot = takeFullSnapshot;\r\n try {\r\n const handlers = [];\r\n const observe = (doc) => {\r\n return callbackWrapper(initObservers)({\r\n onMutation,\r\n mutationCb: wrappedMutationEmit,\r\n mousemoveCb: (positions, source) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source,\r\n positions,\r\n },\r\n }),\r\n mouseInteractionCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MouseInteraction,\r\n ...d,\r\n },\r\n }),\r\n scrollCb: wrappedScrollEmit,\r\n viewportResizeCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.ViewportResize,\r\n ...d,\r\n },\r\n }),\r\n inputCb: (v) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Input,\r\n ...v,\r\n },\r\n }),\r\n mediaInteractionCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MediaInteraction,\r\n ...p,\r\n },\r\n }),\r\n styleSheetRuleCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleSheetRule,\r\n ...r,\r\n },\r\n }),\r\n styleDeclarationCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleDeclaration,\r\n ...r,\r\n },\r\n }),\r\n canvasMutationCb: wrappedCanvasMutationEmit,\r\n fontCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Font,\r\n ...p,\r\n },\r\n }),\r\n selectionCb: (p) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Selection,\r\n ...p,\r\n },\r\n });\r\n },\r\n customElementCb: (c) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CustomElement,\r\n ...c,\r\n },\r\n });\r\n },\r\n blockClass,\r\n ignoreClass,\r\n ignoreSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskInputOptions,\r\n inlineStylesheet,\r\n sampling,\r\n recordCanvas,\r\n inlineImages,\r\n userTriggeredOnInput,\r\n collectFonts,\r\n doc,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n keepIframeSrcFn,\r\n blockSelector,\r\n unblockSelector,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n mirror,\r\n iframeManager,\r\n stylesheetManager,\r\n shadowDomManager,\r\n processedNodeManager,\r\n canvasManager,\r\n ignoreCSSAttributes,\r\n plugins: plugins\r\n ?.filter((p) => p.observer)\r\n ?.map((p) => ({\r\n observer: p.observer,\r\n options: p.options,\r\n callback: (payload) => wrappedEmit({\r\n type: EventType.Plugin,\r\n data: {\r\n plugin: p.name,\r\n payload,\r\n },\r\n }),\r\n })) || [],\r\n }, {});\r\n };\r\n iframeManager.addLoadListener((iframeEl) => {\r\n try {\r\n handlers.push(observe(iframeEl.contentDocument));\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n });\r\n const init = () => {\r\n takeFullSnapshot();\r\n handlers.push(observe(document));\r\n };\r\n if (document.readyState === 'interactive' ||\r\n document.readyState === 'complete') {\r\n init();\r\n }\r\n else {\r\n handlers.push(on('DOMContentLoaded', () => {\r\n wrappedEmit({\r\n type: EventType.DomContentLoaded,\r\n data: {},\r\n });\r\n if (recordAfter === 'DOMContentLoaded')\r\n init();\r\n }));\r\n handlers.push(on('load', () => {\r\n wrappedEmit({\r\n type: EventType.Load,\r\n data: {},\r\n });\r\n if (recordAfter === 'load')\r\n init();\r\n }, window));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n processedNodeManager.destroy();\r\n _takeFullSnapshot = undefined;\r\n unregisterErrorHandler();\r\n };\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n}\r\nfunction addCustomEvent(tag, payload) {\r\n if (!_wrappedEmit) {\r\n throw new Error('please add custom event after start recording');\r\n }\r\n wrappedEmit({\r\n type: EventType.Custom,\r\n data: {\r\n tag,\r\n payload,\r\n },\r\n });\r\n}\r\nfunction freezePage() {\r\n mutationBuffers.forEach((buf) => buf.freeze());\r\n}\r\nfunction takeFullSnapshot(isCheckout) {\r\n if (!_takeFullSnapshot) {\r\n throw new Error('please take full snapshot after start recording');\r\n }\r\n _takeFullSnapshot(isCheckout);\r\n}\r\nrecord.mirror = mirror;\r\nrecord.takeFullSnapshot = takeFullSnapshot;\r\nfunction _getCanvasManager(getCanvasManagerFn, options) {\r\n try {\r\n return getCanvasManagerFn\r\n ? getCanvasManagerFn(options)\r\n : new CanvasManagerNoop();\r\n }\r\n catch {\r\n console.warn('Unable to initialize CanvasManager');\r\n return new CanvasManagerNoop();\r\n }\r\n}\n\nexport { addCustomEvent, record as default, freezePage, mirror, takeFullSnapshot };\n","import { initMutationObserver, initScrollObserver, initAdoptedStyleSheetObserver } from './observer.js';\nimport { setTimeout, patch, inDom } from '../utils.js';\nimport { isNativeShadowDom } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nclass ShadowDomManagerNoop {\r\n init() {\r\n }\r\n addShadowRoot() {\r\n }\r\n observeAttachShadow() {\r\n }\r\n reset() {\r\n }\r\n}\r\nclass ShadowDomManager {\r\n constructor(options) {\r\n this.shadowDoms = new WeakSet();\r\n this.restoreHandlers = [];\r\n this.mutationCb = options.mutationCb;\r\n this.scrollCb = options.scrollCb;\r\n this.bypassOptions = options.bypassOptions;\r\n this.mirror = options.mirror;\r\n this.init();\r\n }\r\n init() {\r\n this.reset();\r\n this.patchAttachShadow(Element, document);\r\n }\r\n addShadowRoot(shadowRoot, doc) {\r\n if (!isNativeShadowDom(shadowRoot))\r\n return;\r\n if (this.shadowDoms.has(shadowRoot))\r\n return;\r\n this.shadowDoms.add(shadowRoot);\r\n const observer = initMutationObserver({\r\n ...this.bypassOptions,\r\n doc,\r\n mutationCb: this.mutationCb,\r\n mirror: this.mirror,\r\n shadowDomManager: this,\r\n }, shadowRoot);\r\n this.restoreHandlers.push(() => observer.disconnect());\r\n this.restoreHandlers.push(initScrollObserver({\r\n ...this.bypassOptions,\r\n scrollCb: this.scrollCb,\r\n doc: shadowRoot,\r\n mirror: this.mirror,\r\n }));\r\n setTimeout(() => {\r\n if (shadowRoot.adoptedStyleSheets &&\r\n shadowRoot.adoptedStyleSheets.length > 0)\r\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\r\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\r\n mirror: this.mirror,\r\n stylesheetManager: this.bypassOptions.stylesheetManager,\r\n }, shadowRoot));\r\n }, 0);\r\n }\r\n observeAttachShadow(iframeElement) {\r\n if (!iframeElement.contentWindow || !iframeElement.contentDocument)\r\n return;\r\n this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);\r\n }\r\n patchAttachShadow(element, doc) {\r\n const manager = this;\r\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {\r\n return function (option) {\r\n const shadowRoot = original.call(this, option);\r\n if (this.shadowRoot && inDom(this))\r\n manager.addShadowRoot(this.shadowRoot, doc);\r\n return shadowRoot;\r\n };\r\n }));\r\n }\r\n reset() {\r\n this.restoreHandlers.forEach((handler) => {\r\n try {\r\n handler();\r\n }\r\n catch (e) {\r\n }\r\n });\r\n this.restoreHandlers = [];\r\n this.shadowDoms = new WeakSet();\r\n }\r\n}\n\nexport { ShadowDomManager, ShadowDomManagerNoop };\n","import { onRequestAnimationFrame, isBlocked } from '../../../utils.js';\nimport { CanvasContext } from '../../../../../types/dist/rrweb-types.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\nimport { getImageBitmapDataUrlWorkerURL as t } from '../../../../../rrweb-worker/es/rrweb-worker/index.js';\nimport { callbackWrapper, registerErrorHandler } from '../../error-handler.js';\n\nclass CanvasManagerNoop {\r\n reset() {\r\n }\r\n freeze() {\r\n }\r\n unfreeze() {\r\n }\r\n lock() {\r\n }\r\n unlock() {\r\n }\r\n snapshot() {\r\n }\r\n}\r\nclass CanvasManager {\r\n reset() {\r\n this.pendingCanvasMutations.clear();\r\n this.resetObservers && this.resetObservers();\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n }\r\n lock() {\r\n this.locked = true;\r\n }\r\n unlock() {\r\n this.locked = false;\r\n }\r\n constructor(options) {\r\n this.pendingCanvasMutations = new Map();\r\n this.rafStamps = { latestId: 0, invokeId: null };\r\n this.frozen = false;\r\n this.locked = false;\r\n this.processMutation = (target, mutation) => {\r\n const newFrame = this.rafStamps.invokeId &&\r\n this.rafStamps.latestId !== this.rafStamps.invokeId;\r\n if (newFrame || !this.rafStamps.invokeId)\r\n this.rafStamps.invokeId = this.rafStamps.latestId;\r\n if (!this.pendingCanvasMutations.has(target)) {\r\n this.pendingCanvasMutations.set(target, []);\r\n }\r\n this.pendingCanvasMutations.get(target).push(mutation);\r\n };\r\n const { sampling = 'all', win, blockClass, blockSelector, unblockSelector, maxCanvasSize, recordCanvas, dataURLOptions, errorHandler, } = options;\r\n this.mutationCb = options.mutationCb;\r\n this.mirror = options.mirror;\r\n this.options = options;\r\n if (errorHandler) {\r\n registerErrorHandler(errorHandler);\r\n }\r\n if (options.enableManualSnapshot) {\r\n return;\r\n }\r\n callbackWrapper(() => {\r\n if (recordCanvas && sampling === 'all')\r\n this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector);\r\n if (recordCanvas && typeof sampling === 'number')\r\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, {\r\n dataURLOptions,\r\n });\r\n })();\r\n }\r\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options) {\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true);\r\n const rafId = this.takeSnapshot(false, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options.dataURLOptions);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) {\r\n this.startRAFTimestamping();\r\n this.startPendingCanvasMutationFlusher();\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false);\r\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector);\r\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n canvas2DReset();\r\n canvasWebGL1and2Reset();\r\n };\r\n }\r\n snapshot(canvasElement) {\r\n const { options } = this;\r\n const rafId = this.takeSnapshot(true, options.sampling === 'all' ? 2 : options.sampling || 2, options.win, options.blockClass, options.blockSelector, options.unblockSelector, options.maxCanvasSize, options.dataURLOptions, canvasElement);\r\n this.resetObservers = () => {\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n takeSnapshot(isManualSnapshot, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, dataURLOptions, canvasElement) {\r\n const snapshotInProgressMap = new Map();\r\n const worker = new Worker(t());\r\n worker.onmessage = (e) => {\r\n const data = e.data;\r\n const { id } = data;\r\n snapshotInProgressMap.set(id, false);\r\n if (!('base64' in data))\r\n return;\r\n const { base64, type, width, height } = data;\r\n this.mutationCb({\r\n id,\r\n type: CanvasContext['2D'],\r\n commands: [\r\n {\r\n property: 'clearRect',\r\n args: [0, 0, width, height],\r\n },\r\n {\r\n property: 'drawImage',\r\n args: [\r\n {\r\n rr_type: 'ImageBitmap',\r\n args: [\r\n {\r\n rr_type: 'Blob',\r\n data: [{ rr_type: 'ArrayBuffer', base64 }],\r\n type,\r\n },\r\n ],\r\n },\r\n 0,\r\n 0,\r\n width,\r\n height,\r\n ],\r\n },\r\n ],\r\n });\r\n };\r\n const timeBetweenSnapshots = 1000 / fps;\r\n let lastSnapshotTime = 0;\r\n let rafId;\r\n const getCanvas = (canvasElement) => {\r\n if (canvasElement) {\r\n return [canvasElement];\r\n }\r\n const matchedCanvas = [];\r\n win.document.querySelectorAll('canvas').forEach((canvas) => {\r\n if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector, true)) {\r\n matchedCanvas.push(canvas);\r\n }\r\n });\r\n return matchedCanvas;\r\n };\r\n const takeCanvasSnapshots = (timestamp) => {\r\n if (lastSnapshotTime &&\r\n timestamp - lastSnapshotTime < timeBetweenSnapshots) {\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return;\r\n }\r\n lastSnapshotTime = timestamp;\r\n getCanvas(canvasElement).forEach((canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n if (snapshotInProgressMap.get(id))\r\n return;\r\n if (!canvas.width || !canvas.height)\r\n return;\r\n snapshotInProgressMap.set(id, true);\r\n if (!isManualSnapshot &&\r\n ['webgl', 'webgl2'].includes(canvas.__context)) {\r\n const context = canvas.getContext(canvas.__context);\r\n if (context?.getContextAttributes()?.preserveDrawingBuffer === false) {\r\n context.clear(context.COLOR_BUFFER_BIT);\r\n }\r\n }\r\n createImageBitmap(canvas)\r\n .then((bitmap) => {\r\n worker.postMessage({\r\n id,\r\n bitmap,\r\n width: canvas.width,\r\n height: canvas.height,\r\n dataURLOptions,\r\n maxCanvasSize,\r\n }, [bitmap]);\r\n })\r\n .catch((error) => {\r\n callbackWrapper(() => {\r\n throw error;\r\n })();\r\n });\r\n });\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n };\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return rafId;\r\n }\r\n startPendingCanvasMutationFlusher() {\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n startRAFTimestamping() {\r\n const setLatestRAFTimestamp = (timestamp) => {\r\n this.rafStamps.latestId = timestamp;\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n };\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n }\r\n flushPendingCanvasMutations() {\r\n this.pendingCanvasMutations.forEach((values, canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n this.flushPendingCanvasMutationFor(canvas, id);\r\n });\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n flushPendingCanvasMutationFor(canvas, id) {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\r\n if (!valuesWithType || id === -1)\r\n return;\r\n const values = valuesWithType.map((value) => {\r\n const { type, ...rest } = value;\r\n return rest;\r\n });\r\n const { type } = valuesWithType[0];\r\n this.mutationCb({ id, type, commands: values });\r\n this.pendingCanvasMutations.delete(canvas);\r\n }\r\n}\n\nexport { CanvasManager, CanvasManagerNoop };\n","import { stringifyRule } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { StyleSheetMirror } from '../utils.js';\n\nclass StylesheetManager {\r\n constructor(options) {\r\n this.trackedLinkElements = new WeakSet();\r\n this.styleMirror = new StyleSheetMirror();\r\n this.mutationCb = options.mutationCb;\r\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\r\n }\r\n attachLinkElement(linkEl, childSn) {\r\n if ('_cssText' in childSn.attributes)\r\n this.mutationCb({\r\n adds: [],\r\n removes: [],\r\n texts: [],\r\n attributes: [\r\n {\r\n id: childSn.id,\r\n attributes: childSn\r\n .attributes,\r\n },\r\n ],\r\n });\r\n this.trackLinkElement(linkEl);\r\n }\r\n trackLinkElement(linkEl) {\r\n if (this.trackedLinkElements.has(linkEl))\r\n return;\r\n this.trackedLinkElements.add(linkEl);\r\n this.trackStylesheetInLinkElement(linkEl);\r\n }\r\n adoptStyleSheets(sheets, hostId) {\r\n if (sheets.length === 0)\r\n return;\r\n const adoptedStyleSheetData = {\r\n id: hostId,\r\n styleIds: [],\r\n };\r\n const styles = [];\r\n for (const sheet of sheets) {\r\n let styleId;\r\n if (!this.styleMirror.has(sheet)) {\r\n styleId = this.styleMirror.add(sheet);\r\n styles.push({\r\n styleId,\r\n rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\r\n rule: stringifyRule(r),\r\n index,\r\n })),\r\n });\r\n }\r\n else\r\n styleId = this.styleMirror.getId(sheet);\r\n adoptedStyleSheetData.styleIds.push(styleId);\r\n }\r\n if (styles.length > 0)\r\n adoptedStyleSheetData.styles = styles;\r\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\r\n }\r\n reset() {\r\n this.styleMirror.reset();\r\n this.trackedLinkElements = new WeakSet();\r\n }\r\n trackStylesheetInLinkElement(linkEl) {\r\n }\r\n}\n\nexport { StylesheetManager };\n","import { onRequestAnimationFrame } from '../utils.js';\n\nclass ProcessedNodeManager {\r\n constructor() {\r\n this.nodeMap = new WeakMap();\r\n this.loop = true;\r\n this.periodicallyClear();\r\n }\r\n periodicallyClear() {\r\n onRequestAnimationFrame(() => {\r\n this.clear();\r\n if (this.loop)\r\n this.periodicallyClear();\r\n });\r\n }\r\n inOtherBuffer(node, thisBuffer) {\r\n const buffers = this.nodeMap.get(node);\r\n return (buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer));\r\n }\r\n add(node, buffer) {\r\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\r\n }\r\n clear() {\r\n this.nodeMap = new WeakMap();\r\n }\r\n destroy() {\r\n this.loop = false;\r\n }\r\n}\n\nexport { ProcessedNodeManager as default };\n","type ClassOption = string | RegExp;\n\n/** Duplicate this from @sentry-internal/rrweb so we can export this as well. */\nexport const ReplayEventTypeDomContentLoaded = 0;\nexport const ReplayEventTypeLoad = 1;\nexport const ReplayEventTypeFullSnapshot = 2;\nexport const ReplayEventTypeIncrementalSnapshot = 3;\nexport const ReplayEventTypeMeta = 4;\nexport const ReplayEventTypeCustom = 5;\nexport const ReplayEventTypePlugin = 6;\n\nexport type ReplayEventType =\n | typeof ReplayEventTypeDomContentLoaded\n | typeof ReplayEventTypeLoad\n | typeof ReplayEventTypeFullSnapshot\n | typeof ReplayEventTypeIncrementalSnapshot\n | typeof ReplayEventTypeMeta\n | typeof ReplayEventTypeCustom\n | typeof ReplayEventTypePlugin;\n\n/**\n * This is a partial copy of rrweb's eventWithTime type which only contains the properties\n * we specifcally need in the SDK.\n */\nexport type ReplayEventWithTime = {\n type: ReplayEventType;\n data: unknown;\n timestamp: number;\n delay?: number;\n};\n\n/**\n * This is a partial copy of rrweb's recording options which only contains the properties\n * we specifically us in the SDK. Users can specify additional properties, hence we add the\n * Record union type.\n */\nexport type RrwebRecordOptions = {\n maskAllText?: boolean;\n maskAllInputs?: boolean;\n blockClass?: ClassOption;\n ignoreClass?: string;\n maskTextClass?: ClassOption;\n maskTextSelector?: string;\n blockSelector?: string;\n maskInputOptions?: Record;\n} & Record;\n\nexport interface CanvasManagerInterface {\n reset(): void;\n freeze(): void;\n unfreeze(): void;\n lock(): void;\n unlock(): void;\n snapshot(): void;\n}\n\nexport interface CanvasManagerOptions {\n recordCanvas: boolean;\n enableManualSnapshot?: boolean;\n blockClass: string | RegExp;\n blockSelector: string | null;\n unblockSelector: string | null;\n sampling?: 'all' | number;\n dataURLOptions: Partial<{\n type: string;\n quality: number;\n }>;\n mutationCb: (p: any) => void;\n win: typeof globalThis & Window;\n mirror: any;\n}\n","/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nexport function timestampToMs(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n\n/**\n * Converts a timestamp to s, if it was in ms, or keeps it as s.\n */\nexport function timestampToS(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../../types';\n\n/**\n * Add a breadcrumb event to replay.\n */\nexport function addBreadcrumbEvent(replay: ReplayContainer, breadcrumb: Breadcrumb): void {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category as string)) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1_000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n","import type { INode } from '@sentry-internal/rrweb-snapshot';\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/** Get the closest interactive parent element, or else return the given element. */\nexport function getClosestInteractive(element: Element): Element {\n const closestInteractive = element.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || element;\n}\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nexport function getClickTargetNode(event: Event | MouseEvent | Node): Node | INode | null {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n return getClosestInteractive(target);\n}\n\n/** Get the event target node. */\nexport function getTargetNode(event: Node | { target: EventTarget | null }): Node | INode | null {\n if (isEventWithTarget(event)) {\n return event.target as Node | null;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event: unknown): event is { target: EventTarget | null } {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n","import { fill } from '@sentry/utils';\n\nimport { WINDOW } from '../../constants';\n\ntype WindowOpenHandler = () => void;\n\nlet handlers: undefined | WindowOpenHandler[];\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nexport function onWindowOpen(cb: WindowOpenHandler): () => void {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers as WindowOpenHandler[]).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen(): void {\n fill(WINDOW, 'open', function (originalWindowOpen: () => void): () => void {\n return function (...args: unknown[]): void {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n","import { IncrementalSource, MouseInteractions, record } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\n\nimport { WINDOW } from '../constants';\nimport type {\n RecordingEvent,\n ReplayClickDetector,\n ReplayContainer,\n ReplayMultiClickFrame,\n ReplaySlowClickFrame,\n SlowClickConfig,\n} from '../types';\nimport { ReplayEventTypeIncrementalSnapshot } from '../types';\nimport { timestampToS } from '../util/timestamp';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClosestInteractive } from './util/domUtils';\nimport { onWindowOpen } from './util/onWindowOpen';\n\ntype ClickBreadcrumb = Breadcrumb & {\n timestamp: number;\n};\n\ninterface Click {\n timestamp: number;\n mutationAfter?: number;\n scrollAfter?: number;\n clickBreadcrumb: ClickBreadcrumb;\n clickCount: number;\n node: HTMLElement;\n}\n\ntype IncrementalRecordingEvent = RecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { source: IncrementalSource };\n};\n\ntype IncrementalMouseInteractionRecordingEvent = IncrementalRecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { type: MouseInteractions; id: number };\n};\n\n/** Handle a click. */\nexport function handleClick(clickDetector: ReplayClickDetector, clickBreadcrumb: Breadcrumb, node: HTMLElement): void {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nexport class ClickDetector implements ReplayClickDetector {\n // protected for testing\n protected _lastMutation: number;\n protected _lastScroll: number;\n\n private _clicks: Click[];\n private _teardown: undefined | (() => void);\n\n private _threshold: number;\n private _scollTimeout: number;\n private _timeout: number;\n private _ignoreSelector: string;\n\n private _replay: ReplayContainer;\n private _checkClickTimeout?: ReturnType;\n private _addBreadcrumbEvent: typeof addBreadcrumbEvent;\n\n public constructor(\n replay: ReplayContainer,\n slowClickConfig: SlowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n this._lastMutation = 0;\n this._lastScroll = 0;\n this._clicks = [];\n\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n public addListeners(): void {\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n this._teardown = () => {\n cleanupWindowOpen();\n\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n public removeListeners(): void {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** @inheritDoc */\n public handleClick(breadcrumb: Breadcrumb, node: HTMLElement): void {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const newClick: Click = {\n timestamp: timestampToS(breadcrumb.timestamp),\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n\n // If there was a click in the last 1s on the same element, ignore it - only keep a single reference per second\n if (\n this._clicks.some(click => click.node === newClick.node && Math.abs(click.timestamp - newClick.timestamp) < 1)\n ) {\n return;\n }\n\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** @inheritDoc */\n public registerMutation(timestamp = Date.now()): void {\n this._lastMutation = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerScroll(timestamp = Date.now()): void {\n this._lastScroll = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerClick(element: HTMLElement): void {\n const node = getClosestInteractive(element);\n this._handleMultiClick(node as HTMLElement);\n }\n\n /** Count multiple clicks on elements. */\n private _handleMultiClick(node: HTMLElement): void {\n this._getClicks(node).forEach(click => {\n click.clickCount++;\n });\n }\n\n /** Get all pending clicks for a given node. */\n private _getClicks(node: HTMLElement): Click[] {\n return this._clicks.filter(click => click.node === node);\n }\n\n /** Check the clicks that happened. */\n private _checkClicks(): void {\n const timedOutClicks: Click[] = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // All of these are in seconds!\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n const pos = this._clicks.indexOf(click);\n\n if (pos > -1) {\n this._generateBreadcrumbs(click);\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n private _generateBreadcrumbs(click: Click): void {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb: ReplaySlowClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb: ReplayMultiClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n private _scheduleCheckClicks(): void {\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n\n this._checkClickTimeout = setTimeout(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nexport function ignoreElement(node: HTMLElement, ignoreSelector: string): boolean {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is ClickBreadcrumb {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds(): number {\n return Date.now() / 1000;\n}\n\n/** Update the click detector based on a recording event of rrweb. */\nexport function updateClickDetectorForRecordingEvent(clickDetector: ReplayClickDetector, event: RecordingEvent): void {\n try {\n // note: We only consider incremental snapshots here\n // This means that any full snapshot is ignored for mutation detection - the reason is that we simply cannot know if a mutation happened here.\n // E.g. think that we are buffering, an error happens and we take a full snapshot because we switched to session mode -\n // in this scenario, we would not know if a dead click happened because of the error, which is a key dead click scenario.\n // Instead, by ignoring full snapshots, we have the risk that we generate a false positive\n // (if a mutation _did_ happen but was \"swallowed\" by the full snapshot)\n // But this should be more unlikely as we'd generally capture the incremental snapshot right away\n\n if (!isIncrementalEvent(event)) {\n return;\n }\n\n const { source } = event.data;\n if (source === IncrementalSource.Mutation) {\n clickDetector.registerMutation(event.timestamp);\n }\n\n if (source === IncrementalSource.Scroll) {\n clickDetector.registerScroll(event.timestamp);\n }\n\n if (isIncrementalMouseInteraction(event)) {\n const { type, id } = event.data;\n const node = record.mirror.getNode(id);\n\n if (node instanceof HTMLElement && type === MouseInteractions.Click) {\n clickDetector.registerClick(node);\n }\n }\n } catch {\n // ignore errors here, e.g. if accessing something that does not exist\n }\n}\n\nfunction isIncrementalEvent(event: RecordingEvent): event is IncrementalRecordingEvent {\n return event.type === ReplayEventTypeIncrementalSnapshot;\n}\n\nfunction isIncrementalMouseInteraction(\n event: IncrementalRecordingEvent,\n): event is IncrementalMouseInteractionRecordingEvent {\n return event.data.source === IncrementalSource.MouseInteraction;\n}\n","var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction classMatchesRegex(node, regex, checkAncestors) {\r\n if (!node)\r\n return false;\r\n if (checkAncestors) {\r\n return (distanceToMatch(node, (node) => elementClassMatchesRegex(node, regex)) >= 0);\r\n }\r\n else if (node.nodeType === node.ELEMENT_NODE) {\r\n return elementClassMatchesRegex(node, regex);\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\nfunction visitSnapshot(node, onVisit) {\r\n function walk(current) {\r\n onVisit(current);\r\n if (current.type === NodeType.Document ||\r\n current.type === NodeType.Element) {\r\n current.childNodes.forEach(walk);\r\n }\r\n }\r\n walk(node);\r\n}\r\nfunction cleanupSnapshot() {\r\n _id = 1;\r\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, classMatchesRegex, cleanupSnapshot, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute, visitSnapshot };\n","import type { ReplayBreadcrumbFrame } from '../types/replayFrame';\n\n/**\n * Create a breadcrumb for a replay.\n */\nexport function createBreadcrumb(\n breadcrumb: Omit & Partial>,\n): ReplayBreadcrumbFrame {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n","// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n 'data-sentry-component',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nexport function getAttributesToRecord(attributes: Record): Record {\n const obj: Record = {};\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n","import { record } from '@sentry-internal/rrweb';\nimport type { serializedElementNodeWithId, serializedNodeWithId } from '@sentry-internal/rrweb-snapshot';\nimport { NodeType } from '@sentry-internal/rrweb-snapshot';\nimport type { Breadcrumb, HandlerDataDom } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { handleClick } from './handleClick';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClickTargetNode, getTargetNode } from './util/domUtils';\nimport { getAttributesToRecord } from './util/getAttributesToRecord';\n\nexport const handleDomListener: (replay: ReplayContainer) => (handlerData: HandlerDataDom) => void = (\n replay: ReplayContainer,\n) => {\n return (handlerData: HandlerDataDom): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick ? (handlerData.event as PointerEvent) : undefined;\n // Ignore clicks if ctrl/alt/meta/shift keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (\n isClick &&\n replay.clickDetector &&\n event &&\n event.target &&\n !event.altKey &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n handleClick(\n replay.clickDetector,\n result as Breadcrumb & { timestamp: number; data: { nodeId: number } },\n getClickTargetNode(handlerData.event as Event) as HTMLElement,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nexport function getBaseDomBreadcrumb(target: Node | null, message: string): Breadcrumb {\n const nodeId = record.mirror.getId(target);\n const node = nodeId && record.mirror.getNode(nodeId);\n const meta = node && record.mirror.getMeta(node);\n const element = meta && isElement(meta) ? meta : null;\n\n return {\n message,\n data: element\n ? {\n nodeId,\n node: {\n id: nodeId,\n tagName: element.tagName,\n textContent: Array.from(element.childNodes)\n .map((node: serializedNodeWithId) => node.type === NodeType.Text && node.textContent)\n .filter(Boolean) // filter out empty values\n .map(text => (text as string).trim())\n .join(''),\n attributes: getAttributesToRecord(element.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nexport function handleDom(handlerData: HandlerDataDom): Breadcrumb | null {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData: HandlerDataDom): { target: Node | null; message: string } {\n const isClick = handlerData.name === 'click';\n\n let message: string | undefined;\n let target: Node | null = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event as Event) : getTargetNode(handlerData.event as Event);\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isElement(node: serializedNodeWithId): node is serializedElementNodeWithId {\n return node.type === NodeType.Element;\n}\n","import { record } from '@sentry-internal/rrweb';\nimport { browserPerformanceTimeOrigin } from '@sentry/utils';\n\nimport { WINDOW } from '../constants';\nimport type {\n AllPerformanceEntry,\n AllPerformanceEntryData,\n ExperimentalPerformanceResourceTiming,\n LargestContentfulPaintData,\n NavigationData,\n PaintData,\n ReplayPerformanceEntry,\n ResourceData,\n} from '../types';\n\n// Map entryType -> function to normalize data for event\nconst ENTRY_TYPES: Record<\n string,\n (entry: AllPerformanceEntry) => null | ReplayPerformanceEntry\n> = {\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nexport function createPerformanceEntries(\n entries: AllPerformanceEntry[],\n): ReplayPerformanceEntry[] {\n return entries.map(createPerformanceEntry).filter(Boolean) as ReplayPerformanceEntry[];\n}\n\nfunction createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEntry | null {\n if (!ENTRY_TYPES[entry.entryType]) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time: number): number {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry: PerformanceNavigationTiming): ReplayPerformanceEntry | null {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry: ExperimentalPerformanceResourceTiming,\n): ReplayPerformanceEntry | null {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\n/**\n * Add a LCP event to the replay based on an LCP metric.\n */\nexport function getLargestContentfulPaint(metric: {\n value: number;\n entries: PerformanceEntry[];\n}): ReplayPerformanceEntry {\n const entries = metric.entries;\n const lastEntry = entries[entries.length - 1] as (PerformanceEntry & { element?: Element }) | undefined;\n const element = lastEntry ? lastEntry.element : undefined;\n\n const value = metric.value;\n\n const end = getAbsoluteTime(value);\n\n const data: ReplayPerformanceEntry = {\n type: 'largest-contentful-paint',\n name: 'largest-contentful-paint',\n start: end,\n end,\n data: {\n value,\n size: value,\n nodeId: element ? record.mirror.getId(element) : undefined,\n },\n };\n\n return data;\n}\n","import { addLcpInstrumentationHandler, addPerformanceInstrumentationHandler } from '@sentry-internal/tracing';\n\nimport type { ReplayContainer } from '../types';\nimport { getLargestContentfulPaint } from '../util/createPerformanceEntries';\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n * Returns a callback to stop observing.\n */\nexport function setupPerformanceObserver(replay: ReplayContainer): () => void {\n function addPerformanceEntry(entry: PerformanceEntry): void {\n // It is possible for entries to come up multiple times\n if (!replay.performanceEntries.includes(entry)) {\n replay.performanceEntries.push(entry);\n }\n }\n\n function onEntries({ entries }: { entries: PerformanceEntry[] }): void {\n entries.forEach(addPerformanceEntry);\n }\n\n const clearCallbacks: (() => void)[] = [];\n\n (['navigation', 'paint', 'resource'] as const).forEach(type => {\n clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));\n });\n\n clearCallbacks.push(\n addLcpInstrumentationHandler(({ metric }) => {\n replay.replayPerformanceEntries.push(getLargestContentfulPaint(metric));\n }),\n );\n\n // A callback to cleanup all handlers\n return () => {\n clearCallbacks.forEach(clearCallback => clearCallback());\n };\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { addBreadcrumb } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Log a message in debug mode, and add a breadcrumb when _experiment.traceInternals is enabled.\n */\nexport function logInfo(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n addLogBreadcrumb(message);\n }\n}\n\n/**\n * Log a message, and add a breadcrumb in the next tick.\n * This is necessary when the breadcrumb may be added before the replay is initialized.\n */\nexport function logInfoNextTick(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => {\n addLogBreadcrumb(message);\n }, 0);\n }\n}\n\nfunction addLogBreadcrumb(message: string): void {\n addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level: 'info',\n message,\n },\n { level: 'info' },\n );\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nexport class EventBufferSizeExceededError extends Error {\n public constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n","import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nexport class EventBufferArray implements EventBuffer {\n /** All the events that are buffered to be sent. */\n public events: RecordingEvent[];\n\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _totalSize: number;\n\n public constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'sync';\n }\n\n /** @inheritdoc */\n public destroy(): void {\n this.events = [];\n }\n\n /** @inheritdoc */\n public async addEvent(event: RecordingEvent): Promise {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n public finish(): Promise {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n public clear(): void {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n","import { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WorkerRequest, WorkerResponse } from '../types';\nimport { logInfo } from '../util/log';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class WorkerHandler {\n private _worker: Worker;\n private _id: number;\n private _ensureReadyPromise?: Promise;\n\n public constructor(worker: Worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }: MessageEvent) => {\n if ((data as WorkerResponse).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n public destroy(): void {\n logInfo('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n public postMessage(method: WorkerRequest['method'], arg?: WorkerRequest['arg']): Promise {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }: MessageEvent): void => {\n const response = data as WorkerResponse;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n DEBUG_BUILD && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response as T);\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n private _getAndIncrementId(): number {\n return this._id++;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\nimport { logger } from '@sentry/utils';\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { WorkerHandler } from './WorkerHandler';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class EventBufferCompressionWorker implements EventBuffer {\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _worker: WorkerHandler;\n private _earliestTimestamp: number | null;\n private _totalSize;\n\n public constructor(worker: Worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n public destroy(): void {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n public addEvent(event: RecordingEvent): Promise {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n public finish(): Promise {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n public clear(): void {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n this._worker.postMessage('clear').then(null, e => {\n DEBUG_BUILD && logger.warn('[Replay] Sending \"clear\" message to worker failed', e);\n });\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n private _sendEventToWorker(data: string): Promise {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n private async _finishRequest(): Promise {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n","import type { ReplayRecordingData } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferCompressionWorker } from './EventBufferCompressionWorker';\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nexport class EventBufferProxy implements EventBuffer {\n private _fallback: EventBufferArray;\n private _compression: EventBufferCompressionWorker;\n private _used: EventBuffer;\n private _ensureWorkerIsLoadedPromise: Promise;\n\n public constructor(worker: Worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return this._used.type;\n }\n\n /** @inheritDoc */\n public get hasEvents(): boolean {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n public get hasCheckout(): boolean {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n public set hasCheckout(value: boolean) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritDoc */\n public destroy(): void {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n public clear(): void {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n public addEvent(event: RecordingEvent): Promise {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n public async finish(): Promise {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n public ensureWorkerIsLoaded(): Promise {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n private async _ensureWorkerIsLoaded(): Promise {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n logInfo('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n private async _switchToCompressionWorker(): Promise {\n const { events, hasCheckout } = this._fallback;\n\n const addEventPromises: Promise[] = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n this._compression.hasCheckout = hasCheckout;\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n","import { WINDOW } from '../constants';\n\n/** If sessionStorage is available. */\nexport function hasSessionStorage(): boolean {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch {\n return false;\n }\n}\n","/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nexport function isSampled(sampleRate?: number): boolean {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n","import { uuid4 } from '@sentry/utils';\n\nimport type { Sampled, Session } from '../types';\n\n/**\n * Get a session with defaults & applied sampling.\n */\nexport function makeSession(session: Partial & { sampled: Sampled }): Session {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const previousSessionId = session.previousSessionId;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n };\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Save a session to session storage.\n */\nexport function saveSession(session: Session): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import type { Sampled, Session, SessionOptions } from '../types';\nimport { isSampled } from '../util/isSampled';\nimport { makeSession } from './Session';\nimport { saveSession } from './saveSession';\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nexport function getSessionSampleType(sessionSampleRate: number, allowBuffering: boolean): Sampled {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nexport function createSession(\n { sessionSampleRate, allowBuffering, stickySession = false }: SessionOptions,\n { previousSessionId }: { previousSessionId?: string } = {},\n): Session {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n previousSessionId,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n","/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nexport function isExpired(\n initialTime: null | number,\n expiry: undefined | number,\n targetTime: number = +new Date(),\n): boolean {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n","import type { Session } from '../types';\nimport { isExpired } from './isExpired';\n\n/**\n * Checks to see if session is expired\n */\nexport function isSessionExpired(\n session: Session,\n {\n maxReplayDuration,\n sessionIdleExpire,\n targetTime = Date.now(),\n }: { maxReplayDuration: number; sessionIdleExpire: number; targetTime?: number },\n): boolean {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, maxReplayDuration, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, sessionIdleExpire, targetTime)\n );\n}\n","import type { Session } from '../types';\nimport { isSessionExpired } from '../util/isSessionExpired';\n\n/** If the session should be refreshed or not. */\nexport function shouldRefreshSession(\n session: Session,\n { sessionIdleExpire, maxReplayDuration }: { sessionIdleExpire: number; maxReplayDuration: number },\n): boolean {\n // If not expired, all good, just keep the session\n if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) {\n return false;\n }\n\n // If we are buffering & haven't ever flushed yet, always continue\n if (session.sampled === 'buffer' && session.segmentId === 0) {\n return false;\n }\n\n return true;\n}\n","import type { Session, SessionOptions } from '../types';\nimport { logInfoNextTick } from '../util/log';\nimport { createSession } from './createSession';\nimport { fetchSession } from './fetchSession';\nimport { shouldRefreshSession } from './shouldRefreshSession';\n\n/**\n * Get or create a session, when initializing the replay.\n * Returns a session that may be unsampled.\n */\nexport function loadOrCreateSession(\n {\n traceInternals,\n sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }: {\n sessionIdleExpire: number;\n maxReplayDuration: number;\n traceInternals?: boolean;\n previousSessionId?: string;\n },\n sessionOptions: SessionOptions,\n): Session {\n const existingSession = sessionOptions.stickySession && fetchSession(traceInternals);\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n logInfoNextTick('[Replay] Creating new session', traceInternals);\n return createSession(sessionOptions, { previousSessionId });\n }\n\n if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {\n return existingSession;\n }\n\n logInfoNextTick('[Replay] Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\nimport { logInfoNextTick } from '../util/log';\nimport { makeSession } from './Session';\n\n/**\n * Fetches a session from storage\n */\nexport function fetchSession(traceInternals?: boolean): Session | null {\n if (!hasSessionStorage()) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) as Session;\n\n logInfoNextTick('[Replay] Loading existing session', traceInternals);\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { getClient } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { EventBufferSizeExceededError } from '../eventBuffer/error';\nimport type { AddEventResult, RecordingEvent, ReplayContainer, ReplayFrameEvent, ReplayPluginOptions } from '../types';\nimport { logInfo } from './log';\nimport { timestampToMs } from './timestamp';\n\nfunction isCustomEvent(event: RecordingEvent): event is ReplayFrameEvent {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * In contrast to `addEvent`, this does not return a promise & does not wait for the adding of the event to succeed/fail.\n * Instead this returns `true` if we tried to add the event, else false.\n * It returns `false` e.g. if we are paused, disabled, or out of the max replay duration.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEventSync(replay: ReplayContainer, event: RecordingEvent, isCheckout?: boolean): boolean {\n if (!shouldAddEvent(replay, event)) {\n return false;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n _addEvent(replay, event, isCheckout);\n\n return true;\n}\n\n/**\n * Add an event to the event buffer.\n * Resolves to `null` if no event was added, else to `void`.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!shouldAddEvent(replay, event)) {\n return Promise.resolve(null);\n }\n\n return _addEvent(replay, event, isCheckout);\n}\n\nasync function _addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!replay.eventBuffer) {\n return null;\n }\n\n try {\n if (isCheckout && replay.recordingMode === 'buffer') {\n replay.eventBuffer.clear();\n }\n\n if (isCheckout) {\n replay.eventBuffer.hasCheckout = true;\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await replay.eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const reason = error && error instanceof EventBufferSizeExceededError ? 'addEventSizeExceeded' : 'addEvent';\n\n DEBUG_BUILD && logger.error(error);\n await replay.stop({ reason });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\n/** Exported only for tests. */\nexport function shouldAddEvent(replay: ReplayContainer, event: RecordingEvent): boolean {\n if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) {\n return false;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return false;\n }\n\n // Throw out events that are +60min from the initial timestamp\n if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) {\n logInfo(\n `[Replay] Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`,\n replay.getOptions()._experiments.traceInternals,\n );\n return false;\n }\n\n return true;\n}\n\nfunction maybeApplyCallback(\n event: RecordingEvent,\n callback: ReplayPluginOptions['beforeAddRecordingEvent'],\n): RecordingEvent | null | undefined {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n DEBUG_BUILD &&\n logger.error('[Replay] An error occured in the `beforeAddRecordingEvent` callback, skipping the event...', error);\n return null;\n }\n\n return event;\n}\n","import type { ErrorEvent, Event, FeedbackEvent, ReplayEvent, TransactionEvent } from '@sentry/types';\n\n/** If the event is an error event */\nexport function isErrorEvent(event: Event): event is ErrorEvent {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nexport function isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nexport function isReplayEvent(event: Event): event is ReplayEvent {\n return event.type === 'replay_event';\n}\n\n/** If the event is a feedback event */\nexport function isFeedbackEvent(event: Event): event is FeedbackEvent {\n return event.type === 'feedback';\n}\n","import { getClient } from '@sentry/core';\nimport type { ErrorEvent, Event, TransactionEvent, Transport, TransportMakeRequestResponse } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isTransactionEvent } from '../util/eventUtils';\n\ntype AfterSendEventCallback = (event: Event, sendResponse: TransportMakeRequestResponse | void) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleAfterSendEvent(replay: ReplayContainer): AfterSendEventCallback {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event: Event, sendResponse: TransportMakeRequestResponse | void) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n if (isTransactionEvent(event)) {\n handleTransactionEvent(replay, event);\n return;\n }\n\n handleErrorEvent(replay, event);\n };\n}\n\nfunction handleTransactionEvent(replay: ReplayContainer, event: TransactionEvent): void {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id as string);\n }\n}\n\nfunction handleErrorEvent(replay: ReplayContainer, event: ErrorEvent): void {\n const replayContext = replay.getContext();\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n // We limit to max. 100 errors linked\n if (event.event_id && replayContext.errorIds.size < 100) {\n replayContext.errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode !== 'buffer' || !event.tags || !event.tags.replayId) {\n return;\n }\n\n const { beforeErrorSampling } = replay.getOptions();\n if (typeof beforeErrorSampling === 'function' && !beforeErrorSampling(event)) {\n return;\n }\n\n setTimeout(() => {\n // Capture current event buffer as new replay\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.sendBufferedReplayOrFlush();\n });\n}\n\nfunction isBaseTransportSend(): boolean {\n const client = getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send as Transport['send'] & { __sentry__baseTransport__?: true }).__sentry__baseTransport__ || false\n );\n}\n","import { EventType } from '@sentry-internal/rrweb';\n\nimport type { AddEventResult, AllEntryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\n\n/**\n * Create a \"span\" for each performance entry.\n */\nexport function createPerformanceSpans(\n replay: ReplayContainer,\n entries: ReplayPerformanceEntry[],\n): Promise[] {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n","import type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../../types';\nimport { createPerformanceSpans } from '../../util/createPerformanceSpans';\nimport { shouldFilterRequest } from '../../util/shouldFilterRequest';\n\n/** Add a performance entry breadcrumb */\nexport function addNetworkBreadcrumb(\n replay: ReplayContainer,\n result: ReplayPerformanceEntry | null,\n): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n","import { getClient, isSentryRequestUrl } from '@sentry/core';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nexport function shouldFilterRequest(replay: ReplayContainer, url: string): boolean {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (DEBUG_BUILD && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return isSentryRequestUrl(url, getClient());\n}\n","import type { TextEncoderInternal } from '@sentry/types';\nimport { dropUndefinedKeys, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { NETWORK_BODY_MAX_SIZE, WINDOW } from '../../constants';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkBody,\n NetworkMetaWarning,\n NetworkRequestData,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n ReplayPerformanceEntry,\n} from '../../types';\n\n/** Get the size of a body. */\nexport function getBodySize(\n body: RequestInit['body'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nexport function parseContentLengthHeader(header: string | null | undefined): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nexport function getBodyString(body: unknown): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof URLSearchParams) {\n return [body.toString()];\n }\n\n if (body instanceof FormData) {\n return [_serializeFormData(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/** Merge a warning into an existing network request/response. */\nexport function mergeWarning(\n info: ReplayNetworkRequestOrResponse | undefined,\n warning: NetworkMetaWarning,\n): ReplayNetworkRequestOrResponse {\n if (!info) {\n return {\n headers: {},\n size: undefined,\n _meta: {\n warnings: [warning],\n },\n };\n }\n\n const newMeta = { ...info._meta };\n const existingWarnings = newMeta.warnings || [];\n newMeta.warnings = [...existingWarnings, warning];\n\n info._meta = newMeta;\n return info;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nexport function makeNetworkReplayBreadcrumb(\n type: string,\n data: ReplayNetworkRequestData | null,\n): ReplayPerformanceEntry | null {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result: ReplayPerformanceEntry = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nexport function buildSkippedNetworkRequestOrResponse(bodySize: number | undefined): ReplayNetworkRequestOrResponse {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nexport function buildNetworkRequestOrResponse(\n headers: Record,\n bodySize: number | undefined,\n body: string | undefined,\n): ReplayNetworkRequestOrResponse | undefined {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info: ReplayNetworkRequestOrResponse = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings && warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nexport function getAllowedHeaders(headers: Record, allowedHeaders: string[]): Record {\n return Object.keys(headers).reduce((filteredHeaders: Record, key: string) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData: FormData): string {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body: string | undefined): {\n body: NetworkBody | undefined;\n warnings?: NetworkMetaWarning[];\n} {\n if (!body || typeof body !== 'string') {\n return {\n body,\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n const isProbablyJson = _strIsProbablyJson(body);\n\n if (exceedsSizeLimit) {\n const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE);\n\n if (isProbablyJson) {\n return {\n body: truncatedBody,\n warnings: ['MAYBE_JSON_TRUNCATED'],\n };\n }\n\n return {\n body: `${truncatedBody}…`,\n warnings: ['TEXT_TRUNCATED'],\n };\n }\n\n if (isProbablyJson) {\n try {\n const jsonBody = JSON.parse(body);\n return {\n body: jsonBody,\n };\n } catch {\n // fall back to just send the body as string\n }\n }\n\n return {\n body,\n };\n}\n\nfunction _strIsProbablyJson(str: string): boolean {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nexport function urlMatches(url: string, urls: (string | RegExp)[]): boolean {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nexport function getFullUrl(url: string, baseURI = WINDOW.document.baseURI): string {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n","import type { Breadcrumb, FetchBreadcrumbData, TextEncoderInternal } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n FetchHint,\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureFetchBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n replay: ReplayContainer;\n },\n): Promise {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichFetchBreadcrumb(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { input, response } = hint;\n\n const body = input ? _getFetchRequestArgBody(input) : undefined;\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n): Promise {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails =\n urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders }: ReplayNetworkOptions,\n input: FetchHint['input'] | undefined,\n requestBodySize?: number,\n): ReplayNetworkRequestOrResponse | undefined {\n const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const [bodyStr, warning] = getBodyString(requestBody);\n const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n\n if (warning) {\n return mergeWarning(data, warning);\n }\n\n return data;\n}\n\n/** Exported only for tests. */\nexport async function _getResponseInfo(\n captureDetails: boolean,\n {\n networkCaptureBodies,\n textEncoder,\n networkResponseHeaders,\n }: Pick & {\n textEncoder: TextEncoderInternal;\n },\n response: Response | undefined,\n responseBodySize?: number,\n): Promise {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {};\n\n if (!response || (!networkCaptureBodies && responseBodySize !== undefined)) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n const [bodyText, warning] = await _parseFetchResponseBody(response);\n const result = getResponseData(bodyText, {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n });\n\n if (warning) {\n return mergeWarning(result, warning);\n }\n\n return result;\n}\n\nfunction getResponseData(\n bodyText: string | undefined,\n {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n }: {\n captureDetails: boolean;\n networkCaptureBodies: boolean;\n responseBodySize: number | undefined;\n headers: Record;\n textEncoder: TextEncoderInternal;\n },\n): ReplayNetworkRequestOrResponse | undefined {\n try {\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize response body', error);\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchResponseBody(response: Response): Promise<[string | undefined, NetworkMetaWarning?]> {\n const res = _tryCloneResponse(response);\n\n if (!res) {\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n try {\n const text = await _tryGetResponseText(res);\n return [text];\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to get text body from response', error);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs: unknown[] = []): RequestInit['body'] | undefined {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] as RequestInit).body;\n}\n\nfunction getAllHeaders(headers: Headers, allowedHeaders: string[]): Record {\n const allHeaders: Record = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) as string;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs: unknown[], allowedHeaders: string[]): Record {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] as Request | RequestInit, allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] as Request | RequestInit, allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input: Request | RequestInit | undefined,\n allowedHeaders: string[],\n): Record {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\nfunction _tryCloneResponse(response: Response): Response | void {\n try {\n // We have to clone this, as the body can only be read once\n return response.clone();\n } catch (error) {\n // this can throw if the response was already consumed before\n DEBUG_BUILD && logger.warn('[Replay] Failed to clone response body', error);\n }\n}\n\n/**\n * Get the response body of a fetch request, or timeout after 500ms.\n * Fetch can return a streaming body, that may not resolve (or not for a long time).\n * If that happens, we rather abort after a short time than keep waiting for this.\n */\nfunction _tryGetResponseText(response: Response): Promise {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error('Timeout while trying to read response body')), 500);\n\n _getResponseText(response)\n .then(\n txt => resolve(txt),\n reason => reject(reason),\n )\n .finally(() => clearTimeout(timeout));\n });\n\n return _getResponseText(response);\n}\n\nasync function _getResponseText(response: Response): Promise {\n // Force this to be a promise, just to be safe\n // eslint-disable-next-line no-return-await\n return await response.text();\n}\n","import type { Breadcrumb, TextEncoderInternal, XhrBreadcrumbData } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n XhrHint,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureXhrBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & { replay: ReplayContainer },\n): Promise {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture xhr breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichXhrBreadcrumb(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { xhr, input } = hint;\n\n if (!xhr) {\n return;\n }\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : _getBodySize(xhr.response, xhr.responseType, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions,\n): ReplayNetworkRequestData | null {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input) : [undefined];\n const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [undefined];\n\n const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);\n const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request: requestWarning ? mergeWarning(request, requestWarning) : request,\n response: responseWarning ? mergeWarning(response, responseWarning) : response,\n };\n}\n\nfunction getResponseHeaders(xhr: XMLHttpRequest): Record {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record, line: string) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n\nfunction _getXhrResponseBody(xhr: XMLHttpRequest): [string | undefined, NetworkMetaWarning?] {\n // We collect errors that happen, but only log them if we can't get any response body\n const errors: unknown[] = [];\n\n try {\n return [xhr.responseText];\n } catch (e) {\n errors.push(e);\n }\n\n // Try to manually parse the response body, if responseText fails\n try {\n return _parseXhrResponse(xhr.response, xhr.responseType);\n } catch (e) {\n errors.push(e);\n }\n\n DEBUG_BUILD && logger.warn('[Replay] Failed to get xhr response body', ...errors);\n\n return [undefined];\n}\n\n/**\n * Get the string representation of the XHR response.\n * Based on MDN, these are the possible types of the response:\n * string\n * ArrayBuffer\n * Blob\n * Document\n * POJO\n *\n * Exported only for tests.\n */\nexport function _parseXhrResponse(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof Document) {\n return [body.body.outerHTML];\n }\n\n if (responseType === 'json' && body && typeof body === 'object') {\n return [JSON.stringify(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\nfunction _getBodySize(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr, textEncoder);\n } catch {\n return undefined;\n }\n}\n","import { getClient } from '@sentry/core';\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n FetchBreadcrumbData,\n TextEncoderInternal,\n XhrBreadcrumbData,\n} from '@sentry/types';\nimport { addFetchInstrumentationHandler, addXhrInstrumentationHandler, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { FetchHint, ReplayContainer, ReplayNetworkOptions, XhrHint } from '../types';\nimport { handleFetchSpanListener } from './handleFetch';\nimport { handleXhrSpanListener } from './handleXhr';\nimport { captureFetchBreadcrumbToReplay, enrichFetchBreadcrumb } from './util/fetchUtils';\nimport { captureXhrBreadcrumbToReplay, enrichXhrBreadcrumb } from './util/xhrUtils';\n\ninterface ExtendedNetworkBreadcrumbsOptions extends ReplayNetworkOptions {\n replay: ReplayContainer;\n textEncoder: TextEncoderInternal;\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nexport function handleNetworkBreadcrumbs(replay: ReplayContainer): void {\n const client = getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options: ExtendedNetworkBreadcrumbsOptions = {\n replay,\n textEncoder,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addFetchInstrumentationHandler(handleFetchSpanListener(replay));\n addXhrInstrumentationHandler(handleXhrSpanListener(replay));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nexport function beforeAddNetworkBreadcrumb(\n options: ExtendedNetworkBreadcrumbsOptions,\n breadcrumb: Breadcrumb,\n hint?: BreadcrumbHint,\n): void {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n DEBUG_BUILD && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: XhrBreadcrumbData } {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: FetchBreadcrumbData } {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint?: BreadcrumbHint): hint is XhrHint {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint?: BreadcrumbHint): hint is FetchHint {\n return hint && hint.response;\n}\n","import type { HandlerDataFetch } from '@sentry/types';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleFetch(handlerData: HandlerDataFetch): null | ReplayPerformanceEntry {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response ? (response as Response).status : undefined,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addFetchInstrumentationHandler(listener)`.\n */\nexport function handleFetchSpanListener(replay: ReplayContainer): (handlerData: HandlerDataFetch) => void {\n return (handlerData: HandlerDataFetch) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { HandlerDataXhr } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleXhr(handlerData: HandlerDataXhr): ReplayPerformanceEntry | null {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addXhrInstrumentationHandler(listener)`.\n */\nexport function handleXhrSpanListener(replay: ReplayContainer): (handlerData: HandlerDataXhr) => void {\n return (handlerData: HandlerDataXhr) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n","import type { Breadcrumb, Scope } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport { CONSOLE_ARG_MAX_SIZE } from '../constants';\nimport type { ReplayContainer } from '../types';\nimport type { ReplayFrame } from '../types/replayFrame';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\nlet _LAST_BREADCRUMB: null | Breadcrumb = null;\n\ntype BreadcrumbWithCategory = Required>;\n\nfunction isBreadcrumbWithCategory(breadcrumb: Breadcrumb): breadcrumb is BreadcrumbWithCategory {\n return !!breadcrumb.category;\n}\n\nexport const handleScopeListener: (replay: ReplayContainer) => (scope: Scope) => void =\n (replay: ReplayContainer) =>\n (scope: Scope): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nexport function handleScope(scope: Scope): Breadcrumb | null {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n !isBreadcrumbWithCategory(newBreadcrumb) ||\n ['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (newBreadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(newBreadcrumb);\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/** exported for tests only */\nexport function normalizeConsoleBreadcrumb(\n breadcrumb: Omit & BreadcrumbWithCategory,\n): ReplayFrame {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n // We use the pretty printed JSON string here as a base\n return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n","import type { BaseClient } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport { addEventProcessor, getClient } from '@sentry/core';\nimport type { Client, DynamicSamplingContext } from '@sentry/types';\nimport { addClickKeypressInstrumentationHandler, addHistoryInstrumentationHandler } from '@sentry/utils';\n\nimport { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';\nimport { handleBeforeSendEvent } from '../coreHandlers/handleBeforeSendEvent';\nimport { handleDomListener } from '../coreHandlers/handleDom';\nimport { handleGlobalEventListener } from '../coreHandlers/handleGlobalEvent';\nimport { handleHistorySpanListener } from '../coreHandlers/handleHistory';\nimport { handleNetworkBreadcrumbs } from '../coreHandlers/handleNetworkBreadcrumbs';\nimport { handleScopeListener } from '../coreHandlers/handleScope';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Add global listeners that cannot be removed.\n */\nexport function addGlobalListeners(replay: ReplayContainer): void {\n // Listeners from core SDK //\n const scope = getCurrentScope();\n const client = getClient();\n\n scope.addScopeListener(handleScopeListener(replay));\n addClickKeypressInstrumentationHandler(handleDomListener(replay));\n addHistoryInstrumentationHandler(handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n const eventProcessor = handleGlobalEventListener(replay, !hasHooks(client));\n if (client && client.addEventProcessor) {\n client.addEventProcessor(eventProcessor);\n } else {\n addEventProcessor(eventProcessor);\n }\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('beforeSendEvent', handleBeforeSendEvent(replay));\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc: DynamicSamplingContext) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n // Ensure to check that the session is still active - it could have expired in the meanwhile\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (isSessionActive) {\n dsc.replay_id = replayId;\n }\n }\n });\n\n client.on('startTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We may be missing the initial startTransaction due to timing issues,\n // so we capture it on finish again.\n client.on('finishTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We want to flush replay\n client.on('beforeSendFeedback', (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options && options.includeReplay && replay.isEnabled() && replayId) {\n // This should never reject\n if (feedbackEvent.contexts && feedbackEvent.contexts.feedback) {\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n }\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client: Client | undefined): client is BaseClient {\n return !!(client && client.on);\n}\n","import type { HandlerDataHistory } from '@sentry/types';\n\nimport type { HistoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from '../util/createPerformanceSpans';\n\nfunction handleHistory(handlerData: HandlerDataHistory): ReplayPerformanceEntry {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addHistoryInstrumentationHandler(listener)`.\n */\nexport function handleHistorySpanListener(replay: ReplayContainer): (handlerData: HandlerDataHistory) => void {\n return (handlerData: HandlerDataHistory) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n","import type { Event, EventHint } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isFeedbackEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';\nimport { isRrwebError } from '../util/isRrwebError';\nimport { handleAfterSendEvent } from './handleAfterSendEvent';\nimport { addFeedbackBreadcrumb } from './util/addFeedbackBreadcrumb';\nimport { shouldSampleForBufferEvent } from './util/shouldSampleForBufferEvent';\n\n/**\n * Returns a listener to be added to `addEventProcessor(listener)`.\n */\nexport function handleGlobalEventListener(\n replay: ReplayContainer,\n includeAfterSendEventHandling = false,\n): (event: Event, hint: EventHint) => Event | null {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return Object.assign(\n (event: Event, hint: EventHint) => {\n // Do nothing if replay has been disabled\n if (!replay.isEnabled()) {\n return event;\n }\n\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors, transactions, and feedbacks, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) {\n return event;\n }\n\n // Ensure we do not add replay_id if the session is expired\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (!isSessionActive) {\n return event;\n }\n\n if (isFeedbackEvent(event)) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.flush();\n event.contexts.feedback.replay_id = replay.getSessionId();\n // Add a replay breadcrumb for this piece of feedback\n addFeedbackBreadcrumb(replay, event);\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n DEBUG_BUILD && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n },\n { id: 'Replay' },\n );\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport type { FeedbackEvent } from '@sentry/types';\n\nimport type { ReplayBreadcrumbFrameEvent, ReplayContainer } from '../../types';\n\n/**\n * Add a feedback breadcrumb event to replay.\n */\nexport function addFeedbackBreadcrumb(replay: ReplayContainer, event: FeedbackEvent): void {\n replay.triggerUserActivity();\n replay.addUpdate(() => {\n if (!event.timestamp) {\n // Ignore events that don't have timestamps (this shouldn't happen, more of a typing issue)\n // Return true here so that we don't flush\n return true;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: event.timestamp * 1000,\n data: {\n tag: 'breadcrumb',\n payload: {\n timestamp: event.timestamp,\n type: 'default',\n category: 'sentry.feedback',\n data: {\n feedbackId: event.event_id,\n },\n },\n },\n } as ReplayBreadcrumbFrameEvent);\n\n return false;\n });\n}\n","import type { Event, EventHint } from '@sentry/types';\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nexport function isRrwebError(event: Event, hint: EventHint): boolean {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-expect-error this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n return false;\n}\n","import type { Event } from '@sentry/types';\n\nimport { UNABLE_TO_SEND_REPLAY } from '../../constants';\nimport type { ReplayContainer } from '../../types';\nimport { isSampled } from '../../util/isSampled';\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `hanldleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nexport function shouldSampleForBufferEvent(replay: ReplayContainer, event: Event): boolean {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n EventProcessor,\n FeedbackEvent,\n Integration,\n IntegrationClass,\n MetricBucketItem,\n MetricsAggregator,\n Outcome,\n ParameterizedString,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n StartSpanOptions,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n SentryError,\n SyncPromise,\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isParameterizedString,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport { getClient } from './exports';\nimport { getIsolationScope } from './hub';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport { createMetricEnvelope } from './metrics/envelope';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /**\n * A reference to a metrics aggregator\n *\n * @experimental Note this is alpha API. It may experience breaking changes in the future.\n */\n public metricsAggregator?: MetricsAggregator;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n protected _eventProcessors: EventProcessor[];\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(\n this._captureEvent(event, hint, capturedSpanScope || scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n if (this.metricsAggregator) {\n this.metricsAggregator.flush();\n }\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n if (this.metricsAggregator) {\n this.metricsAggregator.close();\n }\n return result;\n });\n }\n\n /** Get all installed event processors. */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * This is an internal function to setup all integrations that should run on the client.\n * @deprecated Use `client.init()` instead.\n */\n public setupIntegrations(forceInitialize?: boolean): void {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._setupIntegrations();\n }\n }\n\n /** @inheritdoc */\n public init(): void {\n if (this._isEnabled()) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this.getIntegrationByName(integrationId);\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n public getIntegrationByName(integrationName: string): T | undefined {\n return this._integrations[integrationName] as T | undefined;\n }\n\n /**\n * Returns the client's instance of the given integration class, it any.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, eventOrCount?: Event | number): void {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /**\n * @inheritDoc\n */\n public captureAggregateMetrics(metricBucketItems: Array): void {\n DEBUG_BUILD && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);\n const metricsEnvelope = createMetricEnvelope(\n metricBucketItems,\n this._dsn,\n this._options._metadata,\n this._options.tunnel,\n );\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(metricsEnvelope);\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n public on(hook: 'startTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'startPageLoadSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'startPageLoadSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: 'startNavigationSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n protected _setupIntegrations(): void {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n\n // TODO v8: We don't need this flag anymore\n this._integrationsInitialized = true;\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope = getIsolationScope(),\n ): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n const propagationContext = {\n ...isolationScope.getPropagationContext(),\n ...(scope ? scope.getPropagationContext() : undefined),\n };\n\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n DEBUG_BUILD && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/**\n * Add an event processor to the current client.\n * This event processor will run for all events processed by this client.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n const client = getClient();\n\n if (!client || !client.addEventProcessor) {\n return;\n }\n\n client.addEventProcessor(callback);\n}\n","import type { ErrorEvent, Event } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { isErrorEvent } from '../util/eventUtils';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\ntype BeforeSendEventCallback = (event: Event) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleBeforeSendEvent(replay: ReplayContainer): BeforeSendEventCallback {\n return (event: Event) => {\n if (!replay.isEnabled() || !isErrorEvent(event)) {\n return;\n }\n\n handleHydrationError(replay, event);\n };\n}\n\nfunction handleHydrationError(replay: ReplayContainer, event: ErrorEvent): void {\n const exceptionValue = event.exception && event.exception.values && event.exception.values[0].value;\n if (typeof exceptionValue !== 'string') {\n return;\n }\n\n if (\n // Only matches errors in production builds of react-dom\n // Example https://reactjs.org/docs/error-decoder.html?invariant=423\n exceptionValue.match(/reactjs\\.org\\/docs\\/error-decoder\\.html\\?invariant=(418|419|422|423|425)/) ||\n // Development builds of react-dom\n // Error 1: Hydration failed because the initial UI does not match what was rendered on the server.\n // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match.\n exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)\n ) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.hydrate-error',\n });\n addBreadcrumbEvent(replay, breadcrumb);\n }\n}\n","import { WINDOW } from '../constants';\nimport type { AddEventResult, MemoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from './createPerformanceSpans';\n\ntype ReplayMemoryEntry = ReplayPerformanceEntry & { data: { memory: MemoryInfo } };\n\ninterface MemoryInfo {\n jsHeapSizeLimit: number;\n totalJSHeapSize: number;\n usedJSHeapSize: number;\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nexport async function addMemoryEntry(replay: ReplayContainer): Promise> {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry: MemoryInfo): ReplayMemoryEntry {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n","import { EventType } from '@sentry-internal/rrweb';\nimport { logger } from '@sentry/utils';\n\nimport { updateClickDetectorForRecordingEvent } from '../coreHandlers/handleClick';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { saveSession } from '../session/saveSession';\nimport type { RecordingEvent, ReplayContainer, ReplayOptionFrameEvent } from '../types';\nimport { addEventSync } from './addEvent';\nimport { logInfo } from './log';\n\ntype RecordingEmitCallback = (event: RecordingEvent, isCheckout?: boolean) => void;\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nexport function getHandleRecordingEmit(replay: ReplayContainer): RecordingEmitCallback {\n let hadFirstEvent = false;\n\n return (event: RecordingEvent, _isCheckout?: boolean) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n if (replay.clickDetector) {\n updateClickDetectorForRecordingEvent(replay.clickDetector, event);\n }\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // If the event is not added (e.g. due to being paused, disabled, or out of the max replay duration),\n // Skip all further steps\n if (!addEventSync(replay, event, isCheckout)) {\n // Return true to skip scheduling a debounced flush\n return true;\n }\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time.\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n addSettingsEvent(replay, isCheckout);\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n logInfo(\n `[Replay] Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`,\n replay.getOptions()._experiments.traceInternals,\n );\n\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n if (replay.recordingMode === 'session') {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void replay.flush();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nexport function createOptionsEvent(replay: ReplayContainer): ReplayOptionFrameEvent {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n shouldRecordCanvas: replay.isRecordingCanvas(),\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay: ReplayContainer, isCheckout?: boolean): void {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return;\n }\n\n addEventSync(replay, createOptionsEvent(replay), false);\n}\n","import type { DsnComponents, ReplayEnvelope, ReplayEvent, ReplayRecordingData } from '@sentry/types';\nimport { createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader } from '@sentry/utils';\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nexport function createReplayEnvelope(\n replayEvent: ReplayEvent,\n recordingData: ReplayRecordingData,\n dsn: DsnComponents,\n tunnel?: string,\n): ReplayEnvelope {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n","import type { ReplayRecordingData } from '@sentry/types';\n\n/**\n * Prepare the recording data ready to be sent.\n */\nexport function prepareRecordingData({\n recordingData,\n headers,\n}: {\n recordingData: ReplayRecordingData;\n headers: Record;\n}): ReplayRecordingData {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n","import type { IntegrationIndex, Scope } from '@sentry/core';\nimport { getIsolationScope } from '@sentry/core';\nimport { prepareEvent } from '@sentry/core';\nimport type { Client, EventHint, ReplayEvent } from '@sentry/types';\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nexport async function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}: {\n client: Client & { _integrations?: IntegrationIndex };\n scope: Scope;\n replayId: string;\n event: ReplayEvent;\n}): Promise {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n\n const eventHint: EventHint = { event_id, integrations };\n\n if (client.emit) {\n client.emit('preprocessEvent', event, eventHint);\n }\n\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n eventHint,\n scope,\n client,\n getIsolationScope(),\n )) as ReplayEvent | null;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n","import { getClient, getCurrentScope } from '@sentry/core';\nimport type { ReplayEvent, TransportMakeRequestResponse } from '@sentry/types';\nimport type { RateLimits } from '@sentry/utils';\nimport { isRateLimited, updateRateLimits } from '@sentry/utils';\n\nimport { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { createReplayEnvelope } from './createReplayEnvelope';\nimport { logInfo } from './log';\nimport { prepareRecordingData } from './prepareRecordingData';\nimport { prepareReplayEvent } from './prepareReplayEvent';\n\n/**\n * Send replay attachment using `fetch()`\n */\nexport async function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}: SendReplayData): Promise {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const client = getClient();\n const scope = getCurrentScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent: ReplayEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n logInfo('An event processor returned `null`, will not send event.');\n return;\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete replayEvent.sdkProcessingMetadata;\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response: void | TransportMakeRequestResponse;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n const rateLimits = updateRateLimits({}, response);\n if (isRateLimited(rateLimits, 'replay')) {\n throw new RateLimitError(rateLimits);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nexport class TransportStatusCodeError extends Error {\n public constructor(statusCode: number) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * This error indicates that we hit a rate limit API error.\n */\nexport class RateLimitError extends Error {\n public rateLimits: RateLimits;\n\n public constructor(rateLimits: RateLimits) {\n super('Rate limit hit');\n this.rateLimits = rateLimits;\n }\n}\n","import { captureException, setContext } from '@sentry/core';\n\nimport { RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SendReplayData } from '../types';\nimport { RateLimitError, TransportStatusCodeError, sendReplayRequest } from './sendReplayRequest';\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nexport async function sendReplay(\n replayData: SendReplayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n): Promise {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (DEBUG_BUILD && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n","export const THROTTLED = '__THROTTLED';\nexport const SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle any>(\n fn: T,\n maxCount: number,\n durationSeconds: number,\n): (...rest: Parameters) => ReturnType | typeof THROTTLED | typeof SKIPPED {\n const counter = new Map();\n\n const _cleanup = (now: number): void => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = (): number => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest: Parameters): ReturnType | typeof THROTTLED | typeof SKIPPED => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n","/* eslint-disable max-lines */ // TODO: We might want to split this file up\nimport { EventType, record } from '@sentry-internal/rrweb';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n captureException,\n getClient,\n getCurrentScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { ReplayRecordingMode, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport {\n BUFFER_CHECKOUT_TIME,\n SESSION_IDLE_EXPIRE_DURATION,\n SESSION_IDLE_PAUSE_DURATION,\n SLOW_CLICK_SCROLL_TIMEOUT,\n SLOW_CLICK_THRESHOLD,\n WINDOW,\n} from './constants';\nimport { ClickDetector } from './coreHandlers/handleClick';\nimport { handleKeyboardEvent } from './coreHandlers/handleKeyboardEvent';\nimport { setupPerformanceObserver } from './coreHandlers/performanceObserver';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventBuffer } from './eventBuffer';\nimport { clearSession } from './session/clearSession';\nimport { loadOrCreateSession } from './session/loadOrCreateSession';\nimport { saveSession } from './session/saveSession';\nimport { shouldRefreshSession } from './session/shouldRefreshSession';\n\nimport type {\n AddEventResult,\n AddUpdateCallback,\n AllPerformanceEntry,\n AllPerformanceEntryData,\n EventBuffer,\n InternalEventContext,\n PopEventContext,\n RecordingEvent,\n RecordingOptions,\n ReplayBreadcrumbFrame,\n ReplayCanvasIntegrationOptions,\n ReplayContainer as ReplayContainerInterface,\n ReplayPerformanceEntry,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n Session,\n SlowClickConfig,\n Timeouts,\n} from './types';\nimport { ReplayEventTypeCustom } from './types';\nimport { addEvent, addEventSync } from './util/addEvent';\nimport { addGlobalListeners } from './util/addGlobalListeners';\nimport { addMemoryEntry } from './util/addMemoryEntry';\nimport { createBreadcrumb } from './util/createBreadcrumb';\nimport { createPerformanceEntries } from './util/createPerformanceEntries';\nimport { createPerformanceSpans } from './util/createPerformanceSpans';\nimport { debounce } from './util/debounce';\nimport { getHandleRecordingEmit } from './util/handleRecordingEmit';\nimport { isExpired } from './util/isExpired';\nimport { isSessionExpired } from './util/isSessionExpired';\nimport { logInfo, logInfoNextTick } from './util/log';\nimport { sendReplay } from './util/sendReplay';\nimport type { SKIPPED } from './util/throttle';\nimport { THROTTLED, throttle } from './util/throttle';\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nexport class ReplayContainer implements ReplayContainerInterface {\n public eventBuffer: EventBuffer | null;\n\n public performanceEntries: AllPerformanceEntry[];\n\n public replayPerformanceEntries: ReplayPerformanceEntry[];\n\n public session: Session | undefined;\n\n public clickDetector: ClickDetector | undefined;\n\n /**\n * Recording can happen in one of three modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n public recordingMode: ReplayRecordingMode;\n\n /**\n * The current or last active transcation.\n * This is only available when performance is enabled.\n */\n public lastTransaction?: Transaction;\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n public readonly timeouts: Timeouts;\n\n private _throttledAddEvent: (\n event: RecordingEvent,\n isCheckout?: boolean,\n ) => typeof THROTTLED | typeof SKIPPED | Promise;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n private readonly _options: ReplayPluginOptions;\n\n private _performanceCleanupCallback?: () => void;\n\n private _debouncedFlush: ReturnType;\n private _flushLock: Promise | undefined;\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n private _lastActivity: number;\n\n /**\n * Is the integration currently active?\n */\n private _isEnabled: boolean;\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n private _isPaused: boolean;\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n private _hasInitializedCoreListeners: boolean;\n\n /**\n * Function to stop recording\n */\n private _stopRecording: ReturnType | undefined;\n\n private _context: InternalEventContext;\n\n /**\n * Internal use for canvas recording options\n */\n private _canvas: ReplayCanvasIntegrationOptions | undefined;\n\n public constructor({\n options,\n recordingOptions,\n }: {\n options: ReplayPluginOptions;\n recordingOptions: RecordingOptions;\n }) {\n this.eventBuffer = null;\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n this.recordingMode = 'session';\n this.timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n } as const;\n this._lastActivity = Date.now();\n this._isEnabled = false;\n this._isPaused = false;\n this._hasInitializedCoreListeners = false;\n this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event: RecordingEvent, isCheckout?: boolean) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig: SlowClickConfig | undefined = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n }\n\n /** Get the event context. */\n public getContext(): InternalEventContext {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n public isEnabled(): boolean {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n public isPaused(): boolean {\n return this._isPaused;\n }\n\n /**\n * Determine if canvas recording is enabled\n */\n public isRecordingCanvas(): boolean {\n return Boolean(this._canvas);\n }\n\n /** Get the replay integration options. */\n public getOptions(): ReplayPluginOptions {\n return this._options;\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n public initializeSampling(previousSessionId?: string): void {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n if (errorSampleRate <= 0 && sessionSampleRate <= 0) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n this._initializeSessionForSampling(previousSessionId);\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n this._handleException(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled === false) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n // If segmentId > 0, it means we've previously already captured this session\n // In this case, we still want to continue in `session` recording mode\n this.recordingMode = this.session.sampled === 'buffer' && this.session.segmentId === 0 ? 'buffer' : 'session';\n\n logInfoNextTick(\n `[Replay] Starting replay in ${this.recordingMode} mode`,\n this._options._experiments.traceInternals,\n );\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (this._isEnabled && this.recordingMode === 'session') {\n throw new Error('Replay recording is already in progress');\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n throw new Error('Replay buffering is in progress, call `flush()` to save the replay');\n }\n\n logInfoNextTick('[Replay] Starting replay in session mode', this._options._experiments.traceInternals);\n\n // Required as user activity is initially set in\n // constructor, so if `start()` is called after\n // session idle expiration, a replay will not be\n // created due to an idle timeout.\n this._updateUserActivity();\n\n const session = loadOrCreateSession(\n {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n },\n );\n\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n public startBuffering(): void {\n if (this._isEnabled) {\n throw new Error('Replay recording is already in progress');\n }\n\n logInfoNextTick('[Replay] Starting replay in buffer mode', this._options._experiments.traceInternals);\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: 0,\n allowBuffering: true,\n },\n );\n\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n public startRecording(): void {\n try {\n const canvasOptions = this._canvas;\n\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n ...(canvasOptions\n ? {\n recordCanvas: canvasOptions.recordCanvas,\n getCanvasManager: canvasOptions.getCanvasManager,\n sampling: canvasOptions.sampling,\n dataURLOptions: canvasOptions.dataURLOptions,\n }\n : {}),\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n public stopRecording(): boolean {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public async stop({ forceFlush = false, reason }: { forceFlush?: boolean; reason?: string } = {}): Promise {\n if (!this._isEnabled) {\n return;\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n\n try {\n logInfo(\n `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`,\n this._options._experiments.traceInternals,\n );\n\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (forceFlush) {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n public pause(): void {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n logInfo('[Replay] Pausing replay', this._options._experiments.traceInternals);\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n public resume(): void {\n if (!this._isPaused || !this._checkSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n logInfo('[Replay] Resuming replay', this._options._experiments.traceInternals);\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public async sendBufferedReplayOrFlush({ continueRecording = true }: SendBufferedReplayOptions = {}): Promise {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n logInfo('[Replay] Converting buffer to session', this._options._experiments.traceInternals);\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // To avoid race conditions where this is called multiple times, we check here again that we are still buffering\n if ((this.recordingMode as ReplayRecordingMode) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n public addUpdate(cb: AddUpdateCallback): void {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n public triggerUserActivity(): void {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._checkSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n public updateUserActivity(): void {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n public conditionalFlush(): Promise {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Flush using debounce flush\n */\n public flush(): Promise {\n return this._debouncedFlush() as Promise;\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n public flushImmediate(): Promise {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() as Promise;\n }\n\n /**\n * Cancels queued up flushes.\n */\n public cancelFlush(): void {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current sesion (=replay) ID */\n public getSessionId(): string | undefined {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n public checkAndHandleExpiredSession(): boolean | void {\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._checkSession()) {\n // Check session handles the refreshing itself\n return false;\n }\n\n return true;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n public setInitialState(): void {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n public throttledAddEvent(\n event: RecordingEvent,\n isCheckout?: boolean,\n ): typeof THROTTLED | typeof SKIPPED | Promise {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n // Return `false` if the event _was_ added, as that means we schedule a flush\n return !addEventSync(this, {\n type: ReplayEventTypeCustom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n public getCurrentRoute(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const lastTransaction = this.lastTransaction || getCurrentScope().getTransaction();\n\n const attributes = (lastTransaction && spanToJSON(lastTransaction).data) || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n if (!lastTransaction || !source || !['route', 'custom'].includes(source)) {\n return undefined;\n }\n\n return spanToJSON(lastTransaction).description;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n private _initializeRecording(): void {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n workerUrl: this._options.workerUrl,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n this._isPaused = false;\n\n this.startRecording();\n }\n\n /** A wrapper to conditionally capture exceptions. */\n private _handleException(error: unknown): void {\n DEBUG_BUILD && logger.error('[Replay]', error);\n\n if (DEBUG_BUILD && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n */\n private _initializeSessionForSampling(previousSessionId?: string): void {\n // Whenever there is _any_ error sample rate, we always allow buffering\n // Because we decide on sampling when an error occurs, we need to buffer at all times if sampling for errors\n const allowBuffering = this._options.errorSampleRate > 0;\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n previousSessionId,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering,\n },\n );\n\n this.session = session;\n }\n\n /**\n * Checks and potentially refreshes the current session.\n * Returns false if session is not recorded.\n */\n private _checkSession(): boolean {\n // If there is no session yet, we do not want to refresh anything\n // This should generally not happen, but to be safe....\n if (!this.session) {\n return false;\n }\n\n const currentSession = this.session;\n\n if (\n shouldRefreshSession(currentSession, {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n })\n ) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._refreshSession(currentSession);\n return false;\n }\n\n return true;\n }\n\n /**\n * Refresh a session with a new one.\n * This stops the current session (without forcing a flush, as that would never work since we are expired),\n * and then does a new sampling based on the refreshed session.\n */\n private async _refreshSession(session: Session): Promise {\n if (!this._isEnabled) {\n return;\n }\n await this.stop({ reason: 'refresh session' });\n this.initializeSampling(session.id);\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n private _addListeners(): void {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n this._performanceCleanupCallback = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n private _removeListeners(): void {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceCleanupCallback) {\n this._performanceCleanupCallback();\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n private _handleVisibilityChange: () => void = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n private _handleWindowBlur: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n /**\n * Handle when page is focused\n */\n private _handleWindowFocus: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n private _handleKeyboardEvent: (event: KeyboardEvent) => void = (event: KeyboardEvent) => {\n handleKeyboardEvent(this, event);\n };\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n private _doChangeToBackgroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n });\n\n if (expired) {\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n private _doChangeToForegroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n logInfo('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n private _updateUserActivity(_lastActivity: number = Date.now()): void {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n private _updateSessionActivity(_lastActivity: number = Date.now()): void {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n private _createCustomBreadcrumb(breadcrumb: ReplayBreadcrumbFrame): void {\n this.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEntries`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n private _addPerformanceEntries(): Promise> {\n const performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n return Promise.all(createPerformanceSpans(this, performanceEntries));\n }\n\n /**\n * Clear _context\n */\n private _clearContext(): void {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n private _updateInitialTimestampFromEventBuffer(): void {\n const { session, eventBuffer } = this;\n if (!session || !eventBuffer) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n private _popEventContext(): PopEventContext {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n private async _runFlush(): Promise {\n const replayId = this.getSessionId();\n\n if (!this.session || !this.eventBuffer || !replayId) {\n DEBUG_BUILD && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n // if this changed in the meanwhile, e.g. because the session was refreshed or similar, we abort here\n if (replayId !== this.getSessionId()) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n const timestamp = Date.now();\n\n // Check total duration again, to avoid sending outdated stuff\n // We leave 30s wiggle room to accomodate late flushing etc.\n // This _could_ happen when the browser is suspended during flushing, in which case we just want to stop\n if (timestamp - this._context.initialTimestamp > this._options.maxReplayDuration + 30_000) {\n throw new Error('Session is too long, not sending replay');\n }\n\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp,\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'sendReplay' });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n private _flush = async ({\n force = false,\n }: {\n /**\n * If true, flush while ignoring the `_isEnabled` state of\n * Replay integration. (By default, flush is noop if integration\n * is stopped).\n */\n force?: boolean;\n } = {}): Promise => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n // should never happen, as we would have bailed out before\n return;\n }\n\n const start = this.session.started;\n const now = Date.now();\n const duration = now - start;\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // If session is too short, or too long (allow some wiggle room over maxReplayDuration), do not send it\n // This _should_ not happen, but it may happen if flush is triggered due to a page activity change or similar\n const tooShort = duration < this._options.minReplayDuration;\n const tooLong = duration > this._options.maxReplayDuration + 5_000;\n if (tooShort || tooLong) {\n logInfo(\n `[Replay] Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\n this._options._experiments.traceInternals,\n );\n\n if (tooShort) {\n this._debouncedFlush();\n }\n return;\n }\n\n const eventBuffer = this.eventBuffer;\n if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {\n logInfo('[Replay] Flushing initial segment without checkout.', this._options._experiments.traceInternals);\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = undefined;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n DEBUG_BUILD && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };\n\n /** Save the session, if it is sticky */\n private _maybeSaveSession(): void {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n private _onMutationHandler = (mutations: unknown[]): boolean => {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'mutationLimit', forceFlush: this.recordingMode === 'session' });\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };\n}\n","type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => unknown;\ntype DebounceOptions = { maxWait?: number };\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nexport function debounce(func: CallbackFunction, wait: number, options?: DebounceOptions): DebouncedCallback {\n let callbackReturnValue: unknown;\n\n let timerId: ReturnType | undefined;\n let maxTimerId: ReturnType | undefined;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc(): unknown {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers(): void {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush(): unknown {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced(): unknown {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n","import { REPLAY_SESSION_KEY, WINDOW } from '../../src/constants';\nimport type { ReplayContainer } from '../../src/types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nexport function clearSession(replay: ReplayContainer): void {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession(): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n","import { getWorkerURL } from '@sentry-internal/replay-worker';\n\nimport type { EventBuffer } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferProxy } from './EventBufferProxy';\n\ninterface CreateEventBufferParams {\n useCompression: boolean;\n workerUrl?: string;\n}\n\n// Treeshakable guard to remove the code of the included compression worker\ndeclare const __SENTRY_EXCLUDE_REPLAY_WORKER__: boolean;\n\n/**\n * Create an event buffer for replays.\n */\nexport function createEventBuffer({\n useCompression,\n workerUrl: customWorkerUrl,\n}: CreateEventBufferParams): EventBuffer {\n if (\n useCompression &&\n // eslint-disable-next-line no-restricted-globals\n window.Worker\n ) {\n const worker = _loadWorker(customWorkerUrl);\n\n if (worker) {\n return worker;\n }\n }\n\n logInfo('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl?: string): EventBufferProxy | void {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n logInfo(`[Replay] Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n logInfo('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n}\n\nfunction _getWorkerUrl(): string {\n if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === 'undefined' || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {\n return getWorkerURL();\n }\n\n return '';\n}\n","import r from\"./worker\";function e(){const e=new Blob([r]);return URL.createObjectURL(e)}export{e as getWorkerURL};\n","export default `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==r||r<0)&&(r=0),(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=[\"unexpected EOF\",\"invalid block type\",\"invalid length/literal\",\"invalid distance\",\"stream finished\",\"no stream handler\",,\"no callback\",\"invalid UTF-8 data\",\"extra field too long\",\"date not in range 1980-2099\",\"filename too long\",\"stream finishing\",\"invalid zip data\"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},A=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},_=function(r,e){for(var i=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=x(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},x=function(t,n,r){return-1==t.s?Math.max(x(t.l,n,r+1),x(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,C)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B255){A(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;A(r,m,Q[et]),m+=R[et],et>3&&(A(r,m,rt>>5&8191),m+=i[et])}else A(r,m,N[rt]),m+=P[rt]}return A(r,m,N[256]),m+P[256]},U=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=U[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=C(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=A[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if(\"function\"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,a=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),s=a.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(a,n),O(a,s-8,r.d()),O(a,s-4,e),a}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),G=\"undefined\"!=typeof TextEncoder&&new TextEncoder,H=\"undefined\"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(r){for(var e=new t(n.length),i=0;i>1)),o=0,f=function(t){s[o++]=t};for(i=0;is.length){var h=new t(o+8+(a-i<<1));h.set(s),s=h}var l=n.charCodeAt(i);l<128||r?f(l):l<2048?(f(192|l>>6),f(128|63&l)):l>55295&&l<57344?(f(240|(l=65536+(1047552&l)|1023&n.charCodeAt(++i))>>18),f(128|l>>12&63),f(128|l>>6&63),f(128|63&l)):(f(224|l>>12),f(128|l>>6&63),f(128|63&l))}return b(s,0,o)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const n=this._hasEvents?\",\":\"\";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push(\"]\",!0);const t=function(t){let n=0;for(let r=0,e=t.length;r{this._deflatedData.push(t)},this.stream=new J(((t,n)=>{this.deflate.push(t,n)})),this.stream.push(\"[\")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener(\"message\",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&\"function\"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n","import type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { getBaseDomBreadcrumb } from './handleDom';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\n/** Handle keyboard events & create breadcrumbs. */\nexport function handleKeyboardEvent(replay: ReplayContainer, event: KeyboardEvent): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nexport function getKeyboardBreadcrumb(event: KeyboardEvent): Breadcrumb | null {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target as HTMLElement) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target as Node, message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target: HTMLElement): boolean {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n","import { consoleSandbox } from '@sentry/utils';\n\nimport type { DeprecatedPrivacyOptions, ReplayIntegrationPrivacyOptions } from '../types';\n\ntype GetPrivacyOptions = Required> &\n Omit;\ninterface GetPrivacyReturn {\n maskTextSelector: string;\n unmaskTextSelector: string;\n blockSelector: string;\n unblockSelector: string;\n ignoreSelector: string;\n\n blockClass?: RegExp;\n maskTextClass?: RegExp;\n}\n\nfunction getOption(\n selectors: string[],\n defaultSelectors: string[],\n deprecatedClassOption?: string | RegExp,\n deprecatedSelectorOption?: string,\n): string {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n });\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nexport function getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}: GetPrivacyOptions): GetPrivacyReturn {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options: GetPrivacyReturn = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n","import { getClient } from '@sentry/core';\nimport type { BrowserClientReplayOptions, Integration, IntegrationFn } from '@sentry/types';\nimport { consoleSandbox, dropUndefinedKeys, isBrowser } from '@sentry/utils';\n\nimport {\n DEFAULT_FLUSH_MAX_DELAY,\n DEFAULT_FLUSH_MIN_DELAY,\n MAX_REPLAY_DURATION,\n MIN_REPLAY_DURATION,\n MIN_REPLAY_DURATION_LIMIT,\n} from './constants';\nimport { ReplayContainer } from './replay';\nimport type {\n RecordingOptions,\n ReplayCanvasIntegrationOptions,\n ReplayConfiguration,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n} from './types';\nimport { getPrivacyOptions } from './util/getPrivacyOptions';\nimport { maskAttribute } from './util/maskAttribute';\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\ntype InitialReplayPluginOptions = Omit &\n Partial>;\n\nexport const replayIntegration = ((options?: ReplayConfiguration) => {\n // eslint-disable-next-line deprecation/deprecation\n return new Replay(options);\n}) satisfies IntegrationFn;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n * @deprecated Use `replayIntegration()` instead.\n */\nexport class Replay implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Replay';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n private readonly _initialOptions: InitialReplayPluginOptions;\n\n private _replay?: ReplayContainer;\n\n public constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n minReplayDuration = MIN_REPLAY_DURATION,\n maxReplayDuration = MAX_REPLAY_DURATION,\n stickySession = true,\n useCompression = true,\n workerUrl,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10_000,\n\n slowClickTimeout = 7_000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n maskAttributes = ['title', 'placeholder'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n }: ReplayConfiguration = {}) {\n // eslint-disable-next-line deprecation/deprecation\n this.name = Replay.id;\n\n const privacyOptions = getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n });\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n maskAttributeFn: (key: string, value: string, el: HTMLElement): string =>\n maskAttribute({\n maskAttributes,\n maskAllText,\n privacyOptions,\n key,\n value,\n el,\n }),\n\n ...privacyOptions,\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n errorHandler: (err: Error & { __rrweb__?: boolean }) => {\n try {\n err.__rrweb__ = true;\n } catch (error) {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n workerUrl,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n protected get _isInitialized(): boolean {\n return _initialized;\n }\n\n /** Update _isInitialized */\n protected set _isInitialized(value: boolean) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n public setupOnce(): void {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // Once upon a time, we tried to create a transaction in `setupOnce` and it would\n // potentially create a transaction before some native SDK integrations have run\n // and applied their own global event processor. An example is:\n // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n //\n // So we call `this._initialize()` in next event loop as a workaround to wait for other\n // global event processors to finish. This is no longer needed, but keeping it\n // here to avoid any future issues.\n setTimeout(() => this._initialize());\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n public startBuffering(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public stop(): Promise {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop({ forceFlush: this._replay.recordingMode === 'session' });\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public flush(options?: SendBufferedReplayOptions): Promise {\n if (!this._replay || !this._replay.isEnabled()) {\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n public getReplayId(): string | undefined {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n\n /**\n * Initializes replay.\n */\n protected _initialize(): void {\n if (!this._replay) {\n return;\n }\n\n // We have to run this in _initialize, because this runs in setTimeout\n // So when this runs all integrations have been added\n // Before this, we cannot access integrations on the client,\n // so we need to mutate the options here\n this._maybeLoadFromReplayCanvasIntegration();\n\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n private _setup(): void {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n\n /** Get canvas options from ReplayCanvas integration, if it is also added. */\n private _maybeLoadFromReplayCanvasIntegration(): void {\n // To save bundle size, we skip checking for stuff here\n // and instead just try-catch everything - as generally this should all be defined\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n try {\n const client = getClient()!;\n const canvasIntegration = client.getIntegrationByName!('ReplayCanvas') as Integration & {\n getOptions(): ReplayCanvasIntegrationOptions;\n };\n if (!canvasIntegration) {\n return;\n }\n\n this._replay!['_canvas'] = canvasIntegration.getOptions();\n } catch {\n // ignore errors here\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions: InitialReplayPluginOptions): ReplayPluginOptions {\n const client = getClient();\n const opt = client && (client.getOptions() as BrowserClientReplayOptions);\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n });\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n });\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers: string[]): string[] {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n","import type { getPrivacyOptions } from './getPrivacyOptions';\n\ninterface MaskAttributeParams {\n maskAttributes: string[];\n maskAllText: boolean;\n privacyOptions: ReturnType;\n key: string;\n value: string;\n el: HTMLElement;\n}\n\n/**\n * Masks an attribute if necessary, otherwise return attribute value as-is.\n */\nexport function maskAttribute({\n el,\n key,\n maskAttributes,\n maskAllText,\n privacyOptions,\n value,\n}: MaskAttributeParams): string {\n // We only mask attributes if `maskAllText` is true\n if (!maskAllText) {\n return value;\n }\n\n // unmaskTextSelector takes precendence\n if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) {\n return value;\n }\n\n if (\n maskAttributes.includes(key) ||\n // Need to mask `value` attribute for `` if it's a button-like\n // type\n (key === 'value' && el.tagName === 'INPUT' && ['submit', 'button'].includes(el.getAttribute('type') || ''))\n ) {\n return value.replace(/[\\S]/g, '*');\n }\n\n return value;\n}\n","import type { ConsoleLevel } from '@sentry/types';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type { DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\nimport { serializeMetricBuckets } from './utils';\n\n/**\n * Create envelope from a metric aggregate.\n */\nexport function createMetricEnvelope(\n metricBucketItems: Array,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): StatsdEnvelope {\n const headers: StatsdEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const item = createMetricEnvelopeItem(metricBucketItems);\n return createEnvelope(headers, [item]);\n}\n\nfunction createMetricEnvelopeItem(metricBucketItems: MetricBucketItem[]): StatsdItem {\n const payload = serializeMetricBuckets(metricBucketItems);\n const metricHeaders: StatsdItem[0] = {\n type: 'statsd',\n length: payload.length,\n };\n return [metricHeaders, payload];\n}\n","import type { MeasurementUnit, MetricBucketItem, Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport type { MetricType } from './types';\n\n/**\n * Generate bucket key from metric properties.\n */\nexport function getBucketKey(\n metricType: MetricType,\n name: string,\n unit: MeasurementUnit,\n tags: Record,\n): string {\n const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));\n return `${metricType}${name}${unit}${stringifiedTags}`;\n}\n\n/* eslint-disable no-bitwise */\n/**\n * Simple hash function for strings.\n */\nexport function simpleHash(s: string): number {\n let rv = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n rv = (rv << 5) - rv + c;\n rv &= rv;\n }\n return rv >>> 0;\n}\n/* eslint-enable no-bitwise */\n\n/**\n * Serialize metrics buckets into a string based on statsd format.\n *\n * Example of format:\n * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677\n * Segments:\n * name: metric.name\n * unit: second\n * value: [1, 1.2]\n * type of metric: d (distribution)\n * tags: { a: value, b: anothervalue }\n * timestamp: 12345677\n */\nexport function serializeMetricBuckets(metricBucketItems: MetricBucketItem[]): string {\n let out = '';\n for (const item of metricBucketItems) {\n const tagEntries = Object.entries(item.tags);\n const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';\n out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\\n`;\n }\n return out;\n}\n\n/** Sanitizes units */\nexport function sanitizeUnit(unit: string): string {\n return unit.replace(/[^\\w]+/gi, '_');\n}\n\n/** Sanitizes metric keys */\nexport function sanitizeMetricKey(key: string): string {\n return key.replace(/[^\\w\\-.]+/gi, '_');\n}\n\nfunction sanitizeTagKey(key: string): string {\n return key.replace(/[^\\w\\-./]+/gi, '');\n}\n\nconst tagValueReplacements: [string, string][] = [\n ['\\n', '\\\\n'],\n ['\\r', '\\\\r'],\n ['\\t', '\\\\t'],\n ['\\\\', '\\\\\\\\'],\n ['|', '\\\\u{7c}'],\n [',', '\\\\u{2c}'],\n];\n\nfunction getCharOrReplacement(input: string): string {\n for (const [search, replacement] of tagValueReplacements) {\n if (input === search) {\n return replacement;\n }\n }\n\n return input;\n}\n\nfunction sanitizeTagValue(value: string): string {\n return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), '');\n}\n\n/**\n * Sanitizes tags.\n */\nexport function sanitizeTags(unsanitizedTags: Record): Record {\n const tags: Record = {};\n for (const key in unsanitizedTags) {\n if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {\n const sanitizedKey = sanitizeTagKey(key);\n tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));\n }\n }\n return tags;\n}\n","import type { Scope } from '@sentry/core';\nimport { applySdkMetadata } from '@sentry/core';\nimport { BaseClient } from '@sentry/core';\nimport type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n ParameterizedString,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(options, 'browser', ['browser'], sdkSource);\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n}\n","import type { Options } from '@sentry/types';\nimport { SDK_VERSION } from '../version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: Options, name: string, names = [name], source = 'npm'): void {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n SentryError,\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import { SentryError } from './error';\nimport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n DEBUG_BUILD && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/**\n * Deduplication filter.\n * @deprecated Use `dedupeIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Dedupe = convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n>;\n\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport { functionToStringIntegration, inboundFiltersIntegration } from '@sentry/core';\nimport {\n captureSession,\n getClient,\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n startSession,\n} from '@sentry/core';\nimport type { Integration, Options, UserFeedback } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n logger,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs';\nimport { dedupeIntegration } from './integrations/dedupe';\nimport { globalHandlersIntegration } from './integrations/globalhandlers';\nimport { httpContextIntegration } from './integrations/httpcontext';\nimport { linkedErrorsIntegration } from './integrations/linkederrors';\nimport { browserApiErrorsIntegration } from './integrations/trycatch';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\n/** @deprecated Use `getDefaultIntegrations(options)` instead. */\nexport const defaultIntegrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n];\n\n/** Get the default integrations for the browser SDK. */\nexport function getDefaultIntegrations(_options: Options): Integration[] {\n // We return a copy of the defaultIntegrations here to avoid mutating this\n return [\n // eslint-disable-next-line deprecation/deprecation\n ...defaultIntegrations,\n ];\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\ntype NewReportDialogOptions = ReportDialogOptions & { eventId: string }; // eslint-disable-line\n\ninterface ShowReportDialogFunction {\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\n (options: NewReportDialogOptions): void;\n\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n *\n * @deprecated Please always pass an `options` argument with `eventId`. The `hub` argument will not be used in the next version of the SDK.\n */\n // eslint-disable-next-line deprecation/deprecation\n (options?: ReportDialogOptions, hub?: Hub): void;\n}\n\nexport const showReportDialog: ShowReportDialogFunction = (\n // eslint-disable-next-line deprecation/deprecation\n options: ReportDialogOptions = {},\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub = getCurrentHub(),\n) => {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n // eslint-disable-next-line deprecation/deprecation\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event: MessageEvent): void => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n};\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import {\n captureException,\n captureMessage,\n convertIntegrationFnToClass,\n defineIntegration,\n getClient,\n withScope,\n} from '@sentry/core';\nimport type { CaptureContext, Client, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport {\n CONSOLE_LEVELS,\n GLOBAL_OBJ,\n addConsoleInstrumentationHandler,\n addExceptionMechanism,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\ninterface CaptureConsoleOptions {\n levels?: string[];\n}\n\nconst INTEGRATION_NAME = 'CaptureConsole';\n\nconst _captureConsoleIntegration = ((options: CaptureConsoleOptions = {}) => {\n const levels = options.levels || CONSOLE_LEVELS;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.includes(level)) {\n return;\n }\n\n consoleHandler(args, level);\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);\n\n/**\n * Send Console API calls as Sentry Events.\n * @deprecated Use `captureConsoleIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const CaptureConsole = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n captureConsoleIntegration,\n) as IntegrationClass void }> & {\n new (options?: { levels?: string[] }): Integration;\n};\n\nfunction consoleHandler(args: unknown[], level: string): void {\n const captureContext: CaptureContext = {\n level: severityLevelFromString(level),\n extra: {\n arguments: args,\n },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'console';\n\n addExceptionMechanism(event, {\n handled: false,\n type: 'console',\n });\n\n return event;\n });\n\n if (level === 'assert' && args[0] === false) {\n const message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n captureMessage(message, captureContext);\n return;\n }\n\n const error = args.find(arg => arg instanceof Error);\n if (level === 'error' && error) {\n captureException(error, captureContext);\n return;\n }\n\n const message = safeJoin(args, ' ');\n captureMessage(message, captureContext);\n });\n}\n","import app from 'flarum/forum/app';\n\nimport {\n BrowserClient,\n defaultStackParser,\n getCurrentHub,\n makeFetchTransport,\n showReportDialog,\n Breadcrumbs,\n GlobalHandlers,\n InboundFilters,\n FunctionToString,\n LinkedErrors,\n HttpContext,\n TryCatch,\n BrowserTracing,\n Replay,\n} from '@sentry/browser';\n\nimport { CaptureConsole } from '@sentry/integrations';\n\nconst integrations = [\n new InboundFilters(),\n new FunctionToString(),\n new TryCatch(),\n new GlobalHandlers({\n onerror: true,\n onunhandledrejection: true,\n }),\n new Breadcrumbs({\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n }),\n new LinkedErrors({\n key: 'cause',\n limit: 5,\n }),\n new HttpContext(),\n];\n\nif (__SENTRY_TRACING__) {\n integrations.push(new BrowserTracing());\n}\n\nif (__SENTRY_SESSION_REPLAY__) {\n integrations.push(new Replay());\n}\n\nconst createClient = (config) =>\n new BrowserClient({\n dsn: config.dsn,\n\n transport: makeFetchTransport,\n stackParser: defaultStackParser,\n\n beforeSend: (event) => {\n event.logger = 'javascript';\n\n if (config.scrubEmails && event.user?.email) {\n delete event.user.email;\n }\n\n if (config.showFeedback && event.exception) {\n showReportDialog({ eventId: event.event_id, user: Sentry.getUserData('name') });\n }\n\n return event;\n },\n\n tracesSampleRate: config.tracesSampleRate,\n replaysSessionSampleRate: config.replaysSessionSampleRate,\n replaysOnErrorSampleRate: config.replaysOnErrorSampleRate,\n\n integrations: [...integrations, config.captureConsole && new CaptureConsole()].filter(Boolean),\n });\n\nwindow.Sentry = { createClient, getCurrentHub, showReportDialog };\n\nwindow.Sentry.getUserData = (nameAttr = 'username') => {\n /** @type {Sentry.User} */\n let userData = {};\n\n // Depending on when the error occurs, `app` might not be defined\n if (app) {\n const user = app.session?.user;\n\n if (app.session && user && user.id() != 0) {\n userData = {\n ip_address: '{{auto}}',\n id: user.id(),\n [nameAttr]: user.username(),\n };\n\n if (!app.data['fof-sentry.scrub-emails']) {\n userData.email = user.email();\n }\n } else if (app.data.session && app.data.session.userId != 0) {\n userData = {\n id: app.data.session.userId,\n };\n }\n }\n\n return userData;\n};\n\napp.initializers.add('fof/sentry', () => {\n getCurrentHub().setUser(Sentry.getUserData());\n});\n"],"names":["isNodeEnv","__SENTRY_BROWSER_BUNDLE__","Object","prototype","toString","call","process","_typeof","require","_regeneratorRuntime","module","exports","__esModule","Op","hasOwn","hasOwnProperty","defineProperty","obj","key","desc","value","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","fn","arg","type","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","result","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","undefined","done","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","methodName","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","runtime","regeneratorRuntime","accidentalStrictMode","globalThis","Function","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","n","getter","d","a","definition","o","get","g","e","window","hmd","children","set","prop","r","flarum","core","compat","DEBUG_BUILD","__SENTRY_DEBUG__","isGlobalObj","Math","GLOBAL_OBJ","global","getGlobalObject","getGlobalSingleton","creator","gbl","__SENTRY__","CONSOLE_LEVELS","originalConsoleMethods","consoleSandbox","callback","console","wrappedFuncs","wrappedLevels","level","originalConsoleMethod","enabled","logger","enable","disable","isEnabled","_len","arguments","args","Array","_key","_GLOBAL_OBJ$console","apply","PREFIX","concat","_extends","assign","bind","target","source","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isString","isParameterizedString","isPrimitive","isPlainObject","isEvent","Event","isThenable","Boolean","base","_e","isVueViewModel","__isVue","_isVue","WINDOW","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","options","nextStr","currentElem","out","height","len","keyAttrs","isArray","maxStringLength","_htmlElementAsString","separator","parentNode","join","_oO","el","classes","attr","tagName","HTMLElement","dataset","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","keyAttrPair","split","allowedAttrs","getComponentName","truncate","str","max","safeJoin","input","delimiter","output","String","stringMatchesSomePattern","testString","patterns","requireExactStringMatch","some","pattern","test","includes","isMatchingPattern","fill","replacementFactory","original","wrapped","markFunctionWrapped","addNonEnumerableProperty","o_O","log","proto","getOriginalFunction","func","__sentry_original__","convertToPlainObject","message","stack","getOwnProperties","newObj","serializeEventTarget","currentTarget","CustomEvent","detail","Element","extractedProps","property","dropUndefinedKeys","inputValue","_dropUndefinedKeys","Map","memoizationMap","isPojo","memoVal","returnValue","_i","_Object$keys","item","uuid4","crypto","msCrypto","getRandomByte","random","randomUUID","replace","getRandomValues","typedArray","Uint8Array","_","c","getFirstException","event","getEventDescription","eventId","event_id","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","data","checkOrSetAlreadyCaught","__sentry_captured__","States","resolvedSyncPromise","SyncPromise","rejectedSyncPromise","reason","executor","__init","__init2","__init3","__init4","_state","PENDING","_handlers","_resolve","_reject","_proto","onfulfilled","onrejected","_this","_executeHandlers","onfinally","_this2","isRejected","_this3","_setResult","RESOLVED","_this4","REJECTED","_this5","_value","_this6","cachedHandlers","handler","getGlobalEventProcessors","addGlobalEventProcessor","notifyEventProcessors","processors","hint","index","processor","final","ONE_SECOND_IN_MS","dateTimestampInSeconds","Date","now","timestampInSeconds","performance","approxStartingTimeOrigin","timeOrigin","createUnixTimestampInSecondsFunc","browserPerformanceTimeOrigin","threshold","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","DEFAULT_ENVIRONMENT","updateSession","session","user","ipAddress","ip_address","did","email","username","timestamp","abnormal_mechanism","ignoreDuration","sid","init","started","duration","release","environment","userAgent","errors","status","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","defaultFunctionName","getFunctionName","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","maxSize","normalized","encodeURI","utf8Length","JSON","stringify","memo","hasWeakSet","inner","WeakSet","has","add","splice","_memo","memoize","unmemoize","stringified","_events","document","objName","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","toJSON","numAdded","visitable","visitKey","visitValue","BAGGAGE_HEADER_NAME","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","dynamicSamplingContextToSentryBaggageHeader","dynamicSamplingContext","entries","reduce","baggageHeader","_ref4","currentIndex","objectKey","objectValue","baggageEntry","encodeURIComponent","newBaggageHeader","warn","objectToBaggageHeader","acc","_ref2","dscKey","dscValue","baggageHeaderToObject","keyOrValue","decodeURIComponent","trim","_ref3","TRACEPARENT_REGEXP","RegExp","propagationContextFromHeaders","sentryTrace","baggage","traceparentData","traceparent","parentSampled","matches","match","traceId","parentSpanId","extractTraceparentData","baggageObject","curr","currBaggageObject","_ref","baggageHeaderToDynamicSamplingContext","substring","spanId","sampled","dsc","generateSentryTraceHeader","sampledString","TRACE_FLAG_SAMPLED","spanToTraceContext","span","_span$spanContext","spanContext","span_id","trace_id","_spanToJSON","spanToJSON","op","parent_span_id","tags","origin","spanToTraceHeader","_span$spanContext2","spanIsSampled","spanTimeInputToSeconds","ensureTimestampInSeconds","getTime","getSpanJSON","spanIsSpanClass","traceFlags","debugIdStackParserCache","WeakMap","captureContextKeys","captureEvent","getCurrentHub","addBreadcrumb","breadcrumb","getClient","getCurrentScope","getScope","getRootSpan","transaction","getDynamicSamplingContextFromClient","client","scope","getOptions","public_key","getDsn","publicKey","user_segment","getUser","segment","emit","getDynamicSamplingContextFromSpan","txn","v7FrozenDsc","_frozenDynamicSamplingContext","_txn$metadata","metadata","maybeSampleRate","sampleRate","sample_rate","jsonSpan","description","applyScopeDataToEvent","fingerprint","breadcrumbs","sdkProcessingMetadata","extra","contexts","transactionName","cleanedExtra","cleanedTags","cleanedUser","cleanedContexts","applyDataToEvent","trace","rootSpan","applySpanToEvent","maybeArray","applyFingerprintToEvent","mergedBreadcrumbs","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","eventProcessors","attachments","propagationContext","mergeAndOverwriteScopeData","mergeVal","globalScope","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","_propagationContext","generatePropagationContext","clone","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","_client","setClient","addScopeListener","addEventProcessor","setUser","_notifyScopeListeners","getRequestSession","setRequestSession","requestSession","setTags","setTag","_extends2","setExtras","extras","setExtra","_extends3","setFingerprint","setLevel","setTransactionName","setContext","setSpan","getSpan","getTransaction","setSession","getSession","update","captureContext","scopeToMerge","scopeData","getScopeData","scopeContext","clear","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","getAttachments","clearAttachments","applyToEvent","additionalEventProcessors","setSDKProcessingMetadata","newData","setPropagationContext","getPropagationContext","captureException","syntheticException","originalException","captureMessage","SDK_VERSION","API_VERSION","parseFloat","Hub","isolationScope","_version","assignedScope","assignedIsolationScope","_stack","bindClient","_isolationScope","isOlderThan","version","top","getStackTop","setupIntegrations","pushScope","getStack","popScope","withScope","maybePromiseResult","res","getIsolationScope","_lastEventId","lastEventId","_this$getStackTop","_ref$beforeBreadcrumb","beforeBreadcrumb","_ref$maxBreadcrumbs","finalBreadcrumb","configureScope","_this$getStackTop2","run","oldHub","makeMain","getIntegration","integration","startTransaction","customSamplingContext","_callExtensionMethod","traceHeaders","captureSession","endSession","_sendSessionUpdate","closeSession","startSession","_this$getStackTop3","_ref2$environment","navigator","startingTime","toISOString","attrs","user_agent","sessionToJSON","makeSession","currentSession","shouldSendDefaultPii","sendDefaultPii","_this$getStackTop4","sentry","getMainCarrier","extensions","hub","registry","getHubFromCarrier","setHubOnCarrier","acs","carrier","getGlobalHub","installedIntegrations","afterSetupIntegrations","integrations","_step","_iterator","_createForOfIteratorHelperLoose","afterAllSetup","setupIntegration","integrationIndex","indexOf","setupOnce","setup","on","preprocessEvent","processEvent","convertIntegrationFnToClass","originalFunctionToString","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","INTEGRATION_NAME","inboundFiltersIntegration","_hint","clientOptions","mergedOptions","internalOptions","allowUrls","denyUrls","ignoreErrors","disableErrorDefaults","ignoreTransactions","disableTransactionDefaults","ignoreInternal","_mergeOptions","_isSentryError","lastException","possibleMessages","_getPossibleEventMessages","_isIgnoredError","_isIgnoredTransaction","url","_getEventFilterUrl","_isDeniedUrl","_isAllowedUrl","_shouldDropEvent","InboundFilters","frames","stacktrace","frame","filename","_getLastValidUrl","oO","SETUP_CLIENTS","functionToStringIntegration","originalFunction","FunctionToString","ignoreOnError","shouldIgnoreOnError","before","wrapper","__sentry_wrapped__","sentryWrapped","wrappedArguments","ex","setTimeout","rest","hintIsScopeOrFunction","hintIsScopeContext","parseEventHintOrCaptureContext","getOwnPropertyDescriptor","DEFAULT_EVENT_TARGET","browserApiErrorsIntegration","_options","XMLHttpRequest","eventTarget","requestAnimationFrame","setInterval","_wrapTimeFunction","_wrapRAF","_wrapXHR","eventTargetOption","_wrapEventTarget","TryCatch","originalCallback","function","originalSend","xhr","wrapOptions","_len2","_key2","globalObject","eventName","handleEvent","originalRemoveEventListener","wrappedEventHandler","originalEventHandler","handlers","instrumented","addHandler","maybeInstrument","instrumentFn","triggerHandlers","typeHandlers","_oldOnErrorHandler","addGlobalErrorInstrumentationHandler","instrumentError","onerror","msg","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","addGlobalUnhandledRejectionInstrumentationHandler","instrumentUnhandledRejection","onunhandledrejection","exceptionFromError","stackParser","parseStackFrames","extractMessage","eventFromError","popSize","framesToPop","reactMinifiedRegexp","getPopSize","eventFromUnknownInput","attachStacktrace","isUnhandledRejection","domException","eventFromString","code","normalizeDepth","getNonErrorObjectExceptionValue","__serialized__","eventFromPlainObject","synthetic","__sentry_template_string__","__sentry_template_values__","logentry","params","maxLength","sort","includedKeys","serialized","extractExceptionKeysForMessage","captureType","getObjectClassName","globalHandlersIntegration","stackTraceLimit","_getOptions","groups","_enhanceEventWithInitialFrame","_eventFromIncompleteOnError","_installGlobalOnErrorHandler","globalHandlerLog","_getOptions2","e2","_getUnhandledRejectionError","_installGlobalOnUnhandledRejectionHandler","GlobalHandlers","ev","ev0","ev0s","ev0sf","colno","parseInt","lineno","location","href","getLocationHref","in_app","instrumentConsole","debounceTimerID","lastCapturedEventType","lastCapturedEventTargetId","DEBOUNCE_DURATION","instrumentDOM","triggerDOMHandler","globalDOMEventHandler","makeDOMEventHandler","addEventListener","originalAddEventListener","listener","__sentry_instrumentation_handlers__","handlerForType","refCount","globalListener","getEventTarget","eventType","isContentEditable","shouldSkipDOMEvent","_sentryId","isSimilarToLastCapturedEvent","clearTimeout","SENTRY_XHR_DATA_KEY","addXhrInstrumentationHandler","instrumentXHR","xhrproto","originalOpen","startTimestamp","toUpperCase","parseUrl","request_headers","__sentry_own_request__","onreadystatechangeHandler","xhrInfo","readyState","status_code","endTimestamp","onreadystatechange","readyStateArgs","_len3","setRequestHeaderArgs","_key3","header","sentryXhrData","_len4","_key4","body","isNativeFetch","addFetchInstrumentationHandler","instrumentFetch","EdgeRuntime","Headers","Request","Response","supportsFetch","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","supportsNativeFetch","originalFetch","_parseFetchArgs","fetchArgs","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","response","resource","lastHref","addHistoryInstrumentationHandler","instrumentHistory","isChromePackagedApp","chromeVar","chrome","app","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","to","from","historyReplacementFunction","originalHistoryFunction","validSeverityLevels","query","fragment","host","path","protocol","search","hash","relative","MAX_ALLOWED_STRING_LENGTH","breadcrumbsIntegration","dom","category","_getConsoleBreadcrumbHandler","addClickKeypressInstrumentationHandler","componentName","serializeAttribute","element","_isEvent","_getDomBreadcrumbHandler","_getXhrBreadcrumbHandler","_getFetchBreadcrumbHandler","parsedLoc","parsedFrom","parsedTo","_getHistoryBreadcrumbHandler","_getSentryBreadcrumbHandler","Breadcrumbs","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","parser","maxValueLimit","limit","exceptions","maxValueLength","aggregateExceptionsFromError","prevExceptions","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","childError","is_exception_group","exception_id","parentId","parent_id","SPAN_METRIC_SUMMARY","linkedErrorsIntegration","LinkedErrors","httpContextIntegration","request","referrer","headers","Referer","HttpContext","_assertThisInitialized","ReferenceError","_setPrototypeOf","p","_inheritsLoose","subClass","superClass","_defineProperties","props","descriptor","prim","toPrimitive","_createClass","Constructor","protoProps","staticProps","getMetricSummaryJsonForSpan","storage","getMetricStorageForSpan","_step$value$","exportKey","summary","SpanStatus","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","setHttpStatus","httpStatus","setData","spanStatus","getSpanStatusFromHttpCode","setStatus","SpanRecorder","maxlen","_maxlen","spans","spanRecorder","Span","_traceId","_spanId","_startTime","instrumenter","_attributes","setAttributes","attributes","_name","_parentSpanId","_sampled","_status","_endTime","exclusiveTime","_exclusiveTime","_measurements","measurements","_proto2","startChild","childSpan","logMessage","_logMessage","_extends4","setAttribute","setName","updateName","isSuccess","end","toTraceparent","toContext","_getData","updateWithContext","getTraceContext","start_timestamp","_metrics_summary","profile_id","exclusive_time","isRecording","hasData","hasAttributes","string","startTime","endTime","hasTracingEnabled","maybeOptions","enableTracing","startInactiveSpan","ctx","normalizeContext","parentSpan","onlyIfParent","temporaryScope","forceTransaction","_parentSpan$spanConte","_isolationScope$getPr","ISOLATION_SCOPE_ON_START_SPAN_FIELD","SCOPE_ON_START_SPAN_FIELD","setCapturedScopesOnSpan","createChildSpanOrTransaction","Transaction","_Span","transactionContext","_hub","_metadata","_trimEnd","trimEnd","incomingDynamicSamplingContext","initSpanRecorder","setMeasurement","unit","setMetadata","newMetadata","timestampInS","_finishTransaction","getDynamicSamplingContext","setHub","getProfileId","recordDroppedEvent","finishedSpans","endTimes","current","_getCapturedScopesOnS","capturedSpanScope","capturedSpanIsolationScope","transaction_info","newName","spanMetadata","TRACING_DEFAULTS","idleTimeout","finalTimeout","heartbeatInterval","IDLE_TRANSACTION_FINISH_REASONS","IdleTransactionSpanRecorder","_SpanRecorder","_pushActivity","_popActivity","transactionSpanId","originalEnd","IdleTransaction","_Transaction","_idleHub","_idleTimeout","_finalTimeout","_heartbeatInterval","_onScope","delayAutoFinishUntilSignal","activities","_heartbeatCounter","_finished","_idleTimeoutCanceledPermanently","_beforeFinishCallbacks","_finishReason","_autoFinishAllowed","_restartIdleTimeout","endTimestampInS","spanStartedBeforeTransactionFinish","timeoutWithMarginOfError","spanEndedBeforeFinalTimeout","stringifiedSpan","registerBeforeFinishCallback","_pingHeartbeat","cancelIdleTimeout","_temp","restartOnChildSpanChange","_idleTimeoutID","setFinishReason","sendAutoFinishSignal","_beat","heartbeatString","_prevHeartbeatString","_this7","getActiveTransaction","maybeHub","errorsInstrumented","errorCallback","activeTransaction","sampleTransaction","samplingContext","Number","tracesSampler","tracesSampleRate","isValidSampleRate","rate","_startTransaction","configInstrumenter","transactionInstrumenter","_experiments","maxSpans","startIdleTransaction","onScope","tag","po","bindReporter","metric","reportAllChanges","prevValue","delta","forceReport","getNavigationEntry","__WEB_VITALS_POLYFILL__","getEntriesByType","navigation","navigationEntry","entryType","getNavigationEntryFromPerformanceTiming","getActivationStart","navEntry","activationStart","initMetric","navigationType","prerendering","rating","floor","observe","opts","PerformanceObserver","supportedEntryTypes","list","getEntries","buffered","onHidden","cb","once","onHiddenOrPageHide","visibilityState","removeEventListener","onCLS","onReport","report","sessionValue","sessionEntries","handleEntries","hadRecentInput","firstSessionEntry","lastSessionEntry","stopListening","takeRecords","firstHiddenTime","getVisibilityWatcher","Infinity","timeStamp","onFID","visibilityWatcher","handleEntry","processingStart","disconnect","interactionCountEstimate","minKnownInteractionId","maxKnownInteractionId","updateEstimate","interactionId","min","initInteractionCountPolyfill","durationThreshold","getInteractionCountForNavigation","interactionCount","longestInteractionList","longestInteractionMap","processEntry","minLongestInteraction","existingInteraction","latency","interaction","b","onINP","prevEntry","candidateInteractionIndex","inp","reportedMetricIDs","onLCP","lastEntry","capture","whenReady","onTTFB","responseStart","_previousCls","_previousFid","_previousLcp","_previousTtfb","_previousInp","addPerformanceInstrumentationHandler","instrumentPerformanceObserver","getCleanupCallback","instrumentCls","instrumentFid","instrumentLcp","instrumentTtfb","instrumentInp","addMetricObserver","previousValue","stopOnCallback","DSN_REGEX","dsnToString","dsn","withPassword","pass","port","projectId","dsnFromComponents","components","makeDsn","exec","_match$slice","_match$slice$","_match$slice$2","projectMatch","dsnFromString","find","component","isValidProtocol","validateDsn","createEnvelope","items","forEachEnvelopeItem","envelope","envelopeItem","encodeUTF8","textEncoder","TextEncoder","encode","serializeEnvelope","envHeaders","parts","append","_step2","_iterator2","itemHeaders","payload","stringifiedPayload","buffers","_step3","totalLength","buf","merged","offset","_iterator3","buffer","concatBuffers","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","replay_event","replay_recording","check_in","feedback","statsd","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","sdk","_metadataOrEvent$sdk","createSpanItem","isMeasurementValue","isFinite","_startChild","excluded","sourceKeys","_objectWithoutPropertiesLoose","_excluded","MAX_INT_AS_BYTES","msToSec","time","getBrowserPerformanceAPI","_lcpEntry","_clsEntry","_performanceCursor","startTrackingWebVitals","fidCallback","_ref5","clsCallback","lcpCallback","addLcpInstrumentationHandler","ttfbCallback","_ref6","INP_ENTRY_MAP","click","pointerdown","pointerup","mousedown","mouseup","touchstart","touchend","mouseover","mouseout","mouseenter","mouseleave","pointerover","pointerout","pointerenter","pointerleave","dragstart","dragend","drag","dragenter","dragleave","dragover","drop","keydown","keyup","keypress","_addPerformanceNavigationTiming","eventEnd","start","setResourceEntrySizeData","dataKey","entryVal","DEFAULT_TRACE_PROPAGATION_TARGETS","defaultRequestInstrumentationOptions","traceFetch","traceXHR","enableHTTPTimings","tracingOrigins","tracePropagationTargets","instrumentOutgoingRequests","_traceFetch$traceXHR$","shouldCreateSpanForRequest","shouldCreateSpan","shouldAttachHeadersWithTargets","shouldAttachHeaders","createdSpan","spanOrigin","shouldCreateSpanResult","_handlerData$fetchDat","fullUrl","URL","getFullURL","__span","requestSpan","sentryTraceHeader","sentryBaggageHeader","newHeaders","existingBaggageHeader","newBaggageHeaders","addTracingHeadersToFetchRequest","contentLength","contentLengthNum","endSpan","instrumentFetchRequest","addHTTPTimings","__sentry_xhr_span_id__","setRequestHeader","setHeaderOnXhr","xhrCallback","cleanup","nextHopProtocol","initiatorType","isPerformanceResourceTiming","endsWith","resourceTiming","_extractNetworkProtoc","char","_nextHopProtocol$spli","extractNetworkProtocol","timingSpanData","getAbsoluteTime","redirectStart","fetchStart","domainLookupStart","domainLookupEnd","connectStart","secureConnectionStart","connectEnd","requestStart","responseEnd","resourceTimingEntryToSpanData","DEFAULT_BROWSER_TRACING_OPTIONS","markBackgroundTransactions","routingInstrumentation","customStartTransaction","startTransactionOnPageLoad","startTransactionOnLocationChange","startingUrl","pathname","enableLongTask","enableInp","interactionsSampleRate","BrowserTracing","_hasSetTracePropagationTargets","_collectWebVitals","_interactionIdToRouteNameMapping","interactionIdtoRouteNameMapping","inpCallback","interactionIdToRouteNameMapping","_ref7","interactionType","routeName","parentContext","replayId","userDisplay","profileId","replay_id","getSampleRate","sent_at","transport","getTransport","send","_trackINP","startTrackingINP","enableInteractions","_latestRoute","_getCurrentHub","_this$options","instrumentRouting","clientOptionsTracePropagationTargets","_createRouteTransaction","onStartRouteTransaction","statusType","_registerInteractionListener","_registerInpInteractionListener","expandedContext","_this$options2","beforeNavigate","isPageloadTransaction","_propagationContextFr","getMetaContent","modifiedContext","finalContext","idleTransaction","performanceEntries","transactionStartTime","_addRequest","_addNavigationSpans","measureStartTimestamp","measureEndTimestamp","_addMeasureSpans","firstHidden","shouldRecord","resourceUrl","parsedUrl","renderBlockingStatus","_addResourceSpans","connection","effectiveType","rtt","deviceMemory","hardwareConcurrency","_trackNavigator","_addTtfbRequestTimeToMeasurements","oldValue","measurementTimestamp","normalizedValue","fidMark","cls","measurementName","size","sources","node","_tagMetricInfo","addPerformanceEntries","inflightInteractionTransaction","registerInteractionTransaction","_data","_this3$options","currentTransaction","getSource","replay","getIntegrationByName","getReplayId","currentScope","isPerformanceEventTiming","minInteractionId","metaName","selector","metaTag","querySelector","sourceFromAttributes","sourceFromData","sourceFromMetadata","asyncGeneratorStep","gen","_next","_throw","_asyncToGenerator","_getPrototypeOf","_construct","Parent","Class","Reflect","construct","sham","Proxy","valueOf","isNativeReflectConstruct","instance","_wrapNativeSuper","_cache","Wrapper","_optionalChain","ops","lastAccessLHS","makeLogger","isSyntheticEvent","prepareEvent","_options$normalizeDep","_options$normalizeMax","normalizeMaxBreadth","prepared","dist","_options$maxValueLeng","applyClientOptions","integrationNames","applyIntegrationsMetadata","debugIdStackFramesCache","debugIdMap","_sentryDebugIds","cachedDebugIdStackFrameCache","filenameDebugIdMap","debugIdStackTrace","parsedStack","cachedParsedStack","stackFrame","debug_id","applyDebugIds","finalScope","getFinalScope","clientEventProcessors","getEventProcessors","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","normalizeEvent","removeTrailingSlash","DEFAULT_RETRY_AFTER","updateRateLimits","limits","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","_limit$split","retryAfter","categories","namespaces","headerDelay","delay","all","headerDate","parse","parseRetryAfterHeader","isBrowser","NodeType$1","REPLAY_SESSION_KEY","REPLAY_EVENT_NAME","UNABLE_TO_SEND_REPLAY","RETRY_BASE_INTERVAL","RETRY_MAX_COUNT","NETWORK_BODY_MAX_SIZE","CONSOLE_ARG_MAX_SIZE","REPLAY_MAX_EVENT_BUFFER_SIZE","MAX_REPLAY_DURATION","_optionalChain$5","_value2","isShadowRoot","_2","shadowRoot","isNativeShadowDom","stringifyStylesheet","s","rules","cssRules","cssText","stringifyRule","rule","importStringified","regex","isCSSImportRule","styleSheet","statement","layerName","supportsText","media","mediaText","escapeImportStatement","isCSSStyleRule","selectorText","NodeType","Mirror","idNodeMap","nodeMetaMap","getId","lhs","_3","getMeta","_4","_5","getNode","getIds","removeNodeFromMap","childNodes","childNode","hasNode","meta","oldNode","shouldMaskInput","maskInputOptions","maskInputValue","isMasked","maskInputFn","text","repeat","ORIGINAL_ATTRIBUTE_NAME","getInputType","hasAttribute","getInputValue","canvasService","canvasCtx","_id","tagNameRegex","IGNORED_NODE","genId","URL_IN_CSS_REF","URL_PROTOCOL_MATCH","URL_WWW_MATCH","DATA_URI","absoluteToStylesheet","quote1","path1","quote2","path2","path3","filePath","maybeQuote","part","SRCSET_NOT_SPACES","SRCSET_COMMAS_OR_SPACES","absoluteToDoc","attributeValue","isSVGElement","ownerSVGElement","getHref","transformAttribute","maskAttributeFn","pos","collectCharacters","regEx","chars","descriptorsStr","inParens","getAbsoluteSrcsetString","ignoreAttribute","distanceToMatch","matchPredicate","distance","nodeType","ELEMENT_NODE","createMatchPredicate","eIndex","classList","elementClassMatchesRegex","needMaskingText","maskTextClass","maskTextSelector","unmaskTextClass","unmaskTextSelector","maskAllText","parentElement","autocomplete","maskDistance","unmaskDistance","lowerIfExists","maybeAttr","serializeNodeWithId","mirror","blockClass","blockSelector","unblockSelector","_options$skipChild","skipChild","_options$inlineStyles","inlineStylesheet","_options$maskInputOpt3","maskTextFn","slimDOMOptions","_options$dataURLOptio3","dataURLOptions","_options$inlineImages","inlineImages","_options$recordCanvas","recordCanvas","onSerialize","onIframeLoad","_options$iframeLoadTi","iframeLoadTimeout","onStylesheetLoad","_options$stylesheetLo","stylesheetLoadTimeout","_options$keepIframeSr","keepIframeSrcFn","_options$newlyAddedEl3","newlyAddedElement","_options$preserveWhit","preserveWhiteSpace","_serializedNode","_options$maskInputOpt","_options$dataURLOptio","_options$newlyAddedEl","rootId","docId","getRootId","DOCUMENT_NODE","compatMode","Document","DOCUMENT_TYPE_NODE","DocumentType","publicId","systemId","isCustomElement","_options$maskInputOpt2","_options$dataURLOptio2","_options$newlyAddedEl2","needBlock","contains","_isBlockedElement","HTMLFormElement","processedTagName","getValidTagName","stylesheet","styleSheets","rel","_cssText","sheet","innerText","textContent","checked","forceMask","selected","__context","canvas","getContext","x","width","y","getImageData","originalGetImageData","Uint32Array","pixel","is2DCanvasBlank","rr_dataURL","toDataURL","quality","canvasDataURL","blankCanvas","image","crossOrigin","recordInlineImage","naturalWidth","naturalHeight","drawImage","currentSrc","removeAttribute","rr_mediaState","paused","rr_mediaCurrentTime","currentTime","scrollLeft","rr_scrollLeft","scrollTop","rr_scrollTop","_n$getBoundingClientR","getBoundingClientRect","rr_width","rr_height","src","contentDocument","rr_src","customElements","isSVG","isCustom","serializeElementNode","TEXT_NODE","parentTagName","isStyle","isScript","isTextarea","nextSibling","previousSibling","_6","_7","_8","textarea","Text","serializeTextNode","CDATA_SECTION_NODE","CDATA","COMMENT_NODE","Comment","serializeNode","sn","comment","script","as","headFavicon","headMetaDescKeywords","headMetaSocial","headMetaRobots","headMetaHttpEquiv","headMetaAuthorship","headMetaVerification","slimDOMExcluded","serializedNode","recordChild","isShadowHost","headWhitespace","bypassOptions","_Array$from","serializedChildNode","isElement$1","_i2","_Array$from2","isShadow","iframeEl","win","fired","blankUrl","timer","onceIframeLoaded","iframeDoc","serializedIframeNode","link","styleSheetLoadTimeout","styleSheetLoaded","onceStylesheetLoaded","serializedLinkNode","_optionalChain$4","_value3","passive","DEPARTED_MIRROR_ACCESS_WARNING","_mirror","throttle$1","wait","timeout","previous","leading","remaining","getImplementation","clearTimeout$1","trailing","setTimeout$1","hookSetter","isRevoked","patch","replacement","defineProperties","__rrweb_original__","receiver","nowTimestamp","getWindowScroll","left","scrollingElement","pageXOffset","documentElement","pageYOffset","_9","_10","_11","_12","_13","_14","getWindowHeight","innerHeight","clientHeight","getWindowWidth","innerWidth","clientWidth","closestElementOfNode","isBlocked","checkAncestors","blockedPredicate","isUnblocked","blockDistance","unblockDistance","isIgnored","isAncestorRemoved","legacy_isTouchEvent","changedTouches","isSerializedIframe","nodeName","isSerializedStylesheet","hasShadowRoot","_18","StyleSheetMirror","styleIDMap","idStyleMap","newId","getStyle","generateId","getShadowHost","shadowHost","_19","getRootNode","_20","_21","Node","DOCUMENT_FRAGMENT_NODE","inDom","ownerDocument","rootShadowHost","getRootShadowHost","shadowHostInDom","cachedImplementations","cached","impl","EventType","EventType2","IncrementalSource","IncrementalSource2","MouseInteractions","MouseInteractions2","PointerTypes","PointerTypes2","_optionalChain$3","_value4","_len5","_key5","isNodeInLinkedList","errorHandler","DoubleLinkedList","tail","_proto3","position","addNode","__ln","removeNode","moveKey","MutationBuffer","frozen","locked","texts","attributeMap","removes","mapRemoves","movedMap","addedSet","Set","movedSet","droppedSet","processMutations","mutations","processMutation","adds","addedIds","addList","getNextId","ns","nextId","pushAdd","currentN","iframeManager","addIframe","stylesheetManager","trackLinkElement","shadowDomManager","addShadowRoot","iframe","childSn","attachIframe","observeAttachShadow","attachLinkElement","shift","isParentRemoved","isAncestorInSet","candidate","tailNode","_node","unhandledNode","attribute","style","diffAsStr","styleDiff","unchangedAsStr","_unchangedStyles","mutationCb","m","attributeName","isInputMasked","unattachedDoc","implementation","createHTMLDocument","old","_i3","_Array$from3","pname","newValue","getPropertyValue","newPriority","getPropertyPriority","_i4","_Array$from4","addedNodes","genAdds","removedNodes","nodeId","isSerialized","deepDelete","processedNodeManager","inOtherBuffer","targetId","childN","_proto4","freeze","canvasManager","unfreeze","isFrozen","lock","unlock","addsSet","_isParentRemoved","_isAncestorInSet","registerErrorHandler","unregisterErrorHandler","callbackWrapper","_optionalChain$2","_value6","_len6","_key6","mutationBuffers","composedPath","initMutationObserver","rootEl","mutationBuffer","mutationObserverCtor","MutationObserver","__rrMutationObserver","angularZoneSymbol","Zone","__symbol__","observer","onMutation","attributeOldValue","characterData","characterDataOldValue","childList","subtree","initScrollObserver","scrollCb","sampling","defaultView","scrollLeftTop","scroll","INPUT_TAGS","lastInputValueMap","initInputObserver","_ref10","inputCb","ignoreClass","ignoreSelector","userTriggeredOnInput","eventHandler","userTriggered","isTrusted","isChecked","cbWithDedup","querySelectorAll","v","lastInputValue","currentWindow","h","propertyDescriptor","HTMLInputElement","hookProperties","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","getNestedCSSRulePositions","childRule","hasNestedCSSRule","parentRule","CSSGroupingRule","CSSMediaRule","CSSSupportsRule","CSSConditionRule","unshift","parentStyleSheet","recurse","getIdAndStyleId","styleMirror","styleId","ownerNode","initAdoptedStyleSheetObserver","_ref15","hostId","patchTarget","ShadowRoot","originalPropertyDescriptor","sheets","_15","_16","adoptStyleSheets","initObservers","_hooks","_ref9","viewportResizeCb","lastH","lastW","_step4","mutationObserver","mousemoveHandler","mousemoveCb","mousemove","timeBaseline","callbackThreshold","mousemoveCallback","positions","wrappedCb","totalOffset","timeOffset","updatePosition","clientX","clientY","DragEvent","Drag","MouseEvent","MouseMove","TouchMove","initMoveObserver","mouseInteractionHandler","mouseInteractionCb","mouseInteraction","disableMap","currentPointerType","eventKey","pointerType","thisEventKey","Mouse","Touch","Pen","MouseDown","MouseUp","Click","getHandler","PointerEvent","TouchStart","TouchEnd","initMouseInteractionObserver","scrollHandler","viewportResizeHandler","inputHandler","mediaInteractionHandler","_ref18","mediaInteractionCb","volume","muted","playbackRate","initMediaInteractionObserver","styleSheetObserver","_ref11","_ref12","styleSheetRuleCb","CSSStyleSheet","insertRule","thisArg","argumentsList","_getIdAndStyleId","replaceSync","deleteRule","_getIdAndStyleId2","_getIdAndStyleId3","_getIdAndStyleId4","supportedNestedCSSRuleTypes","canMonkeyPatchNestedCSSRule","unmodifiedFunctions","_ref13","typeKey","_getIdAndStyleId5","_getIdAndStyleId6","_ref14","initStyleSheetObserver","adoptedStyleSheetObserver","styleDeclarationObserver","_ref16","_ref17","styleDeclarationCb","ignoreCSSAttributes","setProperty","CSSStyleDeclaration","priority","_getIdAndStyleId7","_17","removeProperty","_getIdAndStyleId8","remove","initStyleDeclarationObserver","fontObserver","collectFonts","_ref19","fontCb","fontMap","originalFontFace","FontFace","family","descriptors","fontFace","fontSource","restoreHandler","fonts","initFontObserver","selectionObserver","param","selectionCb","collapsed","updateSelection","selection","getSelection","isCollapsed","ranges","count","rangeCount","range","getRangeAt","startContainer","startOffset","endContainer","endOffset","initSelectionObserver","customElementObserver","_ref20","customElementCb","initCustomElementObserver","pluginHandlers","_iterator4","plugins","plugin","CrossOriginIframeMirror","generateIdFn","iframeIdToRemoteIdMap","iframeRemoteIdToIdMap","_proto5","remoteId","idToRemoteMap","remoteToIdMap","idToRemoteIdMap","getIdToRemoteIdMap","remoteIdToIdMap","getRemoteIdToIdMap","_this8","getRemoteId","getRemoteIds","ids","_this9","_optionalChain$1","_value7","_len7","_key7","wrappedEmit","_takeFullSnapshot","IframeManagerNoop","crossOriginIframeMirror","crossOriginIframeRootIdMap","_proto6","addLoadListener","IframeManager","iframes","crossOriginIframeMap","recordCrossOriginIframes","crossOriginIframeStyleMirror","handleMessage","_proto7","loadListener","isAttachIframe","adoptedStyleSheets","crossOriginMessageEvent","transformedEvent","transformCrossOriginEvent","isCheckout","_this10","FullSnapshot","replaceIdOnNode","patchRootIdOnNode","IncrementalSnapshot","Mutation","Meta","Load","DomContentLoaded","Plugin","Custom","replaceIds","ViewportResize","MediaInteraction","MouseInteraction","Scroll","CanvasMutation","Input","StyleSheetRule","StyleDeclaration","replaceStyleIds","Font","Selection","AdoptedStyleSheet","styles","iframeMirror","_step5","_iterator5","_this11","child","_this12","ShadowDomManagerNoop","_proto8","ShadowDomManager","shadowDoms","restoreHandlers","_proto9","patchAttachShadow","_this13","iframeElement","manager","option","CanvasManagerNoop","_proto10","snapshot","StylesheetManager","trackedLinkElements","adoptedStyleSheetCb","_proto11","linkEl","trackStylesheetInLinkElement","_step6","adoptedStyleSheetData","styleIds","_iterator6","CSSRule","ProcessedNodeManager","nodeMap","loop","periodicallyClear","_proto12","_this14","onRequestAnimationFrame","thisBuffer","destroy","checkoutEveryNms","checkoutEveryNth","_options$blockClass","_options$blockSelecto","_options$unblockSelec","_options$ignoreClass","_options$ignoreSelect","_options$maskAllText","_options$maskTextClas","_options$unmaskTextCl","_options$maskTextSele","_options$unmaskTextSe","_options$inlineStyles2","maskAllInputs","_maskInputOptions","_slimDOMOptions","_options$maxCanvasSiz","maxCanvasSize","packFn","_options$sampling","_options$dataURLOptio4","mousemoveWait","_options$recordCanvas2","_options$recordCrossO","_options$recordAfter","recordAfter","_options$userTriggere","_options$collectFonts","_options$inlineImages2","_options$keepIframeSr2","_options$ignoreCSSAtt","getCanvasManager","inEmittingFrame","parent","passEmitsToParent","lastFullSnapshotEvent","color","date","month","number","tel","week","select","radio","checkbox","NodeList","DOMTokenList","polyfill","incrementalSnapshotCount","eventProcessor","_step7","_iterator7","postMessage","exceedCount","exceedTime","takeFullSnapshot","_step8","wrappedMutationEmit","wrappedScrollEmit","wrappedCanvasMutationEmit","__RRWEB_EXCLUDE_IFRAME__","_iterator8","getMirror","nodeMirror","getCanvasManagerFn","_getCanvasManager","__RRWEB_EXCLUDE_SHADOW_DOM__","_ref3$mirror","_ref3$blockClass","_ref3$blockSelector","_ref3$unblockSelector","_ref3$maskAllText","_ref3$maskTextClass","_ref3$unmaskTextClass","_ref3$maskTextSelecto","_ref3$unmaskTextSelec","_ref3$inlineStyleshee","_ref3$inlineImages","_ref3$recordCanvas","_ref3$maskAllInputs","_ref3$slimDOM","slimDOM","_ref3$keepIframeSrcFn","initialOffset","canvasMutationCb","CustomElement","ReplayEventTypeIncrementalSnapshot","timestampToMs","timestampToS","addBreadcrumbEvent","triggerUserActivity","checkAndHandleExpiredSession","addUpdate","throttledAddEvent","INTERACTIVE_SELECTOR","getClosestInteractive","closest","getClickTargetNode","getTargetNode","isEventWithTarget","ClickDetector","slowClickConfig","_addBreadcrumbEvent","_lastMutation","_lastScroll","_clicks","_timeout","_threshold","_scollTimeout","scrollTimeout","_replay","_ignoreSelector","_proto13","addListeners","_this15","cleanupWindowOpen","nowInSeconds","originalWindowOpen","_len8","_key8","_teardown","removeListeners","_checkClickTimeout","handleClick","SLOW_CLICK_TAGS","ignoreElement","isClickBreadcrumb","newClick","clickBreadcrumb","clickCount","_scheduleCheckClicks","registerMutation","registerScroll","registerClick","_handleMultiClick","_getClicks","_checkClicks","_this16","timedOutClicks","mutationAfter","scrollAfter","_i5","_timedOutClicks","_generateBreadcrumbs","hadScroll","hadMutation","isSlowClick","timeAfterClickMs","endReason","route","getCurrentRoute","_this17","createBreadcrumb","ATTRIBUTES_TO_RECORD","getAttributesToRecord","normalizedKey","getBaseDomBreadcrumb","isElement","ENTRY_TYPES","decodedBodySize","encodedBodySize","responseStatus","transferSize","paint","domComplete","domContentLoadedEventStart","domContentLoadedEventEnd","domInteractive","loadEventStart","loadEventEnd","redirectCount","createPerformanceEntry","setupPerformanceObserver","addPerformanceEntry","onEntries","_ref21","clearCallbacks","_ref22","replayPerformanceEntries","getLargestContentfulPaint","clearCallback","logInfo","shouldAddBreadcrumb","addLogBreadcrumb","logInfoNextTick","EventBufferSizeExceededError","_Error","EventBufferArray","events","_totalSize","hasCheckout","_proto14","addEvent","_addEvent2","_callee","eventSize","_context2","_x","_this18","eventsRet","getEarliestTimestamp","WorkerHandler","worker","_worker","_proto15","ensureReady","_this19","_ensureReadyPromise","_ref23","success","terminate","_this20","_getAndIncrementId","_ref24","EventBufferCompressionWorker","_earliestTimestamp","_proto16","_sendEventToWorker","_finishRequest","_finishRequest2","_callee2","_context3","EventBufferProxy","_fallback","_compression","_used","_ensureWorkerIsLoadedPromise","_ensureWorkerIsLoaded","_proto17","_finish","_callee3","_context4","ensureWorkerIsLoaded","_ensureWorkerIsLoaded2","_callee4","_context5","t0","_switchToCompressionWorker","_switchToCompressionWorker2","_callee5","_this$_fallback","addEventPromises","_iterator9","_step9","_context6","hasEvents","hasSessionStorage","sessionStorage","isSampled","lastActivity","segmentId","previousSessionId","saveSession","setItem","createSession","_ref26","sessionSampleRate","allowBuffering","_ref26$stickySession","stickySession","getSessionSampleType","isExpired","initialTime","expiry","targetTime","isSessionExpired","_ref28","maxReplayDuration","sessionIdleExpire","_ref28$targetTime","shouldRefreshSession","_ref29","loadOrCreateSession","_ref30","sessionOptions","traceInternals","existingSession","sessionStringFromStorage","getItem","sessionObj","fetchSession","addEventSync","shouldAddEvent","_addEvent","_x2","_x3","_x4","_addEvent3","_callee11","replayOptions","eventAfterPossibleCallback","_context12","eventBuffer","recordingMode","maybeApplyCallback","beforeAddRecordingEvent","isPaused","timestampInMs","timeouts","sessionIdlePause","initialTimestamp","isCustomEvent","isTransactionEvent","isFeedbackEvent","handleAfterSendEvent","enforceStatusCode","__sentry__baseTransport__","isBaseTransportSend","sendResponse","replayContext","traceIds","handleTransactionEvent","errorIds","beforeErrorSampling","sendBufferedReplayOrFlush","handleErrorEvent","createPerformanceSpans","_ref31","addNetworkBreadcrumb","hubOrClient","isHub","tunnel","checkDsn","checkTunnel","isSentryRequestUrl","shouldFilterRequest","getBodySize","URLSearchParams","FormData","formDataStr","_serializeFormData","Blob","ArrayBuffer","byteLength","parseContentLengthHeader","getBodyString","mergeWarning","warning","_meta","warnings","newMeta","existingWarnings","makeNetworkReplayBreadcrumb","buildSkippedNetworkRequestOrResponse","bodySize","buildNetworkRequestOrResponse","_normalizeNetworkBody","first","last","exceedsSizeLimit","isProbablyJson","truncatedBody","e3","normalizeNetworkBody","normalizedBody","getAllowedHeaders","allowedHeaders","filteredHeaders","formData","urlMatches","urls","baseURI","fixedUrl","getFullUrl","_captureFetchBreadcrumbToReplay","_callee12","_context13","_prepareFetchData","_x8","_x9","_x10","_prepareFetchData2","_callee13","_hint$startTimestamp2","_hint$endTimestamp2","_breadcrumb$data2","_breadcrumb$data2$sta","requestBodySize","responseBodySize","captureDetails","_context14","request_body_size","response_body_size","networkDetailAllowUrls","networkDetailDenyUrls","_getRequestInfo","_getResponseInfo","_ref32","networkCaptureBodies","networkRequestHeaders","getHeadersFromOptions","_getBodyString","_getFetchRequestArgBody","bodyStr","_x11","_x12","_x13","_x14","_getResponseInfo2","_callee14","_ref33","networkResponseHeaders","_yield$_parseFetchRes","bodyText","_context15","getAllHeaders","_parseFetchResponseBody","getResponseData","_ref34","_x15","_parseFetchResponseBody2","_callee15","_context16","_tryCloneResponse","_tryGetResponseText","allHeaders","_x16","_getResponseText2","_getResponseText","txt","_callee16","_context17","_captureXhrBreadcrumbToReplay","_callee17","_context18","_prepareXhrData","_hint$startTimestamp","_hint$endTimestamp","_breadcrumb$data","_breadcrumb$data$stat","getAllResponseHeaders","_line$split","getResponseHeaders","_ref35","requestBody","requestWarning","_ref36","responseText","responseType","outerHTML","_parseXhrResponse","_getXhrResponseBody","responseBody","responseWarning","handleNetworkBreadcrumbs","_replay$getOptions2","_isXhrBreadcrumb","_isXhrHint","reqSize","resSize","getResponseHeader","_getBodySize","enrichXhrBreadcrumb","_x17","_x18","_x19","captureXhrBreadcrumbToReplay","_isFetchBreadcrumb","_isFetchHint","enrichFetchBreadcrumb","_x5","_x6","_x7","captureFetchBreadcrumbToReplay","beforeAddNetworkBreadcrumb","handleFetch","handleFetchSpanListener","handleXhr","handleXhrSpanListener","_LAST_BREADCRUMB","addGlobalListeners","newBreadcrumb","isTruncated","normalizedArgs","normalizedArg","normalizeConsoleBreadcrumb","handleScope","handleScopeListener","_getDomTarget","isClick","getDomTarget","handleDom","clickDetector","altKey","metaKey","ctrlKey","shiftKey","handleDomListener","handleHistory","handleHistorySpanListener","includeAfterSendEventHandling","afterSendHandler","isReplayEvent","flush","getSessionId","feedbackId","addFeedbackBreadcrumb","__rrweb__","isRrwebError","captureExceptions","isErrorEventSampled","errorSampleRate","shouldSampleForBufferEvent","handleGlobalEventListener","hasHooks","exceptionValue","handleHydrationError","handleBeforeSendEvent","lastTransaction","feedbackEvent","includeReplay","addMemoryEntry","_x20","_addMemoryEntry","_callee18","_context19","memoryEntry","memory","jsHeapSizeLimit","totalJSHeapSize","usedJSHeapSize","getHandleRecordingEmit","hadFirstEvent","_isCheckout","isIncrementalEvent","isIncrementalMouseInteraction","_event$data","updateClickDetectorForRecordingEvent","setInitialState","shouldRecordCanvas","isRecordingCanvas","useCompressionOption","useCompression","blockAllMedia","networkDetailHasUrls","networkRequestHasHeaders","networkResponseHasHeaders","createOptionsEvent","addSettingsEvent","earliestEvent","createReplayEnvelope","replayEvent","recordingData","sdkInfo","createEventEnvelopeHeaders","prepareRecordingData","_ref37","payloadWithSequence","replayHeaders","sequence","prepareReplayEvent","_x21","_prepareReplayEvent","_callee19","_ref38","eventHint","preparedEvent","_ref48","_context20","_integrations","platform","getSdkMetadata","sendReplayRequest","_x22","_sendReplayRequest","_callee20","_ref39","segment_id","eventContext","preparedRecordingData","baseEvent","rateLimits","_context21","replay_start_timestamp","error_ids","trace_ids","replay_type","cause","TransportStatusCodeError","isRateLimited","dataCategory","disabledUntil","RateLimitError","_Error2","_Error3","_this21","sendReplay","_x23","_x24","_sendReplay","_callee22","replayData","retryConfig","_context23","interval","_retryCount","_callee21","_context22","THROTTLED","ReplayContainer","_ref40","_this22","recordingOptions","__init5","__init6","_lastActivity","_isEnabled","_isPaused","_hasInitializedCoreListeners","_context","initialUrl","_recordingOptions","_debouncedFlush","callbackReturnValue","timerId","maxTimerId","maxWait","invokeFunc","cancelTimers","debounced","cancel","debounce","_flush","flushMinDelay","flushMaxDelay","_throttledAddEvent","maxCount","durationSeconds","counter","isThrottled","_cleanup","wasThrottled","throttle","_this$getOptions","slowClickTimeout","slowClickIgnoreSelectors","_proto18","_canvas","initializeSampling","_this$_options","_initializeSessionForSampling","_initializeRecording","_handleException","_updateUserActivity","startBuffering","startRecording","canvasOptions","_stopRecording","_onMutationHandler","stopRecording","_stop","_callee6","_temp2","_ref41","_ref41$forceFlush","forceFlush","_context7","_removeListeners","force","removeItem","deleteSession","_x25","pause","resume","_checkSession","_sendBufferedReplayOrFlush","_callee7","_temp3","_ref42$continueRecord","continueRecording","activityTime","hasStoppedRecording","_context8","flushImmediate","_updateSessionActivity","_maybeSaveSession","_x26","cbResult","updateUserActivity","conditionalFlush","cancelFlush","urlPath","_clearContext","_this23","_ref25","customWorkerUrl","workerUrl","Worker","__SENTRY_EXCLUDE_REPLAY_WORKER__","createObjectURL","_loadWorker","createEventBuffer","_addListeners","_refreshSession","_refreshSession2","_callee8","_context9","_x27","_handleVisibilityChange","_handleWindowBlur","_handleWindowFocus","_handleKeyboardEvent","_performanceCleanupCallback","_this24","_doChangeToForegroundTasks","_doChangeToBackgroundTasks","_this25","_this26","_this27","isInputElement","hasModifierKey","isCharacterKey","getKeyboardBreadcrumb","handleKeyboardEvent","_createCustomBreadcrumb","_this28","_addPerformanceEntries","_updateInitialTimestampFromEventBuffer","_popEventContext","_runFlush","_runFlush2","_callee9","_context10","_this29","_ref43","_callee10","_temp4","_ref44$force","tooShort","tooLong","_context11","minReplayDuration","_flushLock","_x28","_this30","mutationLimit","overMutationLimit","mutationBreadcrumbLimit","getOption","selectors","defaultSelectors","deprecatedClassOption","deprecatedSelectorOption","deprecatedSelectors","allSelectors","MEDIA_SELECTORS","DEFAULT_NETWORK_HEADERS","_initialized","Replay$1","_temp5","_ref47","_ref47$flushMinDelay","_ref47$flushMaxDelay","_ref47$minReplayDurat","_ref47$maxReplayDurat","_ref47$stickySession","_ref47$useCompression","_ref47$_experiments","_ref47$maskAllText","_ref47$maskAllInputs","_ref47$blockAllMedia","_ref47$mutationBreadc","_ref47$mutationLimit","_ref47$slowClickTimeo","_ref47$slowClickIgnor","_ref47$networkDetailA","_ref47$networkDetailD","_ref47$networkCapture","_ref47$networkRequest","_ref47$networkRespons","_ref47$mask","mask","_ref47$maskAttributes","maskAttributes","_ref47$unmask","unmask","_ref47$block","block","_ref47$unblock","unblock","_ref47$ignore","ignore","maskFn","privacyOptions","_ref45","getPrivacyOptions","password","_ref46","maskAttribute","_initialOptions","_getMergedNetworkHeaders","_isInitialized","__initStatic","_proto19","_this31","_setup","_initialize","_maybeLoadFromReplayCanvasIntegration","finalOptions","initialOptions","opt","replaysSessionSampleRate","replaysOnErrorSampleRate","loadReplayOptionsFromClient","canvasIntegration","SentryError","logLevel","SENTRY_API_VERSION","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","tunnelOrOptions","_getIngestEndpoint","sentry_key","sentry_version","sentry_client","_encodedAuth","createMetricEnvelope","metricBucketItems","tagEntries","maybeTags","metricType","serializeMetricBuckets","createMetricEnvelopeItem","ALREADY_SEEN_ERROR","BaseClient","_integrationsInitialized","_numProcessing","_outcomes","_dsn","_transport","transportOptions","_process","eventFromException","_captureEvent","eventMessage","promisedEvent","eventFromMessage","sendSession","metricsAggregator","_isClientDoneProcessing","clientFinished","transportFlushed","close","forceInitialize","_setupIntegrations","getIntegrationById","integrationId","integrationName","addIntegration","isAlreadyInstalled","sendEvent","newItem","env","packages","enhanceEventWithSdkInfo","envelopeHeaders","createEventEnvelope","promise","_sendEnvelope","createSessionEnvelope","eventOrCount","sendClientReports","captureAggregateMetrics","metricsEnvelope","hook","_updateSessionFromEvent","crashed","errored","sessionNonTerminal","ticked","clearInterval","_prepareEvent","_processEvent","finalEvent","sentryError","isTransaction","beforeSendLabel","__sentry__","beforeSend","beforeSendTransaction","spanCountBefore","spanCountBeforeProcessing","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","processedEvent","spanCount","droppedSpanCount","transactionInfo","_clearOutcomes","outcomes","_key$split","quantity","BrowserClient","_BaseClient","names","applySdkMetadata","SENTRY_SDK_SOURCE","_flushOutcomes","captureUserFeedback","createUserFeedbackEnvelopeItem","createUserFeedbackEnvelope","discarded_events","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","makeRequest","task","$","taskProducer","drain","capturedSetTimeout","makePromiseBuffer","bufferSize","filteredEnvelopeItems","getEventForEnvelopeItem","filteredEnvelope","recordEnvelopeLoss","cachedFetchImpl","makeFetchTransport","nativeFetch","fetchImpl","getNativeFetchImplementation","pendingBodySize","pendingCount","requestSize","requestOptions","referrerPolicy","keepalive","fetchOptions","UNKNOWN_FUNCTION","createFrame","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","defaultStackParser","parsers","sortedParsers","skipFirst","lines","cleanedLine","localStack","stripSentryFramesAndReverse","subMatch","_extractSafariExtensi","extractSafariExtensionDetails","_extractSafariExtensi2","isSafariExtension","isSafariWebExtension","dedupeIntegration","previousEvent","currentEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","_isSameMessageEvent","previousException","_getExceptionFromEvent","currentException","_isSameExceptionEvent","currentFrames","_getFramesFromEvent","previousFrames","frameA","frameB","currentFingerprint","previousFingerprint","showReportDialog","_hub$getStackTop","dsnLike","dialogOptions","endpoint","encodedOptions","getReportDialogEndpoint","onLoad","onload","onClose","reportDialogClosedMessageHandler","injectionPoint","severityLevelFromString","CaptureConsole","levels","consoleHandler","Replay","Sentry","createClient","config","_event$user","scrubEmails","showFeedback","getUserData","captureConsole","nameAttr","userData","_app$session","_userData","userId"],"sourceRoot":""} \ No newline at end of file