UNPKG

@backtrace/browser

Version:
1 lines 77.6 kB
class t{message;get result(){return this._result}status="Ok";_result;constructor(t,e){this.message=e,this.isSubmissionResponse(t)?this.status=t:this._result=t}static OnLimitReached(e="Server"){return new t("Limit reached",`${e} report limit reached`)}static SdkDisabled(){return new t("Disabled SDK")}static Unsupported(e){return new t("Unsupported",e)}static ReportSkipped(){return new t("Report skipped")}static OnInternalServerError(e){return new t("Server Error",e)}static OnInvalidToken(){return new t("Invalid token")}static OnUnknownError(e){return new t("Unknown",e)}static OnNetworkingError(e){return new t("Network Error",e)}static Ok(e){return new t(e)}isSubmissionResponse(t){return"string"==typeof t}}function e(){const t=[],e=[];return function(s,i){if(null===i)return i;const r=typeof i;if("bigint"===r)return i.toString();if("object"!==r)return i;for(;t.length>0&&t[t.length-1]!==this;)t.pop(),e.pop();return t.includes(i)?`[Circular].${e.filter((t=>!!t)).join(".")}.${s}`:(e.push(s),t.push(i),i)}}class s{static SUBMIT_PREFIX="submit.backtrace.io/";static toJsonReportSubmissionUrl(t,e){if(!e)return t;if(t.includes(this.SUBMIT_PREFIX))return t;if(-1!==t.indexOf(e))return t;const s=new URL("/post",t);return s.searchParams.append("format","json"),s.searchParams.append("token",e),s.href}static toPlCrashReporterSubmissionUrl(t){return this.changeSubmissionFormat(t,"plcrash")}static toMinidumpSubmissionUrl(t){return this.changeSubmissionFormat(t,"minidump")}static toAttachmentSubmissionUrl(t,e,s){const i=`object=${e}&attachment_name=${s}`;return t.includes("?")?t+"&"+i:t+"?"+i}static findUniverse(t){const e=t.indexOf(this.SUBMIT_PREFIX);if(-1!==e){const s=e+this.SUBMIT_PREFIX.length,i=t.indexOf("/",s);return t.substring(s,i)}const s=t.indexOf(".backtrace.io");if(-1===s)return;let i=t.indexOf("://");-1===i?i=0:i+=3;const r=t.substring(i,s),n=r.indexOf(".");return-1===n?r:r.substring(0,n)}static findToken(t){if(-1!==t.indexOf(this.SUBMIT_PREFIX)){const e=t.split("/");return e[e.length-2]??null}return new URL(t).searchParams.get("token")}static changeSubmissionFormat(t,e){const s=t.indexOf(this.SUBMIT_PREFIX);if(-1!==s){const i=t.indexOf("?"),r=-1===i?"":t.substring(i),n=t.substring(s+this.SUBMIT_PREFIX.length,-1===i?void 0:i).split("/"),o=3;return n.length<o?t:(n[2]=e,t.substring(0,s+this.SUBMIT_PREFIX.length)+n.join("/")+r)}{const s=new URL(t);return s.searchParams.set("format",e),s.href}}}class i{_requestHandler;_submissionUrl;constructor(t,e){this._requestHandler=e,this._submissionUrl=s.toJsonReportSubmissionUrl(t.url,t.token)}send(t,s,i){const r=JSON.stringify(t,e());return this._requestHandler.postError(this._submissionUrl,r,s,i)}async sendAttachment(e,i,r){return this._requestHandler.postAttachment?await this._requestHandler.postAttachment(s.toAttachmentSubmissionUrl(this._submissionUrl,e,i.name),i,r):t.Unsupported("postAttachment is not implemented")}}class r{static isConnectionError(t){const e=t;return"ETIMEDOUT"===e.code||"ECONNRESET"===e.code||"ECONNABORTED"===e.code}}class n{static generateSummedEventsUrl(t,e,s){const i=this.findSubmissionInformation(e,s);if(i)return this.generateEventsServiceUrl(t,"summed-events",i.universe,i.token)}static generateUniqueEventsUrl(t,e,s){const i=this.findSubmissionInformation(e,s);if(i)return this.generateEventsServiceUrl(t,"unique-events",i.universe,i.token)}static generateEventsServiceUrl(t,e,s,i){return new URL(`/api/${e}/submit?universe=${s}&token=${i}`,t).toString()}static findSubmissionInformation(t,e){const i=s.findUniverse(t);if(i&&(e=e??s.findToken(t)))return{universe:i,token:e}}}class o{_requestHandler;_summedMetricsSubmissionUrl;_uniqueMetricsSubmissionUrl;_requestBacktraceReportSubmission;constructor(t,e){this._requestHandler=e,this._summedMetricsSubmissionUrl=n.generateSummedEventsUrl(t.metrics?.url??"https://events.backtrace.io",t.url,t.token),this._uniqueMetricsSubmissionUrl=n.generateUniqueEventsUrl(t.metrics?.url??"https://events.backtrace.io",t.url,t.token),this._requestBacktraceReportSubmission=t.requestBacktraceReportSubmission??new i({url:t.url},this._requestHandler)}sendReport(t,e,s){return this._requestBacktraceReportSubmission.send(t,e,s)}sendAttachment(t,e,s){return this._requestBacktraceReportSubmission.sendAttachment(t,e,s)}sendUniqueMetrics(t,e){if(!this._uniqueMetricsSubmissionUrl)throw new Error("Unique metrics URL is not available.");return this._requestHandler.post(this._uniqueMetricsSubmissionUrl,JSON.stringify(t),e)}sendSummedMetrics(t,e){if(!this._summedMetricsSubmissionUrl)throw new Error("Summed metrics URL is not available.");return this._requestHandler.post(this._summedMetricsSubmissionUrl,JSON.stringify(t),e)}}class a{_callbacks={};on(t,e){return this.addCallback(t,{callback:e}),this}once(t,e){return this.addCallback(t,{callback:e,once:!0}),this}off(t,e){return this.removeCallback(t,e),this}emit(t,...e){const s=this._callbacks[t];if(!s||!s.length)return!1;for(const{callback:i,once:r}of[...s]){try{i(...e)}catch{}r&&this.removeCallback(t,i)}return!0}addCallback(t,e){const s=this._callbacks[t];s?s.push(e):this._callbacks[t]=[e]}removeCallback(t,e){const s=this._callbacks[t];if(!s)return;const i=s.findIndex((t=>t.callback===e));-1!==i&&(s.splice(i,1),s.length||delete this._callbacks[t])}}class c{static now(){return Date.now()}static toTimestampInSec(t){return Math.floor(t/1e3)}static convertSecondsToMilliseconds(t){return 1e3*t}}class u{data;attributes;attachments;classifiers=[];annotations={};stackTrace={};message;innerReport=[];timestamp=c.now();skipFrames=0;addStackTrace(t,e,s=""){return this.stackTrace[t]="string"==typeof e?{stack:e,message:s}:e,this}constructor(t,e={},s=[],i={}){this.data=t,this.attributes=e,this.attachments=s,this.skipFrames=i?.skipFrames??0;let r="Exception";t instanceof Error?(this.message=this.generateErrorMessage(t.message),this.annotations.error={...t,message:this.message,name:t.name,stack:t.stack},this.classifiers=[t.name],this.stackTrace.main={stack:t.stack??"",message:this.message},t.cause&&this.innerReport.push(t.cause)):(this.message=this.generateErrorMessage(t),this.stackTrace.main={stack:(new Error).stack??"",message:this.message},this.classifiers=["Message"],r="Message",this.skipFrames+=1),this.attributes["error.type"]||(this.attributes["error.type"]=r),this.attributes["error.message"]=this.message,i?.timestamp&&(this.timestamp=i.timestamp),i?.classifiers&&this.classifiers.unshift(...i.classifiers)}generateErrorMessage(t){return"object"==typeof t?JSON.stringify(t,e()):t?.toString()??""}}class d{attachmentEvents;_attachmentProviders=[];constructor(){this.attachmentEvents=new a}add(...t){this.addProviders(...t.map((t=>"function"==typeof t?{type:"dynamic",get:t}:{type:"scoped",get:()=>t})))}addProviders(...t){let e=!1;for(const s of t)if("dynamic"===s.type)this._attachmentProviders.push(s);else{const t=s.get();this._attachmentProviders.push({type:"scoped",get:()=>t}),e=!0}e&&this.attachmentEvents.emit("scoped-attachments-updated",this.get("scoped"))}get(t){const e=[];for(const s of this._attachmentProviders){if(t&&s.type!==t)continue;const i=s.get();i&&(Array.isArray(i)?e.push(...i):e.push(i))}return e}}class l{static build(t){const e={annotations:{},attributes:{}};if(!t)return e;for(const s in t){const i=t[s];if(null!=i)switch(typeof i){case"object":e.annotations[s]=i;break;case"bigint":e.attributes[s]=i.toString();break;default:e.attributes[s]=i}else e.attributes[s]=i}return e}}class h{attributeEvents;_attributeProviders=[];constructor(t){this.attributeEvents=new a;for(const e of t)this.addProvider(e)}add(t){"function"==typeof t?this.addProvider({type:"dynamic",get:t}):this.addProvider({type:"scoped",get:()=>t})}addProvider(t){if("dynamic"!==t.type){const e=t.get();this._attributeProviders.push({type:"scoped",get:()=>e}),this.attributeEvents.emit("scoped-attributes-updated",this.get("scoped"))}else this._attributeProviders.push(t)}get(t){const e={annotations:{},attributes:{}};for(const s of this._attributeProviders){if(t&&s.type!=t)continue;const i=l.build(s.get());e.attributes={...e.attributes,...i.attributes},e.annotations={...e.annotations,...i.annotations}}return e}}class m{_sdkName;_sdkVersion;_sessionId;constructor(t,e,s){this._sdkName=t,this._sdkVersion=e,this._sessionId=s}get type(){return"scoped"}get(){return{"application.session":this._sessionId,"backtrace.agent":this._sdkName,"backtrace.version":this._sdkVersion}}}class b{type;_source;constructor(t){this._source="function"==typeof t?t:()=>t,this.type="function"==typeof t?"dynamic":"scoped"}get(){return this._source()}}function p(t){return t.toString().length}const f=t=>function(t){return JSON.stringify(t).length}(t),g=p,_=p,w=0,v=0,S=t=>t?4:5,y=0,k=4;const E=(t,e)=>{const s=Object.entries(t);let i=0,r=0;for(const[n,o]of s){const s=T(t,n,o,e);0!==s&&(i++,r+=I(n)+s+1)}return 2+Math.max(0,i-1)+r};function I(t){if(null===t)return k+2;if(void 0===t)return 11;switch(typeof t){case"string":return f(t);case"number":return g(t)+2;case"boolean":return S(t)+2;case"symbol":return w;default:return f(t.toString())}}function T(t,e,s,i){if(s&&"object"==typeof s&&"toJSON"in s&&"function"==typeof s.toJSON&&(s=s.toJSON()),null===(s=i?i.call(t,e,s):s))return k;if(void 0===s)return y;if(Array.isArray(s))return function(t,e){const s=t.length-1;let i=0;for(let s=0;s<t.length;s++){const r=t[s];switch(typeof r){case"function":case"symbol":case"undefined":i+=k;break;default:i+=T(t,s.toString(),r,e)}}return 2+s+i}(s,i);switch(typeof s){case"bigint":return _(s);case"boolean":return S(s);case"function":return v;case"number":return g(s);case"object":return E(s,i);case"string":return f(s);case"symbol":return w;case"undefined":return y}return 0}function x(t,e){return T(void 0,"",t,e)}function A(t,e){if(!(e<1/0))return t;if(e<0)return"<removed>";const s=t=>"object"==typeof t&&t?A(t,e-1):t,i={};for(const e in t){const r=t[e];Array.isArray(r)?i[e]=r.map(s):i[e]=s(r)}return i}function M(){const t=(s=e(),function(...t){let e="";for(const i of t)e+="object"==typeof i?JSON.stringify(i,s):i?.toString();return e});var s;try{return require("util").format??t}catch{return t}}var P;!function(t){t[t.Verbose=1]="Verbose",t[t.Debug=2]="Debug",t[t.Info=4]="Info",t[t.Warning=8]="Warning",t[t.Error=16]="Error"}(P||(P={}));var O;!function(t){t[t.Manual=1]="Manual",t[t.Log=2]="Log",t[t.Navigation=4]="Navigation",t[t.Http=8]="Http",t[t.System=16]="System",t[t.User=32]="User",t[t.Configuration=64]="Configuration"}(O||(O={}));class N{_events={};_formatter;start(t){(t.breadcrumbsType&O.Log)===O.Log&&(this._formatter=M(),this.bindToConsoleMethod("log",P.Info,t),this.bindToConsoleMethod("warn",P.Warning,t),this.bindToConsoleMethod("error",P.Error,t),this.bindToConsoleMethod("debug",P.Debug,t),this.bindToConsoleMethod("trace",P.Verbose,t))}dispose(){for(const t in this._events){const e=this._events[t];console[t]=e}}bindToConsoleMethod(t,e,s){const i=console[t];console[t]=(...t)=>{i(...t);const r=this._formatter(...t);s.addBreadcrumb(r,e,O.Log)},this._events[t]=i}}class R{capacity;_array;_headConstraint;_lengthConstraint;_head=0;_length=0;get head(){return this._head}set head(t){this._head=this._headConstraint(t)}get length(){return this._length}set length(t){this._length=this._lengthConstraint(t)}get start(){return this._headConstraint(this.head-this.length)}constructor(t,e){var s,i;this.capacity=t,this._array=new Array(t),this._headConstraint=(s=0,i=t,function(t){const e=i-s;let r;return t<s?(r=i-(s-t)%e,r===i&&(r=s)):t>=i?(r=s+(t-i)%e,r===i&&(r=s)):r=t,r}),this._lengthConstraint=function(t,e){return function(s){return Math.max(t,Math.min(s,e))}}(0,t),e&&this.push(...e)}add(t){return this.pushOne(t)}push(...t){for(const e of t)this.pushOne(e);return this.length}pop(){this.head--;const t=this._array[this.head];return this._array[this.head]=void 0,this.length--,t}shift(){const t=this._array[this.start];return this._array[this.start]=void 0,this.length--,t}at(t){return this._array[this.index(t)]}*values(){for(let t=0;t<this.length;t++){const e=this.index(t);yield this._array[e]}}*keys(){for(let t=0;t<this.length;t++)yield t}*entries(){for(let t=0;t<this.length;t++){const e=this.index(t);yield[t,this._array[e]]}}[Symbol.iterator](){return this.values()}pushOne(t){this._array[this.head]=t,this.head++,this.length++}index(t){if(!this.length)return this._headConstraint(t);const e=t%this.length+this.start;return this._headConstraint(e)}}class U{_limits;get lastBreadcrumbId(){return this._lastBreadcrumbId}name="bt-breadcrumbs-0";_lastBreadcrumbId=c.toTimestampInSec(c.now());_breadcrumbs;_breadcrumbSizes;constructor(t){this._limits=t,this._breadcrumbs=new R(t.maximumBreadcrumbs??100),this._breadcrumbSizes=new R(this._breadcrumbs.capacity)}getAttachments(){return[this]}getAttachmentProviders(){return[{get:()=>this,type:"scoped"}]}static factory({limits:t}){return new U(t)}get(){return JSON.stringify([...this._breadcrumbs],e())}add(t){this._lastBreadcrumbId++;const s=this._lastBreadcrumbId,i={id:s,message:t.message,timestamp:c.now(),type:O[t.type].toLowerCase(),level:P[t.level].toLowerCase()};if(t.attributes&&(i.attributes=t.attributes),this._breadcrumbs.add(i),this._limits.maximumTotalBreadcrumbsSize){const t=x(i,e());this._breadcrumbSizes.add(t);let s=this.totalSize();for(;s>this._limits.maximumTotalBreadcrumbsSize;){this._breadcrumbs.shift();s-=(this._breadcrumbSizes.shift()??0)+1}}return s}totalSize(){let t=0;for(const e of this._breadcrumbSizes)t+=e;return t+Math.max(0,this._breadcrumbSizes.length-1)+2}}const C="breadcrumbs.lastId",L=(t,e)=>!1===t?void 0:void 0!==t?t:e;class B{breadcrumbsType;logLevel;_enabled=!1;_limits;_eventSubscribers=[new N];_interceptor;_storage;constructor(t,e){this._limits={maximumBreadcrumbs:L(t?.maximumBreadcrumbs,100),maximumAttributesDepth:L(t?.maximumAttributesDepth,2),maximumBreadcrumbMessageLength:L(t?.maximumBreadcrumbMessageLength,255),maximumBreadcrumbSize:L(t?.maximumBreadcrumbSize,65536),maximumTotalBreadcrumbsSize:L(t?.maximumTotalBreadcrumbsSize,1048576)},this.breadcrumbsType=t?.eventType??127,this.logLevel=t?.logLevel??31,this._storage=(e?.storage??U.factory)({limits:this._limits}),this._interceptor=t?.intercept,e?.subscribers&&this._eventSubscribers.push(...e.subscribers)}addEventSubscriber(t){this._enabled&&t.start(this),this._eventSubscribers.push(t)}setStorage(t){this._storage="function"==typeof t?t({limits:this._limits}):t}dispose(){this._enabled=!1;for(const t of this._eventSubscribers)t.dispose()}bind({client:t,attachmentManager:e}){this._storage.getAttachmentProviders?e.addProviders(...this._storage.getAttachmentProviders()):e.add(...this._storage.getAttachments()),t.addAttribute((()=>({[C]:this._storage.lastBreadcrumbId}))),t.on("before-skip",(t=>this.logReport(t)))}initialize(){if(!this._enabled){for(const t of this._eventSubscribers)t.start(this);this._enabled=!0}}verbose(t,e){return this.log(t,P.Verbose,e)}debug(t,e){return this.log(t,P.Debug,e)}info(t,e){return this.log(t,P.Info,e)}warn(t,e){return this.log(t,P.Warning,e)}error(t,e){return this.log(t,P.Error,e)}log(t,e,s){return this.addBreadcrumb(t,e,O.Manual,s)}logReport(t){const e=t.data instanceof Error?P.Error:P.Warning;return this.addBreadcrumb(t.message,e,O.System)}addBreadcrumb(t,s,i,r){if(!this._enabled)return!1;let n,o={message:this.prepareBreadcrumbMessage(t),level:s,type:i,attributes:r};if(this._interceptor){const t=this._interceptor(o);if(!t)return!1;o=t}if((this.logLevel&o.level)!==s)return!1;if((this.breadcrumbsType&o.type)!==i)return!1;if(void 0!==this._limits.maximumBreadcrumbMessageLength&&(o.message=o.message.substring(0,this._limits.maximumBreadcrumbMessageLength)),n=void 0!==this._limits.maximumAttributesDepth&&o.attributes?{...o,attributes:A(o.attributes,this._limits.maximumAttributesDepth)}:o,void 0!==this._limits.maximumBreadcrumbSize){if(x(n,e())>this._limits.maximumBreadcrumbSize)return!1}return void 0!==this._storage.add(n)}prepareBreadcrumbMessage(t){if(null==t)return"";switch(typeof t){case"string":return t;case"object":return JSON.stringify(t,e());default:return t.toString()}}}const D="unknown",q="anonymous";class F{addressSeparator;get engine(){return"v8"}constructor(t=""){this.addressSeparator=t}convert(t,e){const s=[];let i=t.split("\n");const r=e.split("\n");i=-1!==i[0].indexOf(r[0])?i.slice(r.length):i.slice(1);for(const t of i){const e=t.trim();if(!e)continue;const i=this.parseFrame(e);s.push(i)}return s}parseFrame(t){const e="at ";if(!t.startsWith(e))return{funcName:t,library:D};const s="async ";let i=(t=t.substring(t.indexOf(e)+3)).indexOf(" (");if(-1===i)return t.startsWith(s)&&(t=t.substring(6)),{funcName:q,...this.parseSourceCodeInformation(t)};let r=t.substring(i+2-1,t.length);const n="(<anonymous>)";r.startsWith(n)&&(i+=14,r=r.substring(13)),r=r.startsWith(` ${e}`)?r.substring(4):r.substring(1,r.length-1);let o=t.substring(0,i);return o.startsWith(s)&&(o=o.substring(6)),{funcName:o,...this.parseSourceCodeInformation(r)}}parseSourceCodeInformation(t){if(t.startsWith("eval"))return this.extractEvalInformation(t);this.addressSeparator&&t.startsWith(this.addressSeparator)&&(t=t.substring(this.addressSeparator.length).trimStart());const e=t.split(":"),s=parseInt(e[e.length-1]),i=parseInt(e[e.length-2]);return{library:e.slice(0,e.length-2).join(":"),column:isNaN(s)?void 0:s,line:isNaN(i)?void 0:i}}extractEvalInformation(t){const e=t.indexOf("("),s=t.indexOf(")");if(-1===e||-1===s||e>s)return{library:D};const i=t.substring(e+1,s);return this.parseSourceCodeInformation(i)}}class H{static uuid(){const t=[...new Array(16)].map((()=>Math.floor(256*Math.random())));return t[6]=15&t[6]|64,t[8]=63&t[8]|128,t.slice(0,4).map((t=>t.toString(16).padStart(2,"0"))).join("")+"-"+t.slice(4,6).map((t=>t.toString(16).padStart(2,"0"))).join("")+"-"+t.slice(6,8).map((t=>t.toString(16).padStart(2,"0"))).join("")+"-"+t.slice(8,10).map((t=>t.toString(16).padStart(2,"0"))).join("")+"-"+t.slice(10,16).map((t=>t.toString(16).padStart(2,"0"))).join("")}}class j{_sdkOptions;_stackTraceConverter;_attributeManager;_debugIdProvider;MAIN_THREAD_NAME="main";constructor(t,e,s,i){this._sdkOptions=t,this._stackTraceConverter=e,this._attributeManager=s,this._debugIdProvider=i}build(t){const{annotations:e,attributes:s}=this._attributeManager.get(),i=l.build(t.attributes),{threads:r,detectedDebugIdentifier:n}=this.getThreads(t),o={uuid:H.uuid(),timestamp:c.toTimestampInSec(t.timestamp),agent:this._sdkOptions.agent,agentVersion:this._sdkOptions.agentVersion,lang:this._sdkOptions.langName,langVersion:this._sdkOptions.langVersion,classifiers:t.classifiers,mainThread:this.MAIN_THREAD_NAME,threads:r,annotations:{...e,...i.annotations,...t.annotations},attributes:{...s,...i.attributes}};return n&&(o.symbolication="sourcemap"),o}getThreads(t){const e={};let s=!1;for(const[i,r]of Object.entries(t.stackTrace)){let n;if(Array.isArray(r))n=r;else{const{message:t,stack:e}=r;n=this._stackTraceConverter.convert(e,t)}i===this.MAIN_THREAD_NAME&&t.skipFrames>0&&n.splice(0,t.skipFrames);for(const t of n){const e=this._debugIdProvider.getDebugId(t.library);e&&(s=!0,t.debug_identifier=e)}e[i]={fault:i===this.MAIN_THREAD_NAME,name:i,stack:n}}return{threads:e,detectedDebugIdentifier:s}}}class z extends Error{constructor(t){super(t??"Operation cancelled.")}}const V=($="AbortController","undefined"!=typeof window?window[$]:"undefined"!=typeof global?global[$]:"undefined"!=typeof self?self[$]:void 0);var $;class Q{_listeners={};_events=new a;addEventListener(t,e,s){t in this._listeners||(this._listeners[t]=[]);const i=t=>"object"==typeof e?e.handleEvent.call(this,t):e.call(this,t),{once:r,signal:n}="object"==typeof s?s:{};if(r?this._events.once(t,i):this._events.on(t,i),n){const s=()=>this.removeEventListener(t,e);n.addEventListener(t,s,{once:!0})}this._listeners[t].push({callback:i,listener:e,options:s})}removeEventListener(t,e){if(!(t in this._listeners))return;const s=this._listeners[t],i=s.filter((t=>t.listener===e));for(const e of i){this._events.off(t,e.callback);const i=s.indexOf(e);s.splice(i,1)}}dispatchEvent(t){return this._events.emit(t.type,t),!t.defaultPrevented}}class W extends Q{aborted=!1;onabort=null;reason;constructor(){super(),Object.defineProperty(this,"aborted",{writable:!0,configurable:!0,enumerable:!1}),Object.defineProperty(this,"onabort",{writable:!0,configurable:!0,enumerable:!1}),Object.defineProperty(this,"reason",{writable:!0,configurable:!0,enumerable:!1})}toString(){return"[object AbortSignal]"}throwIfAborted(){if(this.aborted)throw this.reason}dispatchEvent(t){return"abort"===t.type&&(this.aborted=!0,"function"==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}any(t){return G(...t)}}let J=class{signal;constructor(){this.signal=new W,Object.defineProperty(this,"signal",{configurable:!0,enumerable:!1})}abort(t){let e;try{e=new Event("abort")}catch(t){if("undefined"!=typeof document){const t=document;!t.createEvent&&t.createEventObject?(e=t.createEventObject(),e.type="abort"):(e=document.createEvent("Event"),e.initEvent("abort",!1,!1))}else e={type:"abort",bubbles:!1,cancelable:!1}}let s=t;if(void 0===s)if("undefined"==typeof document)s=new z("This operation was aborted");else try{s=new DOMException("signal is aborted without reason")}catch(t){s=new z("This operation was aborted")}this.signal.reason=s,this.signal.dispatchEvent(e)}toString(){return"[object AbortController]"}};function X(){return V?new V:new J}function G(...t){const e=X();function s(){for(const e of t)e&&e.removeEventListener("abort",i)}function i(){e.abort(),s()}for(const e of t)if(e){if(e.aborted){i();break}e.addEventListener("abort",i)}return e.signal.dispose=s,e.signal}function Y(t){t&&"number"!=typeof t&&t.unref()}"undefined"!=typeof Symbol&&Symbol.toStringTag&&(J.prototype[Symbol.toStringTag]="AbortController",W.prototype[Symbol.toStringTag]="AbortSignal");class Z{bucketCount;_records;_recordBuckets={};constructor(t=3){this.bucketCount=t,this._records=[],this._recordBuckets={}}find(t){return this._records.find(t)}add(t){void 0===this._recordBuckets[t.id]?(this._records.push(t),this._recordBuckets[t.id]=0):this._recordBuckets[t.id]=0}get(){return this._records.map((t=>({...t})))}getBucket(t){const e=[];for(const s of this._records)this._recordBuckets[s.id]===t&&e.push(s);return e}count(){return this._records.length}countByType(){return this._records.reduce(((t,e)=>(t[e.type]++,t)),{})}remove(t){const e="string"==typeof t?t:t.id,s=this._records.findIndex((t=>t.id===e));-1!==s&&(this._records.splice(s,1),delete this._recordBuckets[e])}increaseBucket(t){for(const[e,s]of Object.entries(this._recordBuckets)){if(s<t)continue;const i=s+1;i>=this.bucketCount&&this.remove(e),this._recordBuckets[e]=i}}load(t){for(const e of t)this.add(e)}dropOverLimits(t){const e={...t},s=[];for(let t=this._records.length-1;t>=0;t--){const i=this._records[t];0===e[i.type]?(this.remove(i),s.push(i)):e[i.type]--}return s}}class K extends a{_options;_storageProvider;_requestHandler;_sessionFiles;get enabled(){return this._enabled}_abortController=X();_databaseRecordContext;_storageProviders=[];_recordLimits;_retryInterval;_intervalId;_enabled=!1;constructor(t,e,s,i){super(),this._options=t,this._storageProvider=e,this._requestHandler=s,this._sessionFiles=i,this._databaseRecordContext=new Z(this._options?.maximumRetries),this._recordLimits={report:this._options?.maximumNumberOfRecords??8,attachment:this._options?.maximumNumberOfAttachmentRecords??10},this._retryInterval=this._options?.retryInterval??6e4}initialize(){if(this._enabled)return this._enabled;if(!1===this._options?.enable)return!1;if(!this._storageProvider.start())return!1;const t=this._sessionFiles?.lockPreviousSessions();return this.loadReports().then((()=>{this.setupDatabaseAutoSend()})).finally((()=>t&&this._sessionFiles?.unlockPreviousSessions(t))),this._enabled=!0,!0}bind({client:t}){this._enabled||!1!==this._options?.enable&&(t.on("before-send",((t,e,s)=>{const i=this.add(e,s);i&&!i.locked&&(i.locked=!0)})),t.on("after-send",((t,e,s,i)=>{const r=this._databaseRecordContext.find((t=>"report"===t.type&&t.data.uuid===e.uuid));r&&(r.locked=!1,"Ok"===i.status&&(this.remove(r),this._sessionFiles?.unlockPreviousSessions(r.id)))})))}add(t,e){if(!this._enabled)return;const s=t.attributes?.["application.session"],i={type:"report",data:t,timestamp:c.now(),id:H.uuid(),locked:!1,attachments:e,sessionId:"string"==typeof s?s:void 0};this.prepareDatabase([i]);return this._storageProvider.add(i)?(this._databaseRecordContext.add(i),this.lockSessionWithRecord(i),this.emit("added",i),i):void 0}addAttachment(t,e,s){if(!this._enabled)return;const i={type:"attachment",timestamp:c.now(),id:H.uuid(),rxid:t,locked:!1,attachment:e,sessionId:s};this.prepareDatabase([i]);return this._storageProvider.add(i)?(this._databaseRecordContext.add(i),this.lockSessionWithRecord(i),this.emit("added",i),i):void 0}get(){return this._databaseRecordContext.get()}count(){return this._databaseRecordContext.count()}countByType(){return this._databaseRecordContext.countByType()}dispose(){this._enabled=!1,clearInterval(this._intervalId),this._abortController.abort()}remove(t){if(!this._enabled)return;const e=Array.isArray(t)?t:[t];for(const t of e)this._databaseRecordContext.remove(t),this._storageProvider.delete(t),this._sessionFiles?.unlockPreviousSessions(t.id),this.emit("removed",t)}addStorageProvider(t){if(this._enabled)throw new Error("Cannot add storage provider after the database has been enabled.");this._storageProviders.push(t)}async flush(t){const e=c.now();await this.send(t);const s=this.get().filter((t=>t.timestamp<=e));for(const e of s){if(t?.aborted)return;this.remove(e)}}async send(t){for(let e=0;e<this._databaseRecordContext.bucketCount;e++){const s=[...this._databaseRecordContext.getBucket(e)],i=G(t,this._abortController.signal);try{for(const t of s){if(!this.enabled)return;if(!t.locked)try{t.locked=!0,this.emit("before-send",t);const s="report"===t.type?await this._requestHandler.send(t.data,t.attachments,i):await this._requestHandler.sendAttachment(t.rxid,t.attachment,i);if(this.emit("after-send",t,s),"Ok"===s.status||"Unsupported"===s.status||"Report skipped"===s.status){this.remove(t);continue}return void this._databaseRecordContext.increaseBucket(e)}finally{t.locked=!1}}}finally{i.dispose()}}}prepareDatabase(t){const e={...this._recordLimits};for(const s of t)e[s.type]--;const s=this._databaseRecordContext.dropOverLimits(e);this.remove(s)}async loadReports(){const t=await this._storageProvider.get(),e={attachment:0,report:0},s=[],i=[];for(const r of t)e[r.type]>=this._recordLimits[r.type]?i.push(r):(s.push(r),e[r.type]++);i.length&&this.remove(i),this.prepareDatabase(s),this._databaseRecordContext.load(s);for(const t of s)this.lockSessionWithRecord(t),this.emit("added",t)}async setupDatabaseAutoSend(){if(!this._enabled)return;if(!1===this._options?.autoSend)return;this._intervalId=setInterval((async()=>{await this.send()}),this._retryInterval),Y(this._intervalId),await this.send()}lockSessionWithRecord(t){if(!this._sessionFiles)return;const e=t.sessionId;if("string"!=typeof e)return void this._sessionFiles.lockPreviousSessions(t.id);const s=this._sessionFiles.getSessionWithId(e);s?.lock(t.id)}}function tt(t){return"filePath"in t&&"string"==typeof t.filePath}class et{type="attachment";id;rxid;timestamp;attachment;sessionId;locked;constructor(t){this.attachment=t.attachment,this.id=t.id,this.timestamp=t.timestamp,this.rxid=t.rxid,this.sessionId=t.sessionId,this.locked=!1}static fromRecord(t){return new et(t)}static fromJson(t,e){try{const s="string"==typeof t?JSON.parse(t):t;if(!tt(s.attachment))return;if(!e.existsSync(s.attachment.filePath))return;const i=e.createAttachment(s.attachment.filePath,s.attachment.name);return new et({...s,attachment:i})}catch{return}}}class st{attachments;type="report";data;id;timestamp;sessionId;locked;constructor(t,e){this.attachments=e,this.data=t.data,this.id=t.id,this.timestamp=t.timestamp,this.sessionId=t.sessionId,this.locked=!1}static fromRecord(t){return new st(t,t.attachments.filter(tt))}static fromJson(t,e){try{const s="string"==typeof t?JSON.parse(t):t,i=s.attachments?s.attachments.filter(tt).map((t=>e.createAttachment(t.filePath,t.name))):[];return new st(s,i)}catch{return}}}const it={fromRecord(t){switch(t.type){case"attachment":return et.fromRecord(t);case"report":return st.fromRecord(t);default:throw new Error("unknown record type")}},fromJson(t,e){try{const s=JSON.parse(t);switch(s.type){case"attachment":return et.fromJson(s,e);case"report":return st.fromJson(s,e);default:return}}catch{return}}};class rt{_fileSystem;_path;_enabled=!0;RECORD_SUFFIX="-record.json";constructor(t,e){this._fileSystem=t,this._path=e}static createIfValid(t,e){if(e&&e.enable){if(e.enable&&!e.path)throw new Error("Missing mandatory path to the database. Please define the database.path option in the configuration.");return new rt(t,e.path)}}start(){return!1!==this._enabled}delete(t){const e=this.getRecordPath(t.id);return this.unlinkRecord(e)}add(t){const s=this.getRecordPath(t.id);try{return this._fileSystem.writeFileSync(s,JSON.stringify(it.fromRecord(t),e())),!0}catch{return!1}}async get(){const t=(await this._fileSystem.readDir(this._path)).filter((t=>t.endsWith(this.RECORD_SUFFIX))).map((t=>this._path+"/"+t)),e=[];for(const s of t)try{const t=await this._fileSystem.readFile(s),i=it.fromJson(t,this._fileSystem);if(!i){await this._fileSystem.unlink(s);continue}e.push(i)}catch{await this._fileSystem.unlink(s)}return e}unlinkRecord(t){if(!this._fileSystem.existsSync(t))return!1;try{return this._fileSystem.unlinkSync(t),!0}catch{return!1}}getRecordPath(t){return this._path+"/"+`${t}${this.RECORD_SUFFIX}`}}class nt{metricGroupName;metricGroupValue;attributes;id=H.uuid();constructor(t,e,s={}){this.metricGroupName=t,this.metricGroupValue=e,this.attributes=s}toJSON(){return{timestamp:c.toTimestampInSec(c.now()),attributes:this.attributes,[this.metricGroupName]:this.metricGroupValue}}}class ot extends nt{constructor(t,e={}){super("metric_group",t,e)}}class at extends nt{constructor(t){super("unique",["guid"],t)}}class ct{_options;_sessionProvider;_attributeManager;_summedEventsSubmissionQueue;_uniqueEventsSubmissionQueue;get sessionId(){return this._sessionProvider.sessionId}DEFAULT_UPDATE_INTERVAL=c.convertSecondsToMilliseconds(1800);DEFAULT_SERVER_URL="https://events.backtrace.io";metricsHost;_updateInterval;_updateIntervalId;_abortController;constructor(t,e,s,i,r){this._options=t,this._sessionProvider=e,this._attributeManager=s,this._summedEventsSubmissionQueue=i,this._uniqueEventsSubmissionQueue=r,this.metricsHost=this._options.metricsSubmissionUrl??this.DEFAULT_SERVER_URL,this._updateInterval=this._options.autoSendInterval??this.DEFAULT_UPDATE_INTERVAL,this._abortController=X()}initialize(){this._sessionProvider.newSession&&(this.addSummedEvent("Application Launches"),this.handleAbort((()=>this.send(this._abortController.signal))),0!==this._updateInterval&&(this._updateIntervalId=setInterval((()=>{this.handleAbort((()=>this.send(this._abortController.signal)))}),this._updateInterval),Y(this._updateIntervalId)))}count(){return this._summedEventsSubmissionQueue?.total??0+this._uniqueEventsSubmissionQueue?.total??0}addSummedEvent(t,e={}){if(!t)return!1;const s=this.convertAttributes({...this._attributeManager.get().attributes,...l.build(e??{}).attributes});return this._summedEventsSubmissionQueue.add(new ot(t,s)),!0}async send(t){return!!this._sessionProvider.shouldSend()&&(await Promise.all([this.sendUniqueEvent(t),this._summedEventsSubmissionQueue.send(t)]),this._sessionProvider.afterMetricsSubmission(),!0)}dispose(){this._abortController.abort(),this._updateIntervalId&&clearInterval(this._updateIntervalId),this._uniqueEventsSubmissionQueue.dispose&&this._uniqueEventsSubmissionQueue.dispose(),this._summedEventsSubmissionQueue.dispose&&this._summedEventsSubmissionQueue.dispose()}async sendUniqueEvent(t){const{attributes:e}=this._attributeManager.get();this._uniqueEventsSubmissionQueue.add(new at(this.convertAttributes(e))),await this._uniqueEventsSubmissionQueue.send(t)}convertAttributes(t){return Object.keys(t).filter((e=>null!=t[e])).reduce(((e,s)=>(e[s]=t[s]?.toString(),e)),{})}async handleAbort(t){try{return await t(),!0}catch(t){if(t instanceof z)return!1;throw t}}}class ut{static wait(t,e){return new Promise(((s,i)=>{let r;function n(){clearTimeout(r),i(new z)}if(e?.aborted)return n();r=setTimeout((()=>{e?.removeEventListener("abort",n),s()}),t),e?.addEventListener("abort",n)}))}}class dt{_submissionUrl;_eventName;_requestHandler;_metricMetadata;maximumEvents;get total(){return this._events.length}get submissionUrl(){return this._submissionUrl}DELAY_BETWEEN_REQUESTS=c.convertSecondsToMilliseconds(10);_events=[];_numberOfDroppedRequests=0;_abortController;MAXIMUM_NUMBER_OF_ATTEMPTS=3;constructor(t,e,s,i,r=50){this._submissionUrl=t,this._eventName=e,this._requestHandler=s,this._metricMetadata=i,this.maximumEvents=r,this._abortController=X()}add(t){this._events.push(t),this.reachedLimit()&&this.send()}async send(t){const e=this._events.splice(0),s=G(t,this._abortController.signal);try{return await this.submit(e,s)}finally{s.dispose()}}dispose(){this._abortController.abort()}async submit(t,s){for(let i=0;i<this.MAXIMUM_NUMBER_OF_ATTEMPTS;i++){if("Ok"===(await this._requestHandler.post(this._submissionUrl,JSON.stringify({...this._metricMetadata,[this._eventName]:t,metadata:{dropped_events:this._numberOfDroppedRequests}},e()),s)).status)return void(this._numberOfDroppedRequests=0);this._numberOfDroppedRequests++,await ut.wait(2**i*this.DELAY_BETWEEN_REQUESTS,s)}this.returnEventsIfPossible(t)}returnEventsIfPossible(t){this.maximumEvents<this._events.length+t.length||this._events.unshift(...t)}reachedLimit(){return this.maximumEvents===this._events.length&&0!==this.maximumEvents}}class lt{_options;_sessionProvider;_attributeManager;_requestHandler;DEFAULT_UPDATE_INTERVAL=c.convertSecondsToMilliseconds(1800);APPLICATION_VERSION_ATTRIBUTE="application.version";APPLICATION_ATTRIBUTE="application";constructor(t,e,s,i){this._options=t,this._sessionProvider=e,this._attributeManager=s,this._requestHandler=i}build(t,e){const s={...this.optionsWithDefaults(),...this._options.metrics??{}};if(!s.enable)return;const i=this.verifyAttributeSetup();return i&&(t=t??this.createUniqueEventSubmissionQueue(s.metricsSubmissionUrl,i))&&(e=e??this.createSummedEventSubmissionQueue(s.metricsSubmissionUrl,i))?new ct(s,this._sessionProvider,this._attributeManager,e,t):void 0}verifyAttributeSetup(){const{attributes:t}=this._attributeManager.get(),e=t[this.APPLICATION_ATTRIBUTE],s=t[this.APPLICATION_VERSION_ATTRIBUTE];if(e&&s)return{application:e,applicationVersion:s}}createUniqueEventSubmissionQueue(t,e){const s=n.generateUniqueEventsUrl(t,this._options.url,this._options.token);if(s)return new dt(s,"unique_events",this._requestHandler,{[this.APPLICATION_ATTRIBUTE]:e.application,appversion:e.applicationVersion},this._options?.metrics?.size)}createSummedEventSubmissionQueue(t,e){const s=n.generateSummedEventsUrl(t,this._options.url,this._options.token);if(s)return new dt(s,"summed_events",this._requestHandler,{[this.APPLICATION_ATTRIBUTE]:e.application,appversion:e.applicationVersion},this._options?.metrics?.size)}optionsWithDefaults(){return{enable:!0,autoSendInterval:this.DEFAULT_UPDATE_INTERVAL,metricsSubmissionUrl:"https://events.backtrace.io",size:50}}}class ht{newSession=!0;sessionId=H.uuid();_lastActive=0;get lastActive(){return this._lastActive}afterMetricsSubmission(){this._lastActive=c.now()}shouldSend(){return!0}}class mt{MAXIMUM_TIME_IN_QUEUE=6e4;_reportPerMin;_watcherEnable;_reportQueue=[];get enabled(){return this._watcherEnable}constructor(t){if(null==t&&(t=0),t<0)throw new Error("ReportPerMinute argument must be greater or equal to zero");this._reportPerMin=t,this._watcherEnable=t>0}skipReport(){const t=c.now();return!!this._watcherEnable&&(this.clear(t),this._reportQueue.length>=this._reportPerMin||(this._reportQueue.push(t),!1))}clear(t){if(0!==this._reportQueue.length&&!(t-this._reportQueue[0]<this.MAXIMUM_TIME_IN_QUEUE))for(let e=this._reportQueue.length;0!=e;e--)if(t-this._reportQueue[e-1]>this.MAXIMUM_TIME_IN_QUEUE)return void(this._reportQueue=this._reportQueue.slice(e))}}class bt extends a{static _instance;get enabled(){return this._enabled}get sessionId(){return this._sessionProvider.sessionId}get agent(){return this._sdkOptions.agent}get agentVersion(){return this._sdkOptions.agentVersion}get attributes(){return this.attributeManager.get().attributes}get annotations(){return this.attributeManager.get().annotations}get metrics(){return this._modules.get(ct)}get breadcrumbs(){return this._modules.get(B)}get database(){return this._modules.get(K)}get attachments(){return this.attachmentManager.get()}get modules(){return this._modules}get sessionFiles(){return this._modules.get(vt)}options;attributeManager;attachmentManager;fileSystem;_modules=new Map;_dataBuilder;_reportSubmission;_rateLimitWatcher;_sessionProvider;_sdkOptions;_requestHandler;_enabled=!1;constructor(t){super(),this.options=t.options,this.fileSystem=t.fileSystem,this._sdkOptions=t.sdkOptions,this._sessionProvider=t.sessionProvider??new ht,this._reportSubmission=t.reportSubmission??new i(this.options,t.requestHandler),this._rateLimitWatcher=new mt(this.options.rateLimit),this._requestHandler=t.requestHandler;const e=[new m(this.agent,this.agentVersion,this._sessionProvider.sessionId)];t.attributeProviders&&e.push(...t.attributeProviders),this.options.userAttributes&&e.push(new b(this.options.userAttributes)),this.attributeManager=new h(e),this.attachmentManager=new d,this.options.attachments&&this.attachmentManager.add(...this.options.attachments);const s=t.stackTraceConverter??new F;if(this._dataBuilder=new j(this._sdkOptions,s,this.attributeManager,new St(s,t.debugIdMapProvider)),!0===this.options?.database?.enable&&t.fileSystem){const e=rt.createIfValid(t.fileSystem,this.options.database);if(this.fileSystem){const t=new vt(this.fileSystem,this.options.database.path,this.sessionId,this.options.database.maximumOldSessions??1);this._modules.set(vt,t)}if(e){const t=new K(this.options.database,e,this._reportSubmission,this.sessionFiles);this._modules.set(K,t)}}const r=new lt(this.options,this._sessionProvider,this.attributeManager,t.requestHandler).build(t.uniqueMetricsQueue,t.summedMetricsQueue);if(r&&this._modules.set(ct,r),!1!==this.options.breadcrumbs?.enable){const e=new B(this.options?.breadcrumbs,t.breadcrumbsSetup);this._modules.set(B,e)}if(t.modules)for(const e of t.modules)this.addModule(e)}initialize(){if(this.validateAttributes(),this.fileSystem&&this.options.database?.createDatabaseDirectory){if(!this.options.database.path)throw new Error("Missing mandatory path to the database. Please define the database.path option in the configuration.");this.fileSystem.createDirSync(this.options.database?.path)}for(const t of this._modules.values())t.bind&&t.bind(this.getModuleBindData()),t.initialize&&t.initialize();this.sessionFiles?.clearPreviousSessions(),this._enabled=!0,bt._instance=this}addAttribute(t){this.attributeManager.add(t)}addAttachment(...t){this.attachmentManager.add(...t)}send(e,s,i=[],r){if(!this._enabled)return Promise.resolve(t.SdkDisabled());if(this._rateLimitWatcher.skipReport())return Promise.resolve(t.OnLimitReached("Client"));const n=this.isReport(e)?void 0:s;r=this.isReport(e)?s:r;const o=this.isReport(e)?e:new u(e,n,[],{skipFrames:this.skipFrameOnMessage(e)});if(this.emit("before-skip",o),this.options.skipReport&&this.options.skipReport(o))return Promise.resolve(t.ReportSkipped());const a=this.generateSubmissionData(o);if(!a)return Promise.resolve(t.ReportSkipped());const c=this.generateSubmissionAttachments(o,i);return this.emit("before-send",o,a,c),this._reportSubmission.send(a,c,r).then((t=>(this.emit("after-send",o,a,c,t),t)))}dispose(){this._enabled=!1;for(const t of this._modules.values())t.dispose&&t.dispose();bt.destroy()}addModule(t,e){let s;if("function"==typeof t?s=t:(e=t,s=Object.getPrototypeOf(e)),!e)throw new Error("Module implementation is required.");this._modules.set(s,e),this._enabled&&(e.bind&&e.bind(this.getModuleBindData()),e.initialize&&e.initialize())}generateSubmissionData(t){const e=this._dataBuilder.build(t);return this.options.beforeSend?this.options.beforeSend(e):e}generateSubmissionAttachments(t,e){return[...this.attachmentManager.get(),...t.attachments??[],...e??[]]}skipFrameOnMessage(t){return"string"==typeof t?1:0}isReport(t){return t instanceof u}getModuleBindData(){return{client:this,options:this.options,attributeManager:this.attributeManager,attachmentManager:this.attachmentManager,reportSubmission:this._reportSubmission,requestHandler:this._requestHandler,database:this.database,sessionFiles:this.sessionFiles,fileSystem:this.fileSystem}}static destroy(){this._instance=void 0}validateAttributes(){function t(t){if(!t.application||!t["application.version"])return"application and application.version attributes must be defined."}if(!t(this.attributeManager.get("scoped").attributes))return;const e=t(this.attributeManager.get().attributes);if(e)throw new Error(e)}}class pt{clientSetup;constructor(t){this.clientSetup=t}addAttributeProvider(t){return this.clientSetup.attributeProviders?this.clientSetup.attributeProviders.push(t):this.clientSetup.attributeProviders=[t],this}useBreadcrumbSubscriber(t){return this.clientSetup.breadcrumbsSetup||(this.clientSetup.breadcrumbsSetup={}),this.clientSetup.breadcrumbsSetup.subscribers?this.clientSetup.breadcrumbsSetup.subscribers.push(t):this.clientSetup.breadcrumbsSetup.subscribers=[t],this}useBreadcrumbsStorage(t){return this.clientSetup.breadcrumbsSetup||(this.clientSetup.breadcrumbsSetup={}),this.clientSetup.breadcrumbsSetup.storage="function"==typeof t?t:()=>t,this}useSessionProvider(t){return this.clientSetup.sessionProvider=t,this}useRequestHandler(t){return this.clientSetup.requestHandler=t,this}useStackTraceConverter(t){return this.clientSetup.stackTraceConverter=t,this}useFileSystem(t){return this.clientSetup.fileSystem=t,this}useReportSubmission(t){return this.clientSetup.reportSubmission=t,this}useSummedMetricsQueue(t){return this.clientSetup.summedMetricsQueue=t,this}useUniqueMetricsQueue(t){return this.clientSetup.uniqueMetricsQueue=t,this}useModule(t){return this.clientSetup.modules?this.clientSetup.modules.push(t):this.clientSetup.modules=[t],this}}class ft{name;data;constructor(t,e){this.name=t,this.data=e}get(){return this.data}}class gt{name;data;constructor(t,e){this.name=t,this.data=e}get(){return new Blob([this.data.buffer])}}const _t="bt-session",wt=t=>!!t;class vt{_fileSystem;_directory;sessionId;_maxPreviousLockedSessions;timestamp;_lockable;marker;_events=new a;_escapedSessionId;_locks=new Set;_previousSession;_cleared=!1;constructor(t,e,s,i=1,r=Date.now(),n=!0){this._fileSystem=t,this._directory=e,this.sessionId=s,this._maxPreviousLockedSessions=i,this.timestamp=r,this._lockable=n,this._escapedSessionId=this.escapeFileName(s),this.marker=this.getFileName(_t)}initialize(){this.createSessionMarker()}getPreviousSession(){if(this._previousSession)return this._previousSession;const t=this.readDirectoryFiles();if(!t.length)return;const e=t.filter((t=>t.startsWith(_t))).map((t=>this.getFileSession(t))).filter(wt).sort(((t,e)=>e.timestamp-t.timestamp)),s=e.find((t=>t.sessionId===this.sessionId)),i=s?e.filter((({timestamp:t})=>s.timestamp>t))[0]:e[0];return i?this._previousSession=new vt(this._fileSystem,this._directory,i.sessionId,this._maxPreviousLockedSessions-1,i.timestamp,this._maxPreviousLockedSessions>0):void 0}getSessionWithId(t){let e=this;for(;e&&e.sessionId!==t;)e=e.getPreviousSession();return e}getPreviousSessions(t=1/0){const e=[];let s=this.getPreviousSession();for(;s&&t>0;)e.push(s),t--,s=s.getPreviousSession();return e}lockPreviousSessions(t){t=t??H.uuid();for(const e of this.getPreviousSessions(this._maxPreviousLockedSessions))e.lock(t);return t}unlockPreviousSessions(t){for(const e of this.getPreviousSessions(this._maxPreviousLockedSessions))e.unlock(t)}clearPreviousSessions(){for(const t of this.getPreviousSessions())t.clearSession()}getFileName(t){return this.throwIfCleared(),this._directory+"/"+`${this.escapeFileName(t)}_${this._escapedSessionId}_${this.timestamp}`}getSessionFiles(){this.throwIfCleared();return this.readDirectoryFiles().map((t=>this.getFileSession(t))).filter(wt).filter((({sessionId:t})=>t===this.sessionId)).map((({file:t})=>this._directory+"/"+t))}clearSession(){if(this._locks.size>0)this._events.once("unlocked",(()=>this.clearSession()));else if(!this._cleared)try{const t=this.getSessionFiles();for(const e of t)this._fileSystem.unlinkSync(e)}catch{}finally{this._cleared=!0}}lock(t){if(!this._cleared&&this._lockable)return t=t??H.uuid(),this._locks.add(t),t}unlock(t){this._locks.delete(t),0===this._locks.size&&this._events.emit("unlocked")}getFileSession(t){const[e,s]=this.splitByOneChar(t,"_").slice(-2),i=parseInt(s);if(!isNaN(i))return{file:t,escapedSessionId:e,timestamp:i,sessionId:this.unescapeFileName(e)}}readDirectoryFiles(){try{return this._fileSystem.readDirSync(this._directory)}catch{return[]}}createSessionMarker(){this._fileSystem.writeFileSync(this.marker,"")}escapeFileName(t){return t.replace(/_/g,"__")}unescapeFileName(t){return t.replace(/__/g,"_")}splitByOneChar(t,e){const s=[];let i=0,r=t.indexOf(e);for(;-1!==r;)t[r+1]===e?r=t.indexOf(e,r+2):(s.push(t.substring(i,r)),i=r+1,r=t.indexOf(e,i));return s.push(t.substring(i)),s}throwIfCleared(){if(this._cleared)throw new Error("This session files are cleared.")}}class St{_stackTraceConverter;_debugIdMapProvider;_fileDebugIds;constructor(t,e){this._stackTraceConverter=t,this._debugIdMapProvider=e,this._fileDebugIds=this.loadDebugIds()}getDebugId(t){const e=this._fileDebugIds[t];return e||(this._fileDebugIds=this.loadDebugIds(),this._fileDebugIds[t])}loadDebugIds(){const t=this._debugIdMapProvider?.getDebugIdMap();if(!t)return{};const e=(new Error).message,s={};for(const[i,r]of Object.entries(t)){const t=this._stackTraceConverter.convert(i,e);if(!t.length)continue;s[t[0].library]=r}return s}}class yt{_variable;constructor(t){this._variable=t}getDebugIdMap(){return this._variable._btDebugIds??{}}}const kt={langName:"js",langVersion:navigator.userAgent,agent:"@backtrace/browser",agentVersion:"0.5.0"};function Et(t,e,s,i){return new(s||(s=Promise))((function(r,n){function o(t){try{c(i.next(t))}catch(t){n(t)}}function a(t){try{c(i.throw(t))}catch(t){n(t)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(o,a)}c((i=i.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class It{constructor(t){var e;this.UPLOAD_FILE_NAME="upload_file",this.JSON_HEADERS={"Content-type":"application/json","Transfer-Encoding":"chunked"},this.MULTIPART_HEADERS={"Transfer-Encoding":"chunked"},this._timeout=null!==(e=null==t?void 0:t.timeout)&&void 0!==e?e:15e3}postError(t,e,s,i){return Et(this,void 0,void 0,(function*(){const r=0===s.length?e:this.createFormData(e,s);return this.post(t,r,i)}))}post(e,s,i){return Et(this,void 0,void 0,(function*(){const n=new AbortController,o=setTimeout((()=>n.abort()),this._timeout),a=G(i,n.signal);try{const i=yield fetch(e,{method:"POST",body:s,headers:"string"==typeof s?this.JSON_HEADERS:this.MULTIPART_HEADERS,signal:a});switch(clearInterval(o),i.status){case 200:{const e=yield i.json();return t.Ok(e)}case 401:case 403:return t.OnInvalidToken();case 429:return t.OnLimitReached();default:return t.OnInternalServerError(i.statusText)}}catch(e){return e instanceof Error?"AbortError"===e.name?t.OnNetworkingError("Timeout"):r.isConnectionError(e)?t.OnNetworkingError(e.message):t.OnUnknownError(e.message):t.OnUnknownError(e)}finally{"dispose"in a&&"function"==typeof a.dispose&&a.dispose()}}))}createFormData(t,e){const s=new FormData;if(s.append(this.UPLOAD_FILE_NAME,t),!e||0===e.length)return s;for(const t of e){const e=t.get();e&&s.append(`attachment_${t.name}`,e)}return s}}class Tt extends o{constructor(t){var e;super(t,null!==(e=t.requestHandler)&&void 0!==e?e:new It(t.requestHandlerOptions))}}class xt{get lastActive(){return this._lastActive}constructor(){if(this.SESSION_LAST_ACTIVE="backtrace-last-active",this.SESSION_GUID="backtrace-guid",this.newSession=!0,this.sessionId=H.uuid(),this._lastActive=0,!window.localStorage)return;const t=this.readLastActiveTimestamp();if(!t||c.now()-t>xt.PERSISTENCE_INTERVAL)return this.updateLastActiveTimestamp(),void localStorage.setItem(this.SESSION_GUID,this.sessionId);this._lastActive=t,this.newSession=!1,this.sessionId=localStorage.getItem(this.SESSION_GUID)}afterMetricsSubmission(){this.updateLastActiveTimestamp()}shouldSend(){return!1===document.hidden}readLastActiveTimestamp(){const t=localStorage.getItem(this.SESSION_LAST_ACTIVE);if(!t)return;const e=parseInt(t,10);return isNaN(e)?void 0:e}updateLastActiveTimestamp(){this._lastActive=c.now(),localStorage.setItem(this.SESSION_LAST_ACTIVE,this._lastActive.toString(10))}}xt.PERSISTENCE_INTERVAL=c.convertSecondsToMilliseconds(1800);class At{get type(){return"scoped"}constructor(t){if(this.APPLICATION_ATTRIBUTE="application",this.APPLICATION_VERSION_ATTRIBUTE="application.version",this._application=t.name,this._applicationVersion=t.version,!this._application||!this._applicationVersion)throw new Error("Missing application/application version information!")}get(){return{[this.APPLICATION_ATTRIBUTE]:this._application,[this.APPLICATION_VERSION_ATTRIBUTE]:this._applicationVersion}}}var Mt,Pt,Ot="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Nt={exports:{}};Mt=Nt,Pt=Nt.exports,function(t,e){var s="function",i="undefined",r="object",n="string",o="major",a="model",c="name",u="type",d="vendor",l="version",h="architecture",m="console",b="mobile",p="tablet",f="smarttv",g="wearable",_="embedded",w="Amazon",v="Apple",S="ASUS",y="BlackBerry",k="Browser",E="Chrome",I="Firefox",T="Google",x="Hua