@groundcover/browser 0.0.22 → 0.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,7 +80,7 @@ groundcover.init({
80
80
  options: {
81
81
  batchSize: 50,
82
82
  sessionSampleRate: 0.5, // 50% sessions sampled
83
- eventsSampleRate: 0.5,
83
+ eventSampleRate: 0.5,
84
84
  },
85
85
  });
86
86
  ```
package/dist/index.d.mts CHANGED
@@ -1,3 +1,15 @@
1
+ type BaseEvent = {
2
+ type: "dom.event" | "exception" | "network" | "log" | "pageload" | "navigation" | "custom" | "performance";
3
+ timestamp?: number;
4
+ end_timestamp?: number;
5
+ start_timestamp?: number;
6
+ span_name?: string;
7
+ id: string;
8
+ spanId: string;
9
+ parentSpanId: string | undefined;
10
+ traceId: string | undefined;
11
+ attributes?: Record<string, unknown>;
12
+ };
1
13
  type UserIdentifiers = {
2
14
  id: string;
3
15
  email: string;
@@ -6,7 +18,125 @@ type UserIdentifiers = {
6
18
  organization: string;
7
19
  properties: Record<string, unknown>;
8
20
  };
21
+ type DomEventAttributes = {
22
+ dom_event_type: string;
23
+ dom_event_coordinates: {
24
+ clientX: number;
25
+ clientY: number;
26
+ };
27
+ dom_event_target: {
28
+ tagName: string;
29
+ id: string;
30
+ className: string;
31
+ text: string;
32
+ };
33
+ dom_event_selector: string;
34
+ dom_event_key_code: string;
35
+ };
36
+ type NetworkEventAttributes = {
37
+ type: "HTTP";
38
+ resource_name: string;
39
+ status: string;
40
+ subType: string;
41
+ level?: string;
42
+ timestamp?: number;
43
+ operation: {
44
+ name: string;
45
+ startTime?: number;
46
+ endTime?: number;
47
+ };
48
+ http: {
49
+ url: {
50
+ full: string;
51
+ };
52
+ route: string;
53
+ path: string;
54
+ status: string;
55
+ method: string;
56
+ request: {
57
+ headers: Record<string, string>;
58
+ method: string;
59
+ };
60
+ response: {
61
+ headers: Record<string, string>;
62
+ status_code: string;
63
+ };
64
+ duration_ms?: number;
65
+ };
66
+ gc: {
67
+ request: {
68
+ body: string;
69
+ };
70
+ response: {
71
+ body: string;
72
+ };
73
+ };
74
+ error?: {
75
+ type: string;
76
+ };
77
+ };
78
+ type Stacktrace = {
79
+ filename: string;
80
+ function: string;
81
+ lineno: number;
82
+ colno: number;
83
+ };
84
+ type ErrorEventAttributes = {
85
+ error_type: string;
86
+ error_message: string;
87
+ error_stacktrace?: Array<Stacktrace>;
88
+ error_fingerprint: string;
89
+ error_handled: boolean;
90
+ };
91
+ type LogEventAttributes = {
92
+ message: string;
93
+ level: string;
94
+ };
95
+ type PageLoadEventAttributes = {
96
+ page_url: string;
97
+ page_resources: {
98
+ count: number;
99
+ totalSize: number;
100
+ totalDuration: number;
101
+ byType: {
102
+ [key: string]: {
103
+ count: number;
104
+ size: number;
105
+ duration: number;
106
+ };
107
+ };
108
+ };
109
+ page_referrer: string;
110
+ page_load_time: number;
111
+ };
112
+ type NavigationEventAttributes = {
113
+ page_url: string;
114
+ };
115
+ type UserDefinedEventAttributes = {
116
+ custom_event_name: string;
117
+ custom_event_attributes?: Record<string, unknown>;
118
+ };
119
+ type PerformanceEventAttributes = {
120
+ performance_metric_name: string;
121
+ performance_metric_value: number;
122
+ performance_metric_id: string;
123
+ performance_metric_navigation_type: string;
124
+ };
9
125
 
126
+ type Event<T extends BaseEvent["type"], A> = Omit<BaseEvent, "attributes"> & {
127
+ type: T;
128
+ attributes: A;
129
+ };
130
+ type EventTypes = {
131
+ "dom.event": Event<"dom.event", DomEventAttributes>;
132
+ exception: Event<"exception", ErrorEventAttributes>;
133
+ network: Event<"network", NetworkEventAttributes>;
134
+ log: Event<"log", LogEventAttributes>;
135
+ pageload: Event<"pageload", PageLoadEventAttributes>;
136
+ navigation: Event<"navigation", NavigationEventAttributes>;
137
+ custom: Event<"custom", UserDefinedEventAttributes>;
138
+ performance: Event<"performance", PerformanceEventAttributes>;
139
+ };
10
140
  interface SDKOptions {
11
141
  batchSize: number;
12
142
  batchTimeout: number;
@@ -17,11 +147,14 @@ interface SDKOptions {
17
147
  debug: boolean;
18
148
  maskFields: string[];
19
149
  tracePropagationUrls: string[];
150
+ beforeSend?: (event: EventTypes[keyof EventTypes]) => boolean;
151
+ excludedUrls?: Array<string | RegExp>;
20
152
  }
21
153
 
22
154
  declare function init(params: {
23
155
  cluster: string;
24
156
  environment: string;
157
+ namespace: string;
25
158
  appId: string;
26
159
  userIdentifier?: Partial<UserIdentifiers>;
27
160
  dsn: string;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,15 @@
1
+ type BaseEvent = {
2
+ type: "dom.event" | "exception" | "network" | "log" | "pageload" | "navigation" | "custom" | "performance";
3
+ timestamp?: number;
4
+ end_timestamp?: number;
5
+ start_timestamp?: number;
6
+ span_name?: string;
7
+ id: string;
8
+ spanId: string;
9
+ parentSpanId: string | undefined;
10
+ traceId: string | undefined;
11
+ attributes?: Record<string, unknown>;
12
+ };
1
13
  type UserIdentifiers = {
2
14
  id: string;
3
15
  email: string;
@@ -6,7 +18,125 @@ type UserIdentifiers = {
6
18
  organization: string;
7
19
  properties: Record<string, unknown>;
8
20
  };
21
+ type DomEventAttributes = {
22
+ dom_event_type: string;
23
+ dom_event_coordinates: {
24
+ clientX: number;
25
+ clientY: number;
26
+ };
27
+ dom_event_target: {
28
+ tagName: string;
29
+ id: string;
30
+ className: string;
31
+ text: string;
32
+ };
33
+ dom_event_selector: string;
34
+ dom_event_key_code: string;
35
+ };
36
+ type NetworkEventAttributes = {
37
+ type: "HTTP";
38
+ resource_name: string;
39
+ status: string;
40
+ subType: string;
41
+ level?: string;
42
+ timestamp?: number;
43
+ operation: {
44
+ name: string;
45
+ startTime?: number;
46
+ endTime?: number;
47
+ };
48
+ http: {
49
+ url: {
50
+ full: string;
51
+ };
52
+ route: string;
53
+ path: string;
54
+ status: string;
55
+ method: string;
56
+ request: {
57
+ headers: Record<string, string>;
58
+ method: string;
59
+ };
60
+ response: {
61
+ headers: Record<string, string>;
62
+ status_code: string;
63
+ };
64
+ duration_ms?: number;
65
+ };
66
+ gc: {
67
+ request: {
68
+ body: string;
69
+ };
70
+ response: {
71
+ body: string;
72
+ };
73
+ };
74
+ error?: {
75
+ type: string;
76
+ };
77
+ };
78
+ type Stacktrace = {
79
+ filename: string;
80
+ function: string;
81
+ lineno: number;
82
+ colno: number;
83
+ };
84
+ type ErrorEventAttributes = {
85
+ error_type: string;
86
+ error_message: string;
87
+ error_stacktrace?: Array<Stacktrace>;
88
+ error_fingerprint: string;
89
+ error_handled: boolean;
90
+ };
91
+ type LogEventAttributes = {
92
+ message: string;
93
+ level: string;
94
+ };
95
+ type PageLoadEventAttributes = {
96
+ page_url: string;
97
+ page_resources: {
98
+ count: number;
99
+ totalSize: number;
100
+ totalDuration: number;
101
+ byType: {
102
+ [key: string]: {
103
+ count: number;
104
+ size: number;
105
+ duration: number;
106
+ };
107
+ };
108
+ };
109
+ page_referrer: string;
110
+ page_load_time: number;
111
+ };
112
+ type NavigationEventAttributes = {
113
+ page_url: string;
114
+ };
115
+ type UserDefinedEventAttributes = {
116
+ custom_event_name: string;
117
+ custom_event_attributes?: Record<string, unknown>;
118
+ };
119
+ type PerformanceEventAttributes = {
120
+ performance_metric_name: string;
121
+ performance_metric_value: number;
122
+ performance_metric_id: string;
123
+ performance_metric_navigation_type: string;
124
+ };
9
125
 
126
+ type Event<T extends BaseEvent["type"], A> = Omit<BaseEvent, "attributes"> & {
127
+ type: T;
128
+ attributes: A;
129
+ };
130
+ type EventTypes = {
131
+ "dom.event": Event<"dom.event", DomEventAttributes>;
132
+ exception: Event<"exception", ErrorEventAttributes>;
133
+ network: Event<"network", NetworkEventAttributes>;
134
+ log: Event<"log", LogEventAttributes>;
135
+ pageload: Event<"pageload", PageLoadEventAttributes>;
136
+ navigation: Event<"navigation", NavigationEventAttributes>;
137
+ custom: Event<"custom", UserDefinedEventAttributes>;
138
+ performance: Event<"performance", PerformanceEventAttributes>;
139
+ };
10
140
  interface SDKOptions {
11
141
  batchSize: number;
12
142
  batchTimeout: number;
@@ -17,11 +147,14 @@ interface SDKOptions {
17
147
  debug: boolean;
18
148
  maskFields: string[];
19
149
  tracePropagationUrls: string[];
150
+ beforeSend?: (event: EventTypes[keyof EventTypes]) => boolean;
151
+ excludedUrls?: Array<string | RegExp>;
20
152
  }
21
153
 
22
154
  declare function init(params: {
23
155
  cluster: string;
24
156
  environment: string;
157
+ namespace: string;
25
158
  appId: string;
26
159
  userIdentifier?: Partial<UserIdentifiers>;
27
160
  dsn: string;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("error-stack-parser"),t=require("web-vitals");function n(e){return e&&e.__esModule?e:{default:e}}var s=n(e),i=console.log.bind(console),r=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&i(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},o=r.getInstance();function a(e){o.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var l={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:["dom","network","error","log"],tracePropagationUrls:[]},c=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.userIdentifier=e.userIdentifier||null,this.options={...l,...e.options}}getEndpoint(){return this.dsn}},d=class{constructor(){this.generateTraceId=u(16),this.generateSpanId=u(8),this.generateId=u(16)}},h=Array(32);function u(e){return function(){for(let t=0;t<2*e;t++)h[t]=Math.floor(16*Math.random())+48,h[t]>=58&&(h[t]+=39);return String.fromCharCode.apply(null,h.slice(0,2*e))}}var g=class e{constructor(){this.config=null,this.logger=r.getInstance(),this.sessionId=null,this.idGenerator=new d}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new c(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},p="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},m=g.getInstance(),f=new d;function v(){const e=m?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function y(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,y(s,i)):e[i]=s,e}),{})}function E(e){const t=1e6*Date.now(),n=f.generateId(),s=e.spanId||f.generateSpanId(),i=e.traceId||f.generateTraceId(),r=e.parentSpanId||"",o=y(e.attributes||{}),a={path:p?.location?.pathname,url:p?.location?.href,title:p?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var b=class{constructor(){this.logger=r.getInstance(),this.config=g.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{if(t.options.debug)return void this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},I=class e{constructor(){this.events=[],this.timeoutId=null,this.config=g.getInstance(),this.initialized=!1,this.transporter=new b}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){a(e)}}addEvent(e){if(!e||!this.initialized)return;this.events.push(e);const t=this.config.getConfig()?.options?.batchSize||100;this.events.length>=t&&this.flush()}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){a(e)}}scheduleFlush(){try{null!==this.timeoutId&&(p.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=p.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){a(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};I.instance=null;var w=I,T=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance()}};function L({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var _,S=class extends T{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>L({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){a(e)}};this.eventHandlers.push({type:e,handler:t}),p?.addEventListener(e,t)}))}catch(e){a(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return E({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},C=["log","info","warn","error","assert","trace"],q=class extends T{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),C.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){a(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){a(e)}}destroy(){try{if(!this.isInitialized)return;C.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){a(e)}}handleEvent(e,t){try{if(!v())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){a(e)}}buildEvent({message:e,level:t}){return E({type:"log",attributes:{message:L({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return a(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{C.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){a(e)}return e}},z=class extends T{constructor(){super(...arguments),this.config=g.getInstance(),this.idGenerator=new d,this.handleEvent=e=>{try{const t=this.config.getConfig()?.dsn;if(t&&e.url?.includes(t))return;if(!v())return;const n=this.buildEvent(e);this.queueEvent(n)}catch(e){a(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return E({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";try{i=await s.text()}catch(e){i="[unreadable response body]"}const l={};s.headers.forEach(((e,t)=>{l[t]=e})),this.logger.log("[network-events-listener.patchFetch] called",{url:a});const d={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(d),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=L({text:s}),e}),{})}shouldIgnoreRequest(e){return[".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t)))}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},R=class extends T{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){a(e)}}}initialize(){p?.addEventListener("error",this.handleEvent),p?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){p?.removeEventListener("error",this.handleEvent),p?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return E({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${L({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return s.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},x=class extends T{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(p.MutationObserver){const e=p.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0}))}p?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){return E({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},N=class extends T{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),p?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){a(e)}}destroy(){p?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return E({type:"pageload",attributes:{page_url:p?.location?.href||"",page_load_time:e,page_referrer:p?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},k=class extends T{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}}initialize(){t.onCLS(this.handleEvent),t.onLCP(this.handleEvent),t.onFCP(this.handleEvent),t.onTTFB(this.handleEvent),t.onINP(this.handleEvent)}destroy(){}buildEvent(e){return E({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},H=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.domEventsListener=new S,this.logEventsListener=new q,this.errorsEventsListener=new R,this.networkEventsListener=new z,this.navigationListener=new x,this.performanceListener=new k,this.pageLoadListener=new N,this.domEventsListener.initialize(),this.logEventsListener.initialize(),this.errorsEventsListener.initialize(),this.networkEventsListener.initialize(),this.navigationListener.initialize(),this.performanceListener.initialize(),this.pageLoadListener.initialize(),this.logger.log("[instrumentation-manager.instrument] initialized listeners")}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=E({type:"custom",attributes:{custom_event_name:e?.event,custom_user:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){a(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){a(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy()}},M=class{constructor(e){this.initialized=!1,this.logger=r.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new H,this.idGenerator=new d;if(!(!e.options?.sessionSampleRate||Math.random()<e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=g.getInstance();t.initialize(e);w.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");g.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var U={init:function(e){try{_=new M({cluster:e?.cluster,environment:e?.environment,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){a(e)}},identifyUser:function(e){_?_.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){_&&_.sendCustomEvent(e)},captureException:function(e){_&&_.captureException(e)}};module.exports=U;
1
+ "use strict";var e=require("error-stack-parser"),t=require("web-vitals");function n(e){return e&&e.__esModule?e:{default:e}}var s=n(e),i=console.log.bind(console),r=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&i(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},o=r.getInstance();function a(e){o.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var l={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:["dom","network","error","log"],tracePropagationUrls:[]},c=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.namespace=e.namespace,this.userIdentifier=e.userIdentifier||null,this.options={...l,...e.options}}getEndpoint(){return this.dsn}},h=class{constructor(){this.generateTraceId=u(16),this.generateSpanId=u(8),this.generateId=u(16)}},d=Array(32);function u(e){return function(){for(let t=0;t<2*e;t++)d[t]=Math.floor(16*Math.random())+48,d[t]>=58&&(d[t]+=39);return String.fromCharCode.apply(null,d.slice(0,2*e))}}var g=class e{constructor(){this.config=null,this.logger=r.getInstance(),this.sessionId=null,this.idGenerator=new h}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new c(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},p="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},m=g.getInstance(),f=new h;function v(){const e=m?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function y(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,y(s,i)):e[i]=s,e}),{})}function E(e){const t=1e6*Date.now(),n=f.generateId(),s=e.spanId||f.generateSpanId(),i=e.traceId||f.generateTraceId(),r=e.parentSpanId||"",o=y(e.attributes||{}),a={path:p?.location?.pathname,url:p?.location?.href,title:p?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var b=class{constructor(){this.logger=r.getInstance(),this.config=g.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{t.options.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},I=class e{constructor(){this.events=[],this.timeoutId=null,this.config=g.getInstance(),this.initialized=!1,this.transporter=new b}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){a(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend;if(t&&!t(e))return;this.events.push(e);const n=this.config.getConfig()?.options?.batchSize||100;this.events.length>=n&&this.flush()}catch(e){a(e)}}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){a(e)}}scheduleFlush(){try{null!==this.timeoutId&&(p.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=p.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){a(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",namespace:this.config.getConfig()?.namespace||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};I.instance=null;var w=I,T=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance()}};function L({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var _,S=class extends T{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>L({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){a(e)}};this.eventHandlers.push({type:e,handler:t}),p?.addEventListener(e,t)}))}catch(e){a(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return E({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},C=["log","info","warn","error","assert","trace"],q=class extends T{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),C.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){a(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){a(e)}}destroy(){try{if(!this.isInitialized)return;C.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){a(e)}}handleEvent(e,t){try{if(!v())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){a(e)}}buildEvent({message:e,level:t}){return E({type:"log",attributes:{message:L({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return a(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{C.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){a(e)}return e}},z=class extends T{constructor(){super(...arguments),this.config=g.getInstance(),this.idGenerator=new h,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return E({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return a(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";try{i=await s.text()}catch(e){i="[unreadable response body]"}const l={};s.headers.forEach(((e,t)=>{l[t]=e})),this.logger.log("[network-events-listener.patchFetch] called",{url:a});const h={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(h),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=L({text:s}),e}),{})}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},R=class extends T{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){a(e)}}}initialize(){p?.addEventListener("error",this.handleEvent),p?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){p?.removeEventListener("error",this.handleEvent),p?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return E({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${L({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return s.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},x=class extends T{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(p.MutationObserver){const e=p.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0}))}p?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){return E({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},N=class extends T{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),p?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){a(e)}}destroy(){p?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return E({type:"pageload",attributes:{page_url:p?.location?.href||"",page_load_time:e,page_referrer:p?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},k=class extends T{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}}initialize(){t.onCLS(this.handleEvent),t.onLCP(this.handleEvent),t.onFCP(this.handleEvent),t.onTTFB(this.handleEvent),t.onINP(this.handleEvent)}destroy(){}buildEvent(e){return E({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},H=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.domEventsListener=new S,this.logEventsListener=new q,this.errorsEventsListener=new R,this.networkEventsListener=new z,this.navigationListener=new x,this.performanceListener=new k,this.pageLoadListener=new N,this.domEventsListener.initialize(),this.logEventsListener.initialize(),this.errorsEventsListener.initialize(),this.networkEventsListener.initialize(),this.navigationListener.initialize(),this.performanceListener.initialize(),this.pageLoadListener.initialize(),this.logger.log("[instrumentation-manager.instrument] initialized listeners")}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=E({type:"custom",attributes:{custom_event_name:e?.event,custom_user:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){a(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){a(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy()}},U=class{constructor(e){this.initialized=!1,this.logger=r.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new H,this.idGenerator=new h;if(!(!e.options?.sessionSampleRate||Math.random()<e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=g.getInstance();t.initialize(e);w.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");g.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var M={init:function(e){try{_=new U({cluster:e?.cluster,environment:e?.environment,namespace:e?.namespace,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){a(e)}},identifyUser:function(e){_?_.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){_&&_.sendCustomEvent(e)},captureException:function(e){_&&_.captureException(e)}};module.exports=M;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import e from"error-stack-parser";import{onCLS as t,onLCP as n,onFCP as s,onTTFB as i,onINP as r}from"web-vitals";var o=console.log.bind(console),a=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&o(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},l=a.getInstance();function c(e){l.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var h={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:["dom","network","error","log"],tracePropagationUrls:[]},d=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.userIdentifier=e.userIdentifier||null,this.options={...h,...e.options}}getEndpoint(){return this.dsn}},u=class{constructor(){this.generateTraceId=p(16),this.generateSpanId=p(8),this.generateId=p(16)}},g=Array(32);function p(e){return function(){for(let t=0;t<2*e;t++)g[t]=Math.floor(16*Math.random())+48,g[t]>=58&&(g[t]+=39);return String.fromCharCode.apply(null,g.slice(0,2*e))}}var m=class e{constructor(){this.config=null,this.logger=a.getInstance(),this.sessionId=null,this.idGenerator=new u}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new d(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},f="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},v=m.getInstance(),y=new u;function E(){const e=v?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function b(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,b(s,i)):e[i]=s,e}),{})}function I(e){const t=1e6*Date.now(),n=y.generateId(),s=e.spanId||y.generateSpanId(),i=e.traceId||y.generateTraceId(),r=e.parentSpanId||"",o=b(e.attributes||{}),a={path:f?.location?.pathname,url:f?.location?.href,title:f?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var w=class{constructor(){this.logger=a.getInstance(),this.config=m.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{if(t.options.debug)return void this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},T=class e{constructor(){this.events=[],this.timeoutId=null,this.config=m.getInstance(),this.initialized=!1,this.transporter=new w}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){c(e)}}addEvent(e){if(!e||!this.initialized)return;this.events.push(e);const t=this.config.getConfig()?.options?.batchSize||100;this.events.length>=t&&this.flush()}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){c(e)}}scheduleFlush(){try{null!==this.timeoutId&&(f.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=f.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){c(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};T.instance=null;var L=T,_=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance()}};function S({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var C,q=class extends _{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>S({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){c(e)}};this.eventHandlers.push({type:e,handler:t}),f?.addEventListener(e,t)}))}catch(e){c(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return I({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},z=["log","info","warn","error","assert","trace"],R=class extends _{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),z.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){c(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){c(e)}}destroy(){try{if(!this.isInitialized)return;z.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){c(e)}}handleEvent(e,t){try{if(!E())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){c(e)}}buildEvent({message:e,level:t}){return I({type:"log",attributes:{message:S({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return c(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{z.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){c(e)}return e}},x=class extends _{constructor(){super(...arguments),this.config=m.getInstance(),this.idGenerator=new u,this.handleEvent=e=>{try{const t=this.config.getConfig()?.dsn;if(t&&e.url?.includes(t))return;if(!E())return;const n=this.buildEvent(e);this.queueEvent(n)}catch(e){c(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return I({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";try{i=await s.text()}catch(e){i="[unreadable response body]"}const l={};s.headers.forEach(((e,t)=>{l[t]=e})),this.logger.log("[network-events-listener.patchFetch] called",{url:a});const h={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(h),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=S({text:s}),e}),{})}shouldIgnoreRequest(e){return[".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t)))}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},N=class extends _{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){c(e)}}}initialize(){f?.addEventListener("error",this.handleEvent),f?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){f?.removeEventListener("error",this.handleEvent),f?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return I({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${S({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(t){if(!t)return[];try{return e.parse(t).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},k=class extends _{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(f.MutationObserver){const e=f.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0}))}f?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){return I({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},H=class extends _{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),f?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){c(e)}}destroy(){f?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return I({type:"pageload",attributes:{page_url:f?.location?.href||"",page_load_time:e,page_referrer:f?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},U=class extends _{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}}initialize(){t(this.handleEvent),n(this.handleEvent),s(this.handleEvent),i(this.handleEvent),r(this.handleEvent)}destroy(){}buildEvent(e){return I({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},M=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.domEventsListener=new q,this.logEventsListener=new R,this.errorsEventsListener=new N,this.networkEventsListener=new x,this.navigationListener=new k,this.performanceListener=new U,this.pageLoadListener=new H,this.domEventsListener.initialize(),this.logEventsListener.initialize(),this.errorsEventsListener.initialize(),this.networkEventsListener.initialize(),this.navigationListener.initialize(),this.performanceListener.initialize(),this.pageLoadListener.initialize(),this.logger.log("[instrumentation-manager.instrument] initialized listeners")}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=I({type:"custom",attributes:{custom_event_name:e?.event,custom_user:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){c(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){c(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy()}},j=class{constructor(e){this.initialized=!1,this.logger=a.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new M,this.idGenerator=new u;if(!(!e.options?.sessionSampleRate||Math.random()<e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=m.getInstance();t.initialize(e);L.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");m.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var A={init:function(e){try{C=new j({cluster:e?.cluster,environment:e?.environment,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){c(e)}},identifyUser:function(e){C?C.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){C&&C.sendCustomEvent(e)},captureException:function(e){C&&C.captureException(e)}};export{A as default};
1
+ import e from"error-stack-parser";import{onCLS as t,onLCP as n,onFCP as s,onTTFB as i,onINP as r}from"web-vitals";var o=console.log.bind(console),a=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&o(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},l=a.getInstance();function c(e){l.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var h={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:["dom","network","error","log"],tracePropagationUrls:[]},d=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.namespace=e.namespace,this.userIdentifier=e.userIdentifier||null,this.options={...h,...e.options}}getEndpoint(){return this.dsn}},u=class{constructor(){this.generateTraceId=p(16),this.generateSpanId=p(8),this.generateId=p(16)}},g=Array(32);function p(e){return function(){for(let t=0;t<2*e;t++)g[t]=Math.floor(16*Math.random())+48,g[t]>=58&&(g[t]+=39);return String.fromCharCode.apply(null,g.slice(0,2*e))}}var m=class e{constructor(){this.config=null,this.logger=a.getInstance(),this.sessionId=null,this.idGenerator=new u}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new d(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},f="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},v=m.getInstance(),y=new u;function E(){const e=v?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function b(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,b(s,i)):e[i]=s,e}),{})}function I(e){const t=1e6*Date.now(),n=y.generateId(),s=e.spanId||y.generateSpanId(),i=e.traceId||y.generateTraceId(),r=e.parentSpanId||"",o=b(e.attributes||{}),a={path:f?.location?.pathname,url:f?.location?.href,title:f?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var w=class{constructor(){this.logger=a.getInstance(),this.config=m.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{t.options.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},T=class e{constructor(){this.events=[],this.timeoutId=null,this.config=m.getInstance(),this.initialized=!1,this.transporter=new w}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){c(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend;if(t&&!t(e))return;this.events.push(e);const n=this.config.getConfig()?.options?.batchSize||100;this.events.length>=n&&this.flush()}catch(e){c(e)}}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){c(e)}}scheduleFlush(){try{null!==this.timeoutId&&(f.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=f.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){c(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",namespace:this.config.getConfig()?.namespace||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};T.instance=null;var L=T,_=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance()}};function S({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var C,q=class extends _{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>S({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){c(e)}};this.eventHandlers.push({type:e,handler:t}),f?.addEventListener(e,t)}))}catch(e){c(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return I({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},z=["log","info","warn","error","assert","trace"],R=class extends _{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),z.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){c(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){c(e)}}destroy(){try{if(!this.isInitialized)return;z.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){c(e)}}handleEvent(e,t){try{if(!E())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){c(e)}}buildEvent({message:e,level:t}){return I({type:"log",attributes:{message:S({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return c(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{z.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){c(e)}return e}},x=class extends _{constructor(){super(...arguments),this.config=m.getInstance(),this.idGenerator=new u,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return I({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return c(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";try{i=await s.text()}catch(e){i="[unreadable response body]"}const l={};s.headers.forEach(((e,t)=>{l[t]=e})),this.logger.log("[network-events-listener.patchFetch] called",{url:a});const h={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(h),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=S({text:s}),e}),{})}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},N=class extends _{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){c(e)}}}initialize(){f?.addEventListener("error",this.handleEvent),f?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){f?.removeEventListener("error",this.handleEvent),f?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return I({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${S({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(t){if(!t)return[];try{return e.parse(t).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},k=class extends _{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(f.MutationObserver){const e=f.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0}))}f?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){return I({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},H=class extends _{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),f?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){c(e)}}destroy(){f?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return I({type:"pageload",attributes:{page_url:f?.location?.href||"",page_load_time:e,page_referrer:f?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},U=class extends _{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}}initialize(){t(this.handleEvent),n(this.handleEvent),s(this.handleEvent),i(this.handleEvent),r(this.handleEvent)}destroy(){}buildEvent(e){return I({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},M=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.domEventsListener=new q,this.logEventsListener=new R,this.errorsEventsListener=new N,this.networkEventsListener=new x,this.navigationListener=new k,this.performanceListener=new U,this.pageLoadListener=new H,this.domEventsListener.initialize(),this.logEventsListener.initialize(),this.errorsEventsListener.initialize(),this.networkEventsListener.initialize(),this.navigationListener.initialize(),this.performanceListener.initialize(),this.pageLoadListener.initialize(),this.logger.log("[instrumentation-manager.instrument] initialized listeners")}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=I({type:"custom",attributes:{custom_event_name:e?.event,custom_user:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){c(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){c(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy()}},j=class{constructor(e){this.initialized=!1,this.logger=a.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new M,this.idGenerator=new u;if(!(!e.options?.sessionSampleRate||Math.random()<e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=m.getInstance();t.initialize(e);L.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");m.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var A={init:function(e){try{C=new j({cluster:e?.cluster,environment:e?.environment,namespace:e?.namespace,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){c(e)}},identifyUser:function(e){C?C.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){C&&C.sendCustomEvent(e)},captureException:function(e){C&&C.captureException(e)}};export{A as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@groundcover/browser",
3
- "version": "0.0.22",
3
+ "version": "0.0.24",
4
4
  "description": "groundcover browser SDK",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",