@aj-2000-test/goodlogs-sdk 0.4.2 → 0.4.4

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.
@@ -26,6 +26,12 @@ interface GoodLogsOptions {
26
26
  * Default: true when `useEnvelope` is on and autocapture is not disabled.
27
27
  * Each fetch call becomes a `op:http.client` span with http.url/method/status_code. */
28
28
  autoFetch?: boolean;
29
+ /** Application release/version (e.g. "1.2.3", commit SHA). Attached to all telemetry
30
+ * for release health tracking. Can also be set later via setRelease(). */
31
+ release?: string;
32
+ /** Deployment environment (e.g. "production", "staging"). Defaults to "production".
33
+ * Can also be set later via setEnvironment(). */
34
+ environment?: string;
29
35
  }
30
36
  interface LogEntry {
31
37
  severity: Severity;
@@ -118,6 +124,9 @@ declare class GoodLogs {
118
124
  private telemetry;
119
125
  private useEnvelope;
120
126
  private autoFetch;
127
+ private release;
128
+ private environment;
129
+ private userProperties;
121
130
  private originalFetch;
122
131
  /** Backup of XMLHttpRequest.prototype.{open,send} so detach() can restore. */
123
132
  private xhrPatched;
@@ -158,6 +167,25 @@ declare class GoodLogs {
158
167
  newSession(): void;
159
168
  /** Set a specific session ID. */
160
169
  setSessionId(id: string): void;
170
+ /** Set the application release/version. Attached to all subsequent telemetry. */
171
+ setRelease(version: string): void;
172
+ /** Get the current release version. */
173
+ getRelease(): string | null;
174
+ /** Set the deployment environment. Attached to all subsequent telemetry. */
175
+ setEnvironment(env: string): void;
176
+ /** Get the current environment. */
177
+ getEnvironment(): string;
178
+ /** Set user properties for richer user identification.
179
+ * Unlike identify() which only sets the ID, this attaches arbitrary
180
+ * properties (email, name, plan, etc.) to all subsequent telemetry. */
181
+ setUser(user: {
182
+ id: string;
183
+ email?: string;
184
+ name?: string;
185
+ [key: string]: unknown;
186
+ }): void;
187
+ /** Get the current user properties. */
188
+ getUser(): Record<string, unknown>;
161
189
  track(event: string, properties?: Record<string, unknown> & {
162
190
  distinctId?: string;
163
191
  }): void;
@@ -26,6 +26,12 @@ interface GoodLogsOptions {
26
26
  * Default: true when `useEnvelope` is on and autocapture is not disabled.
27
27
  * Each fetch call becomes a `op:http.client` span with http.url/method/status_code. */
28
28
  autoFetch?: boolean;
29
+ /** Application release/version (e.g. "1.2.3", commit SHA). Attached to all telemetry
30
+ * for release health tracking. Can also be set later via setRelease(). */
31
+ release?: string;
32
+ /** Deployment environment (e.g. "production", "staging"). Defaults to "production".
33
+ * Can also be set later via setEnvironment(). */
34
+ environment?: string;
29
35
  }
30
36
  interface LogEntry {
31
37
  severity: Severity;
@@ -118,6 +124,9 @@ declare class GoodLogs {
118
124
  private telemetry;
119
125
  private useEnvelope;
120
126
  private autoFetch;
127
+ private release;
128
+ private environment;
129
+ private userProperties;
121
130
  private originalFetch;
122
131
  /** Backup of XMLHttpRequest.prototype.{open,send} so detach() can restore. */
123
132
  private xhrPatched;
@@ -158,6 +167,25 @@ declare class GoodLogs {
158
167
  newSession(): void;
159
168
  /** Set a specific session ID. */
160
169
  setSessionId(id: string): void;
170
+ /** Set the application release/version. Attached to all subsequent telemetry. */
171
+ setRelease(version: string): void;
172
+ /** Get the current release version. */
173
+ getRelease(): string | null;
174
+ /** Set the deployment environment. Attached to all subsequent telemetry. */
175
+ setEnvironment(env: string): void;
176
+ /** Get the current environment. */
177
+ getEnvironment(): string;
178
+ /** Set user properties for richer user identification.
179
+ * Unlike identify() which only sets the ID, this attaches arbitrary
180
+ * properties (email, name, plan, etc.) to all subsequent telemetry. */
181
+ setUser(user: {
182
+ id: string;
183
+ email?: string;
184
+ name?: string;
185
+ [key: string]: unknown;
186
+ }): void;
187
+ /** Get the current user properties. */
188
+ getUser(): Record<string, unknown>;
161
189
  track(event: string, properties?: Record<string, unknown> & {
162
190
  distinctId?: string;
163
191
  }): void;
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- 'use strict';var S=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var x={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(i){let t=i.split("_");return t.length>=4&&t[0]==="gl"?t[2]:"eu"}function y(i,t){if(t)return t;let e=B(i);return x[e]||x.eu}var G=5e3,F=50,v="0.4.2",w="gl_anon_id",E="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return (i==="x"?t:t&3|8).toString(16)})}function M(){let i={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(i.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(i.$language=navigator.language??""),typeof location<"u"&&(i.$url=location.href,i.$path=location.pathname,i.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(i.$referrer=document.referrer),document.title&&(i.$title=document.title))),i}function U(i,t){let e={$session_id:i,$distinct_id:t,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(e.$url=location.href,e.$path=location.pathname),e}function D(){if(!(typeof document<"u"))try{let t=new Error().stack?.split(`
2
- `);if(!t)return;for(let e=3;e<Math.min(t.length,8);e++){let r=t[e]?.trim();if(!r||r.includes("goodlogs")&&(r.includes("client.")||r.includes("index.")))continue;let n=r.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(n){let s=n[1]||"<anonymous>",o=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${o}:${d}`}}}catch{}}function K(){if(typeof localStorage<"u"){let i=localStorage.getItem(w);if(i)return i;let t=b();return localStorage.setItem(w,t),t}return b()}function V(){if(typeof sessionStorage<"u"){let i=sessionStorage.getItem(E);if(i)return i;let t=b();return sessionStorage.setItem(E,t),t}return b()}function X(){let i="";for(let t=0;t<32;t++)i+=(Math.random()*16|0).toString(16);return i}function z(){let i="";for(let t=0;t<16;t++)i+=(Math.random()*16|0).toString(16);return i}function W(i,t){switch(i){case "lcp":return t<=2500?"good":t<=4e3?"needs-improvement":"poor";case "inp":return t<=200?"good":t<=500?"needs-improvement":"poor";case "cls":return t<=.1?"good":t<=.25?"needs-improvement":"poor";case "fcp":return t<=1800?"good":t<=3e3?"needs-improvement":"poor";case "ttfb":return t<=800?"good":t<=1800?"needs-improvement":"poor";case "dns":return t<=20?"good":t<=100?"needs-improvement":"poor";case "tcp":return t<=50?"good":t<=200?"needs-improvement":"poor";case "download":return t<=100?"good":t<=500?"needs-improvement":"poor";case "dom_processing":return t<=500?"good":t<=1500?"needs-improvement":"poor";case "page_load":return t<=1e3?"good":t<=3e3?"needs-improvement":"poor";default:return}}function J(i){if(!i)return [];let t=[];for(let e of i.split(`
3
- `)){let r=e.trim();if(!r||r.startsWith("Error")||r.startsWith("at Error"))continue;let n=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(r);if(n){let s=n[1]?.trim(),o=n[2];t.push({function:s&&s!=="<anonymous>"?s:void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")&&!o.startsWith("internal/")});continue}if(n=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(r),n){let s=n[1]?.trim(),o=n[2];t.push({function:s||void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")});}}return t}var R=class R{constructor(t){this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint).replace(/\/+$/,""),this.flushInterval=t.flushInterval??G,this.batchSize=t.batchSize??F,this.defaultContext=t.defaultContext??{},this.onError=t.onError??(()=>{}),this.disabled=t.disabled??false,this.telemetry=t.telemetry??true,this.useEnvelope=t.useEnvelope??false,this.autoFetch=t.autoFetch??(this.useEnvelope&&t.autocapture!==false),this.anonymousId=K(),this.sessionId=V(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),t.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(t,e,r){if(this.disabled)return;let n=65536,s=e;e.length>n&&(s=e.slice(0,n-100)+`
1
+ 'use strict';var S=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var $={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(o){let e=o.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function y(o,e){if(e)return e;let t=B(o);return $[t]||$.eu}var G=5e3,F=50,v="0.4.4",w="gl_anon_id",k="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let e=Math.random()*16|0;return (o==="x"?e:e&3|8).toString(16)})}function U(){let o={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(o.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(o.$language=navigator.language??""),typeof location<"u"&&(o.$url=location.href,o.$path=location.pathname,o.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(o.$referrer=document.referrer),document.title&&(o.$title=document.title))),o}function M(o,e){let t={$session_id:o,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function D(o,e,t,r,n){let s=M(o,e);return t&&(s.$release=t),s.$environment=r,n.email&&(s.$user_email=n.email),n.name&&(s.$user_name=n.name),s}function K(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
+ `);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let r=e[t]?.trim();if(!r||r.includes("goodlogs")&&(r.includes("client.")||r.includes("index.")))continue;let n=r.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(n){let s=n[1]||"<anonymous>",i=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${i}:${d}`}}}catch{}}function X(o){let e=[],t=o;for(;t&&t.tagName;){let r=t.tagName.toLowerCase();if(r==="html"||r==="body"){e.unshift(r);break}if(t.id){e.unshift(`#${t.id}`);break}let n=1,s=t;for(;s?.previousElementSibling;)s.previousElementSibling.tagName?.toLowerCase()===r&&n++,s=s.previousElementSibling;e.unshift(n>1?`${r}:nth-of-type(${n})`:r),t=t.parentElement;}return e.join(" > ").slice(0,200)}function V(){if(typeof localStorage<"u"){let o=localStorage.getItem(w);if(o)return o;let e=b();return localStorage.setItem(w,e),e}return b()}function z(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(k);if(o)return o;let e=b();return sessionStorage.setItem(k,e),e}return b()}function W(){let o="";for(let e=0;e<32;e++)o+=(Math.random()*16|0).toString(16);return o}function J(){let o="";for(let e=0;e<16;e++)o+=(Math.random()*16|0).toString(16);return o}function Y(o,e){switch(o){case "lcp":return e<=2500?"good":e<=4e3?"needs-improvement":"poor";case "inp":return e<=200?"good":e<=500?"needs-improvement":"poor";case "cls":return e<=.1?"good":e<=.25?"needs-improvement":"poor";case "fcp":return e<=1800?"good":e<=3e3?"needs-improvement":"poor";case "ttfb":return e<=800?"good":e<=1800?"needs-improvement":"poor";case "dns":return e<=20?"good":e<=100?"needs-improvement":"poor";case "tcp":return e<=50?"good":e<=200?"needs-improvement":"poor";case "download":return e<=100?"good":e<=500?"needs-improvement":"poor";case "dom_processing":return e<=500?"good":e<=1500?"needs-improvement":"poor";case "page_load":return e<=1e3?"good":e<=3e3?"needs-improvement":"poor";default:return}}function Q(o){if(!o)return [];let e=[];for(let t of o.split(`
3
+ `)){let r=t.trim();if(!r||r.startsWith("Error")||r.startsWith("at Error"))continue;let n=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(r);if(n){let s=n[1]?.trim(),i=n[2];e.push({function:s&&s!=="<anonymous>"?s:void 0,filename:i,lineno:Number(n[3]),colno:Number(n[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")&&!i.startsWith("internal/")});continue}if(n=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(r),n){let s=n[1]?.trim(),i=n[2];e.push({function:s||void 0,filename:i,lineno:Number(n[3]),colno:Number(n[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")});}}return e}var R=class R{constructor(e){this.userProperties={};this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??G,this.batchSize=e.batchSize??F,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.useEnvelope=e.useEnvelope??false,this.autoFetch=e.autoFetch??(this.useEnvelope&&e.autocapture!==false),this.release=e.release??null,this.environment=e.environment??"production",this.anonymousId=V(),this.sessionId=z(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),!this.disabled&&typeof setTimeout<"u"&&setTimeout(()=>{!this.release&&typeof console<"u"&&console.warn("[GoodLogs] No release version set. Set `release` in options or call gl.setRelease('1.2.3') for release health tracking.");},5e3),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(e,t,r){if(this.disabled)return;let n=65536,s=t;t.length>n&&(s=t.slice(0,n-100)+`
4
4
 
5
- [truncated \u2014 original ${e.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${e.length} to ${n} chars`)));let o=D(),d={severity:t,message:s,properties:{...this.defaultContext,...U(this.sessionId,this.anonymousId),...o?{code_location:o}:{},...r},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(t,e){this.log("debug",t,e);}info(t,e){this.log("info",t,e);}warn(t,e){this.log("warn",t,e);}error(t,e){this.log("error",t,e);}fatal(t,e){this.log("fatal",t,e);}identify(t){this.anonymousId=t,typeof localStorage<"u"&&localStorage.setItem(w,t);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}setSessionId(t){this.sessionId=t,typeof sessionStorage<"u"&&sessionStorage.setItem(E,t);}track(t,e){if(this.disabled)return;let{distinctId:r,...n}=e??{},s={event:t,distinctId:r??this.anonymousId,properties:{...M(),...n,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(t){if(this.disabled)return;let e={ts:t.ts??new Date().toISOString(),...t};this.breadcrumbBuffer.push(e),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(t,e){if(this.disabled)return;let r=this.buildErrorEntry(t,e);this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(r.message,{exception_type:r.exception_type,frames:r.frames});}captureMessage(t,e){if(this.disabled)return;let r={level:e?.level??"info",message:t,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(t);}buildErrorEntry(t,e){let r,n,s=[];if(t instanceof Error)r=t.name,n=t.message,s=J(t.stack);else if(typeof t=="string")n=t;else try{n=JSON.stringify(t);}catch{n=String(t);}return {level:e?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:r,message:n,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id}}captureVital(t,e,r){if(this.disabled||!Number.isFinite(e)||e<0)return;let n=r?.rating??W(t,e),s={metric:t,value_ms:t==="cls"?e:Math.round(e),rating:n,route:r?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:r?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:t.toUpperCase(),$value_ms:s.value_ms,$rating:n}});}startTransaction(t){return this.makeSpan(void 0,t)}startSpan(t){return this.makeSpan(void 0,t)}makeSpan(t,e){let r=e?.trace_id??e?.parent?.trace_id??t?.trace_id??X(),n=z(),s=e?.parent?.span_id??t?.span_id,o=Date.now(),d=new Date(o).toISOString(),a={...e?.attributes??{}},u="unset",c=[],l=false,f=this,g={span_id:n,trace_id:r,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){c.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(l)return;l=true;let h=Date.now(),p={span_id:n,trace_id:r,parent_span_id:s,name:e?.name,op:e?.op,status:u==="unset"?"ok":u,kind:e?.kind,attributes:a,events:c,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-o};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r=this.errorBuffer.splice(0),n=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),o=[];this.useEnvelope?(t.length>0||e.length>0||r.length>0||n.length>0||s.length>0)&&o.push(this.sendEnvelope(t,e,r,n,s)):(t.length>0&&o.push(this.sendLogs(t)),e.length>0&&o.push(this.sendEvents(e))),await Promise.all(o);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({severity:o.severity,message:o.message,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/logs",s,o=>{for(let d of o)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({event:o.event,distinctId:o.distinctId,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/events",s,o=>{for(let d of o)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(t,e,r,n,s){let d=[...t.map(a=>({kind:"log",entry:a})),...e.map(a=>({kind:"event",entry:a})),...r.map(a=>({kind:"error",entry:a})),...n.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),c=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),l=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[c,...l].join(`
6
- `);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(t,e,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:t});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),this.postEnvelopeWithRetry(t,e,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let o of e)o.kind==="log"?this.logBuffer.push(o.entry):o.kind==="event"?this.eventBuffer.push(o.entry):o.kind==="error"?this.errorBuffer.push(o.entry):o.kind==="vital"?this.vitalBuffer.push(o.entry):this.spanBuffer.push(o.entry);}}catch(n){if(r===0)for(let s of e)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(t,e,r,n=0){try{let s=await fetch(`${this.endpoint}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:e})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(t,e,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(e);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=e.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(e),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let t=this.timer;typeof t?.unref=="function"&&t.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let t=(e,r)=>{if(this.useEnvelope)this.captureVital(e.toLowerCase(),r);else {let n=e==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:e,[n]:e==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(e=>{let r=e.getEntries()[0];r&&t("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let r=e.getEntries(),n=r[r.length-1];n&&t("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{e>0&&t("CLS",Math.round(e*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&t("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,o=s(n.domainLookupEnd)-s(n.domainLookupStart);o>0&&this.captureVital("dns",o);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&t("TTFB",e.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(e?.domainLookupEnd)-r(e?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(e?.connectEnd)-r(e?.connectStart);s>0&&this.captureVital("tcp",s);let o=r(e?.responseEnd)-r(e?.responseStart);o>0&&this.captureVital("download",o);let d=r(e?.domComplete)-r(e?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(e?.loadEventEnd)-r(e?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r.duration;n>0&&t("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let t=(e="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,e));};if(typeof history<"u"){let e=history.pushState,r=history.replaceState;history.pushState=function(...n){e.apply(this,n),t("push");},history.replaceState=function(...n){r.apply(this,n),t("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>t("popstate"));}startNavTransaction(t,e){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:t,attributes:{"navigation.type":e,"http.url":typeof location<"u"?location.href:t}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let t=globalThis;typeof t.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=e=>{let r=e,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=e=>{let n=e.reason,s=n;if(!(n instanceof Error)){let o;if(typeof n=="string")o=n;else try{o=JSON.stringify(n);}catch{o=String(n);}s=new Error(o);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},t.addEventListener("error",this.errorHandler),t.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let t=globalThis;typeof t.removeEventListener=="function"&&(this.errorHandler&&(t.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(t.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let t=globalThis;if(this.originalFetch)return;this.originalFetch=t.fetch;let e=t.fetch.bind(globalThis),r=this;t.fetch=function(s,o){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=o??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return e(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},e(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let e=globalThis.XMLHttpRequest;if(!e||!e.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=e.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,o=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,o.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;o.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=o,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let e=globalThis.XMLHttpRequest?.prototype;if(!e)return;let r=Symbol.for("goodlogs.xhr.patched");e.__gl_orig_open&&(e.open=e.__gl_orig_open),e.__gl_orig_set_header&&(e.setRequestHeader=e.__gl_orig_set_header),e.__gl_orig_send&&(e.send=e.__gl_orig_send),delete e.__gl_orig_open,delete e.__gl_orig_set_header,delete e.__gl_orig_send,delete e[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=t=>{let r=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",o=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80);this.track(n||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};t.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),e.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(t,e,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:t,level:e,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var I=R;var L=class{constructor(t){if(!t.apiKey)throw new Error("apiKey is required");if(!t.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint),this.timeout=t.timeout??3e4,this.alerts=new $(this),this.slos=new P(this),this.ai=new A(this);}async _request(t,e,r){let n=`${this.endpoint}${e}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:t,headers:s,body:r?JSON.stringify(r):void 0,signal:o.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(t){return this._request("GET",t)}_post(t,e){return this._request("POST",t,e)}_put(t,e){return this._request("PUT",t,e)}_delete(t){return this._request("DELETE",t)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(t){return this._post("/v1/gql/query",{q:t})}gqlBatch(t){return this._post("/v1/gql",{queries:t})}gqlAutocomplete(t,e){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(t)}`;return e!==void 0&&(r+=`&cursor=${e}`),this._get(r)}nl2gql(t,e){return this._post("/v1/gql/nl",{prompt:t,mode:e})}},$=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/alerts")}create(t){return this.client._post("/v1/alerts",t)}update(t,e){return this.client._put(`/v1/alerts/${t}`,e)}delete(t){return this.client._delete(`/v1/alerts/${t}`)}mute(t,e){return this.client._post(`/v1/alerts/${t}/mute`,{minutes:e})}},P=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/slos")}create(t){return this.client._post("/v1/slos",t)}update(t,e){return this.client._put(`/v1/slos/${t}`,e)}delete(t){return this.client._delete(`/v1/slos/${t}`)}},A=class{constructor(t){this.client=t;}chat(t,e){return this.client._post("/v1/ai/chat",{message:t,session_id:e})}},T=class extends Error{constructor(e,r,n){super(r);this.status=e;this.code=n;this.name="GoodLogsApiError";}};var q="0.1.0";function Y(i,t){let e=y(t?.apiKey??"",t?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};t?.token&&(r.Authorization=`Bearer ${t.token}`),fetch(`${e}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function C(i){if(!i)return null;let t=i.trim().split("-");if(t.length!==4)return null;let[e,r,n,s]=t;return e.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(i,t){if(!i)return;let e=i[t]??i[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function Q(i){return function(e,r,n){let s=(e.method??"GET").toUpperCase(),o=e.originalUrl??e.url??"",d=C(N(e.headers,"traceparent")),a=i.startTransaction({op:"http.server",name:`${s} ${o}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":o}}),u=false,c=()=>{if(u)return;u=true;let l=e.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),e.goodlogs={span:a},n();}}function Z(i){return function(e,r,n){e.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),e.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function tt(i){return {intercept(t,e){let r=t.switchToHttp(),n=r.getRequest(),s=r.getResponse(),o=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=e.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function et(i){let t=globalThis.process;if(!t||typeof t.on!="function")return;let e=t,r=Symbol.for("goodlogs.node-process.patched");e[r]||(t.on("uncaughtException",n=>{try{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.flush();}catch{}}),t.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),e[r]=true);}var H=globalThis.URL;function k(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function nt(...i){let t=i[0],e=i[1],r="GET",n="";if(typeof t=="string")n=t,e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(k(t))n=t.toString(),e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(t&&typeof t=="object"){let o=t;r=String(o.method??r).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",u=o.port?`:${o.port}`:"";n=`${d}://${a}${u}${o.path??"/"}`;}return {method:r,url:n,isOurs:o=>!!o&&n.startsWith(o)}}function rt(i,t,e){let r=i[0]&&typeof i[0]=="object"&&!k(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!k(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(t in r.headers)&&!(t.toLowerCase()in r.headers)&&(r.headers[t]=e));}function st(i,t){let e=t?.endpoint??i.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let o=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=nt(...a);if(!c||l(e))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});rt(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=o(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
7
- exports.GoodLogs=I;exports.GoodLogsApiError=T;exports.GoodLogsClient=L;exports.REGION_URLS=x;exports.goodlogsExpress=Q;exports.goodlogsFastify=Z;exports.goodlogsNestInterceptor=tt;exports.instrumentNodeHttp=st;exports.instrumentNodeProcess=et;exports.parseTraceparent=C;exports.resolveEndpoint=y;exports.resolveRegion=B;exports.sendTelemetry=Y;
5
+ [truncated \u2014 original ${t.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${n} chars`)));let i=K(),d={severity:e,message:s,properties:{...this.defaultContext,...D(this.sessionId,this.anonymousId,this.release,this.environment,this.userProperties),...i?{code_location:i}:{},...r},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(w,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(k,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(k,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(k,e);}setRelease(e){this.release=e;}getRelease(){return this.release}setEnvironment(e){this.environment=e;}getEnvironment(){return this.environment}setUser(e){this.identify(e.id),this.userProperties={...e};}getUser(){return {...this.userProperties}}track(e,t){if(this.disabled)return;let{distinctId:r,...n}=t??{},s={event:e,distinctId:r??this.anonymousId,properties:{...U(),...n,$session_id:this.sessionId,...this.release?{$release:this.release}:{},$environment:this.environment},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(e){if(this.disabled)return;let t={ts:e.ts??new Date().toISOString(),...e};this.breadcrumbBuffer.push(t),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(e,t){if(this.disabled)return;let r=this.buildErrorEntry(e,t);this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(r.message,{exception_type:r.exception_type,frames:r.frames});}captureMessage(e,t){if(this.disabled)return;let r={level:t?.level??"info",message:e,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(e);}buildErrorEntry(e,t){let r,n,s=[];if(e instanceof Error)r=e.name,n=e.message,s=Q(e.stack);else if(typeof e=="string")n=e;else try{n=JSON.stringify(e);}catch{n=String(e);}return {level:t?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:r,message:n,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id,release:this.release??void 0,environment:this.environment}}captureVital(e,t,r){if(this.disabled||!Number.isFinite(t)||t<0)return;let n=r?.rating??Y(e,t),s={metric:e,value_ms:e==="cls"?t:Math.round(t),rating:n,route:r?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:r?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:e.toUpperCase(),$value_ms:s.value_ms,$rating:n}});}startTransaction(e){return this.makeSpan(void 0,e)}startSpan(e){return this.makeSpan(void 0,e)}makeSpan(e,t){let r=t?.trace_id??t?.parent?.trace_id??e?.trace_id??W(),n=J(),s=t?.parent?.span_id??e?.span_id,i=Date.now(),d=new Date(i).toISOString(),a={...t?.attributes??{}},u="unset",c=[],l=false,f=this,g={span_id:n,trace_id:r,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){c.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(l)return;l=true;let h=Date.now(),p={span_id:n,trace_id:r,parent_span_id:s,name:t?.name,op:t?.op,status:u==="unset"?"ok":u,kind:t?.kind,attributes:a,events:c,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-i};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),r=this.errorBuffer.splice(0),n=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),i=[];this.useEnvelope?(e.length>0||t.length>0||r.length>0||n.length>0||s.length>0)&&i.push(this.sendEnvelope(e,t,r,n,s)):(e.length>0&&i.push(this.sendLogs(e)),t.length>0&&i.push(this.sendEvents(t))),await Promise.all(i);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(e){for(let r=0;r<e.length;r+=500){let s=e.slice(r,r+500).map(i=>({severity:i.severity,message:i.message,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/logs",s,i=>{for(let d of i)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(e){for(let r=0;r<e.length;r+=500){let s=e.slice(r,r+500).map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/events",s,i=>{for(let d of i)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(e,t,r,n,s){let d=[...e.map(a=>({kind:"log",entry:a})),...t.map(a=>({kind:"event",entry:a})),...r.map(a=>({kind:"error",entry:a})),...n.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),c=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),l=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[c,...l].join(`
6
+ `);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(e,t,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:e});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),i=Math.random()*500;return await new Promise(d=>setTimeout(d,s+i)),this.postEnvelopeWithRetry(e,t,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let i of t)i.kind==="log"?this.logBuffer.push(i.entry):i.kind==="event"?this.eventBuffer.push(i.entry):i.kind==="error"?this.errorBuffer.push(i.entry):i.kind==="vital"?this.vitalBuffer.push(i.entry):this.spanBuffer.push(i.entry);}}catch(n){if(r===0)for(let s of t)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(e,t,r,n=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(e,t,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(t);return}let i=await s.json().catch(()=>null);if(i&&i.rejected&&i.rejected>0){let d=t.slice(i.accepted??0);d.length>0&&r(d);}}catch(s){let i=s instanceof Error?s:new Error(String(s));n===0&&r(t),this.onError(i);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let e=(t,r)=>{if(this.useEnvelope)this.captureVital(t.toLowerCase(),r);else {let n=t==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:t,[n]:t==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(t=>{let r=t.getEntries()[0];r&&e("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let r=t.getEntries(),n=r[r.length-1];n&&e("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let t=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(t+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{t>0&&e("CLS",Math.round(t*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&e("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,i=s(n.domainLookupEnd)-s(n.domainLookupStart);i>0&&this.captureVital("dns",i);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let t=performance.getEntriesByType?.("navigation")?.[0];t?.responseStart&&e("TTFB",t.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(t?.domainLookupEnd)-r(t?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(t?.connectEnd)-r(t?.connectStart);s>0&&this.captureVital("tcp",s);let i=r(t?.responseEnd)-r(t?.responseStart);i>0&&this.captureVital("download",i);let d=r(t?.domComplete)-r(t?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(t?.loadEventEnd)-r(t?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r.duration;n>0&&e("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let e=(t="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,t));};if(typeof history<"u"){let t=history.pushState,r=history.replaceState;history.pushState=function(...n){t.apply(this,n),e("push");},history.replaceState=function(...n){r.apply(this,n),e("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>e("popstate"));}startNavTransaction(e,t){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:e,attributes:{"navigation.type":t,"http.url":typeof location<"u"?location.href:e}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let e=globalThis;typeof e.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=t=>{let r=t,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=t=>{let n=t.reason,s=n;if(!(n instanceof Error)){let i;if(typeof n=="string")i=n;else try{i=JSON.stringify(n);}catch{i=String(n);}s=new Error(i);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},e.addEventListener("error",this.errorHandler),e.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let e=globalThis;typeof e.removeEventListener=="function"&&(this.errorHandler&&(e.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(e.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let e=globalThis;if(this.originalFetch)return;this.originalFetch=e.fetch;let t=e.fetch.bind(globalThis),r=this;e.fetch=function(s,i){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=i??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return t(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let t=globalThis.XMLHttpRequest;if(!t||!t.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=t.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,i=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,i.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;i.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=i,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let t=globalThis.XMLHttpRequest?.prototype;if(!t)return;let r=Symbol.for("goodlogs.xhr.patched");t.__gl_orig_open&&(t.open=t.__gl_orig_open),t.__gl_orig_set_header&&(t.setRequestHeader=t.__gl_orig_set_header),t.__gl_orig_send&&(t.send=t.__gl_orig_send),delete t.__gl_orig_open,delete t.__gl_orig_set_header,delete t.__gl_orig_send,delete t[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e,r=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",i=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80),u=globalThis,c=u.innerWidth,l=u.innerHeight,f=u.scrollY,g=typeof document<"u"?document.documentElement?.scrollHeight:void 0;this.track(n||"$click",{properties:{$element_tag:s,$element_text:i||void 0,$element_href:d,$element_classes:a||void 0,$element_selector:X(r),$click_x:t.clientX,$click_y:t.clientY,$page_x:t.pageX,$page_y:t.pageY,$viewport_w:c,$viewport_h:l,$scroll_y:f,$doc_h:g,$url:typeof location<"u"?location.href:void 0,$pathname:typeof location<"u"?location.pathname:void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var x=R;var I=class{constructor(e){if(!e.apiKey)throw new Error("apiKey is required");if(!e.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint),this.timeout=e.timeout??3e4,this.alerts=new L(this),this.slos=new P(this),this.ai=new A(this);}async _request(e,t,r){let n=`${this.endpoint}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=new AbortController,d=setTimeout(()=>i.abort(),this.timeout);try{let a=await fetch(n,{method:e,headers:s,body:r?JSON.stringify(r):void 0,signal:i.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(e){return this._request("GET",e)}_post(e,t){return this._request("POST",e,t)}_put(e,t){return this._request("PUT",e,t)}_delete(e){return this._request("DELETE",e)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(e){return this._post("/v1/gql/query",{q:e})}gqlBatch(e){return this._post("/v1/gql",{queries:e})}gqlAutocomplete(e,t){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(e)}`;return t!==void 0&&(r+=`&cursor=${t}`),this._get(r)}nl2gql(e,t){return this._post("/v1/gql/nl",{prompt:e,mode:t})}},L=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/alerts")}create(e){return this.client._post("/v1/alerts",e)}update(e,t){return this.client._put(`/v1/alerts/${e}`,t)}delete(e){return this.client._delete(`/v1/alerts/${e}`)}mute(e,t){return this.client._post(`/v1/alerts/${e}/mute`,{minutes:t})}},P=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/slos")}create(e){return this.client._post("/v1/slos",e)}update(e,t){return this.client._put(`/v1/slos/${e}`,t)}delete(e){return this.client._delete(`/v1/slos/${e}`)}},A=class{constructor(e){this.client=e;}chat(e,t){return this.client._post("/v1/ai/chat",{message:e,session_id:t})}},T=class extends Error{constructor(t,r,n){super(r);this.status=t;this.code=n;this.name="GoodLogsApiError";}};var H="0.1.0";function Z(o,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":H};e?.token&&(r.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:o.source,event:o.event,level:o.level??"info",metadata:{...o.metadata,sdk_version:H}}),keepalive:true}).catch(()=>{});}function C(o){if(!o)return null;let e=o.trim().split("-");if(e.length!==4)return null;let[t,r,n,s]=e;return t.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(o,e){if(!o)return;let t=o[e]??o[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function ee(o){return function(t,r,n){let s=(t.method??"GET").toUpperCase(),i=t.originalUrl??t.url??"",d=C(N(t.headers,"traceparent")),a=o.startTransaction({op:"http.server",name:`${s} ${i}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":i}}),u=false,c=()=>{if(u)return;u=true;let l=t.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),t.goodlogs={span:a},n();}}function te(o){return function(t,r,n){t.addHook("onRequest",(s,i,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=o.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),t.addHook("onResponse",(s,i,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=i.statusCode??i.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function ne(o){return {intercept(e,t){let r=e.switchToHttp(),n=r.getRequest(),s=r.getResponse(),i=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=o.startTransaction({op:"http.server",name:`${i} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":i,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=t.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function re(o){let e=globalThis.process;if(!e||typeof e.on!="function")return;let t=e,r=Symbol.for("goodlogs.node-process.patched");t[r]||(e.on("uncaughtException",n=>{try{o.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),o.flush();}catch{}}),e.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());o.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[r]=true);}var q=globalThis.URL;function E(o){return !!q&&o instanceof q}var j=Symbol.for("goodlogs.node-http.patched");function se(...o){let e=o[0],t=o[1],r="GET",n="";if(typeof e=="string")n=e,t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(E(e))n=e.toString(),t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(e&&typeof e=="object"){let i=e;r=String(i.method??r).toUpperCase();let d=(i.protocol??"http:").replace(":",""),a=i.hostname??i.host??"localhost",u=i.port?`:${i.port}`:"";n=`${d}://${a}${u}${i.path??"/"}`;}return {method:r,url:n,isOurs:i=>!!i&&n.startsWith(i)}}function ie(o,e,t){let r=o[0]&&typeof o[0]=="object"&&!E(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!E(o[1])?o[1]:void 0;r&&(r.headers||(r.headers={}),!(e in r.headers)&&!(e.toLowerCase()in r.headers)&&(r.headers[e]=t));}function oe(o,e){let t=e?.endpoint??o.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let i=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=se(...a);if(!c||l(t))return i(...a);let f=o.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});ie(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=i(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
7
+ exports.GoodLogs=x;exports.GoodLogsApiError=T;exports.GoodLogsClient=I;exports.REGION_URLS=$;exports.goodlogsExpress=ee;exports.goodlogsFastify=te;exports.goodlogsNestInterceptor=ne;exports.instrumentNodeHttp=oe;exports.instrumentNodeProcess=re;exports.parseTraceparent=C;exports.resolveEndpoint=y;exports.resolveRegion=B;exports.sendTelemetry=Z;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.cjs';
2
- export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CkECCGvR.cjs';
1
+ import { G as GoodLogs } from './client-CaWt4mri.cjs';
2
+ export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CaWt4mri.cjs';
3
3
 
4
4
  interface LogRecord {
5
5
  id: number;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.js';
2
- export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CkECCGvR.js';
1
+ import { G as GoodLogs } from './client-CaWt4mri.js';
2
+ export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CaWt4mri.js';
3
3
 
4
4
  interface LogRecord {
5
5
  id: number;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var S=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var x={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(i){let t=i.split("_");return t.length>=4&&t[0]==="gl"?t[2]:"eu"}function y(i,t){if(t)return t;let e=B(i);return x[e]||x.eu}var G=5e3,F=50,v="0.4.2",w="gl_anon_id",E="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return (i==="x"?t:t&3|8).toString(16)})}function M(){let i={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(i.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(i.$language=navigator.language??""),typeof location<"u"&&(i.$url=location.href,i.$path=location.pathname,i.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(i.$referrer=document.referrer),document.title&&(i.$title=document.title))),i}function U(i,t){let e={$session_id:i,$distinct_id:t,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(e.$url=location.href,e.$path=location.pathname),e}function D(){if(!(typeof document<"u"))try{let t=new Error().stack?.split(`
2
- `);if(!t)return;for(let e=3;e<Math.min(t.length,8);e++){let r=t[e]?.trim();if(!r||r.includes("goodlogs")&&(r.includes("client.")||r.includes("index.")))continue;let n=r.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(n){let s=n[1]||"<anonymous>",o=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${o}:${d}`}}}catch{}}function K(){if(typeof localStorage<"u"){let i=localStorage.getItem(w);if(i)return i;let t=b();return localStorage.setItem(w,t),t}return b()}function V(){if(typeof sessionStorage<"u"){let i=sessionStorage.getItem(E);if(i)return i;let t=b();return sessionStorage.setItem(E,t),t}return b()}function X(){let i="";for(let t=0;t<32;t++)i+=(Math.random()*16|0).toString(16);return i}function z(){let i="";for(let t=0;t<16;t++)i+=(Math.random()*16|0).toString(16);return i}function W(i,t){switch(i){case "lcp":return t<=2500?"good":t<=4e3?"needs-improvement":"poor";case "inp":return t<=200?"good":t<=500?"needs-improvement":"poor";case "cls":return t<=.1?"good":t<=.25?"needs-improvement":"poor";case "fcp":return t<=1800?"good":t<=3e3?"needs-improvement":"poor";case "ttfb":return t<=800?"good":t<=1800?"needs-improvement":"poor";case "dns":return t<=20?"good":t<=100?"needs-improvement":"poor";case "tcp":return t<=50?"good":t<=200?"needs-improvement":"poor";case "download":return t<=100?"good":t<=500?"needs-improvement":"poor";case "dom_processing":return t<=500?"good":t<=1500?"needs-improvement":"poor";case "page_load":return t<=1e3?"good":t<=3e3?"needs-improvement":"poor";default:return}}function J(i){if(!i)return [];let t=[];for(let e of i.split(`
3
- `)){let r=e.trim();if(!r||r.startsWith("Error")||r.startsWith("at Error"))continue;let n=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(r);if(n){let s=n[1]?.trim(),o=n[2];t.push({function:s&&s!=="<anonymous>"?s:void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")&&!o.startsWith("internal/")});continue}if(n=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(r),n){let s=n[1]?.trim(),o=n[2];t.push({function:s||void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")});}}return t}var R=class R{constructor(t){this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint).replace(/\/+$/,""),this.flushInterval=t.flushInterval??G,this.batchSize=t.batchSize??F,this.defaultContext=t.defaultContext??{},this.onError=t.onError??(()=>{}),this.disabled=t.disabled??false,this.telemetry=t.telemetry??true,this.useEnvelope=t.useEnvelope??false,this.autoFetch=t.autoFetch??(this.useEnvelope&&t.autocapture!==false),this.anonymousId=K(),this.sessionId=V(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),t.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(t,e,r){if(this.disabled)return;let n=65536,s=e;e.length>n&&(s=e.slice(0,n-100)+`
1
+ var S=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var $={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(o){let e=o.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function y(o,e){if(e)return e;let t=B(o);return $[t]||$.eu}var G=5e3,F=50,v="0.4.4",w="gl_anon_id",k="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let e=Math.random()*16|0;return (o==="x"?e:e&3|8).toString(16)})}function U(){let o={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(o.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(o.$language=navigator.language??""),typeof location<"u"&&(o.$url=location.href,o.$path=location.pathname,o.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(o.$referrer=document.referrer),document.title&&(o.$title=document.title))),o}function M(o,e){let t={$session_id:o,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function D(o,e,t,r,n){let s=M(o,e);return t&&(s.$release=t),s.$environment=r,n.email&&(s.$user_email=n.email),n.name&&(s.$user_name=n.name),s}function K(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
+ `);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let r=e[t]?.trim();if(!r||r.includes("goodlogs")&&(r.includes("client.")||r.includes("index.")))continue;let n=r.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(n){let s=n[1]||"<anonymous>",i=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${i}:${d}`}}}catch{}}function X(o){let e=[],t=o;for(;t&&t.tagName;){let r=t.tagName.toLowerCase();if(r==="html"||r==="body"){e.unshift(r);break}if(t.id){e.unshift(`#${t.id}`);break}let n=1,s=t;for(;s?.previousElementSibling;)s.previousElementSibling.tagName?.toLowerCase()===r&&n++,s=s.previousElementSibling;e.unshift(n>1?`${r}:nth-of-type(${n})`:r),t=t.parentElement;}return e.join(" > ").slice(0,200)}function V(){if(typeof localStorage<"u"){let o=localStorage.getItem(w);if(o)return o;let e=b();return localStorage.setItem(w,e),e}return b()}function z(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(k);if(o)return o;let e=b();return sessionStorage.setItem(k,e),e}return b()}function W(){let o="";for(let e=0;e<32;e++)o+=(Math.random()*16|0).toString(16);return o}function J(){let o="";for(let e=0;e<16;e++)o+=(Math.random()*16|0).toString(16);return o}function Y(o,e){switch(o){case "lcp":return e<=2500?"good":e<=4e3?"needs-improvement":"poor";case "inp":return e<=200?"good":e<=500?"needs-improvement":"poor";case "cls":return e<=.1?"good":e<=.25?"needs-improvement":"poor";case "fcp":return e<=1800?"good":e<=3e3?"needs-improvement":"poor";case "ttfb":return e<=800?"good":e<=1800?"needs-improvement":"poor";case "dns":return e<=20?"good":e<=100?"needs-improvement":"poor";case "tcp":return e<=50?"good":e<=200?"needs-improvement":"poor";case "download":return e<=100?"good":e<=500?"needs-improvement":"poor";case "dom_processing":return e<=500?"good":e<=1500?"needs-improvement":"poor";case "page_load":return e<=1e3?"good":e<=3e3?"needs-improvement":"poor";default:return}}function Q(o){if(!o)return [];let e=[];for(let t of o.split(`
3
+ `)){let r=t.trim();if(!r||r.startsWith("Error")||r.startsWith("at Error"))continue;let n=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(r);if(n){let s=n[1]?.trim(),i=n[2];e.push({function:s&&s!=="<anonymous>"?s:void 0,filename:i,lineno:Number(n[3]),colno:Number(n[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")&&!i.startsWith("internal/")});continue}if(n=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(r),n){let s=n[1]?.trim(),i=n[2];e.push({function:s||void 0,filename:i,lineno:Number(n[3]),colno:Number(n[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")});}}return e}var R=class R{constructor(e){this.userProperties={};this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??G,this.batchSize=e.batchSize??F,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.useEnvelope=e.useEnvelope??false,this.autoFetch=e.autoFetch??(this.useEnvelope&&e.autocapture!==false),this.release=e.release??null,this.environment=e.environment??"production",this.anonymousId=V(),this.sessionId=z(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),!this.disabled&&typeof setTimeout<"u"&&setTimeout(()=>{!this.release&&typeof console<"u"&&console.warn("[GoodLogs] No release version set. Set `release` in options or call gl.setRelease('1.2.3') for release health tracking.");},5e3),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(e,t,r){if(this.disabled)return;let n=65536,s=t;t.length>n&&(s=t.slice(0,n-100)+`
4
4
 
5
- [truncated \u2014 original ${e.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${e.length} to ${n} chars`)));let o=D(),d={severity:t,message:s,properties:{...this.defaultContext,...U(this.sessionId,this.anonymousId),...o?{code_location:o}:{},...r},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(t,e){this.log("debug",t,e);}info(t,e){this.log("info",t,e);}warn(t,e){this.log("warn",t,e);}error(t,e){this.log("error",t,e);}fatal(t,e){this.log("fatal",t,e);}identify(t){this.anonymousId=t,typeof localStorage<"u"&&localStorage.setItem(w,t);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}setSessionId(t){this.sessionId=t,typeof sessionStorage<"u"&&sessionStorage.setItem(E,t);}track(t,e){if(this.disabled)return;let{distinctId:r,...n}=e??{},s={event:t,distinctId:r??this.anonymousId,properties:{...M(),...n,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(t){if(this.disabled)return;let e={ts:t.ts??new Date().toISOString(),...t};this.breadcrumbBuffer.push(e),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(t,e){if(this.disabled)return;let r=this.buildErrorEntry(t,e);this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(r.message,{exception_type:r.exception_type,frames:r.frames});}captureMessage(t,e){if(this.disabled)return;let r={level:e?.level??"info",message:t,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(t);}buildErrorEntry(t,e){let r,n,s=[];if(t instanceof Error)r=t.name,n=t.message,s=J(t.stack);else if(typeof t=="string")n=t;else try{n=JSON.stringify(t);}catch{n=String(t);}return {level:e?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:r,message:n,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id}}captureVital(t,e,r){if(this.disabled||!Number.isFinite(e)||e<0)return;let n=r?.rating??W(t,e),s={metric:t,value_ms:t==="cls"?e:Math.round(e),rating:n,route:r?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:r?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:t.toUpperCase(),$value_ms:s.value_ms,$rating:n}});}startTransaction(t){return this.makeSpan(void 0,t)}startSpan(t){return this.makeSpan(void 0,t)}makeSpan(t,e){let r=e?.trace_id??e?.parent?.trace_id??t?.trace_id??X(),n=z(),s=e?.parent?.span_id??t?.span_id,o=Date.now(),d=new Date(o).toISOString(),a={...e?.attributes??{}},u="unset",c=[],l=false,f=this,g={span_id:n,trace_id:r,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){c.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(l)return;l=true;let h=Date.now(),p={span_id:n,trace_id:r,parent_span_id:s,name:e?.name,op:e?.op,status:u==="unset"?"ok":u,kind:e?.kind,attributes:a,events:c,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-o};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r=this.errorBuffer.splice(0),n=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),o=[];this.useEnvelope?(t.length>0||e.length>0||r.length>0||n.length>0||s.length>0)&&o.push(this.sendEnvelope(t,e,r,n,s)):(t.length>0&&o.push(this.sendLogs(t)),e.length>0&&o.push(this.sendEvents(e))),await Promise.all(o);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({severity:o.severity,message:o.message,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/logs",s,o=>{for(let d of o)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({event:o.event,distinctId:o.distinctId,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/events",s,o=>{for(let d of o)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(t,e,r,n,s){let d=[...t.map(a=>({kind:"log",entry:a})),...e.map(a=>({kind:"event",entry:a})),...r.map(a=>({kind:"error",entry:a})),...n.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),c=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),l=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[c,...l].join(`
6
- `);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(t,e,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:t});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),this.postEnvelopeWithRetry(t,e,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let o of e)o.kind==="log"?this.logBuffer.push(o.entry):o.kind==="event"?this.eventBuffer.push(o.entry):o.kind==="error"?this.errorBuffer.push(o.entry):o.kind==="vital"?this.vitalBuffer.push(o.entry):this.spanBuffer.push(o.entry);}}catch(n){if(r===0)for(let s of e)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(t,e,r,n=0){try{let s=await fetch(`${this.endpoint}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:e})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(t,e,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(e);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=e.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(e),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let t=this.timer;typeof t?.unref=="function"&&t.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let t=(e,r)=>{if(this.useEnvelope)this.captureVital(e.toLowerCase(),r);else {let n=e==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:e,[n]:e==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(e=>{let r=e.getEntries()[0];r&&t("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let r=e.getEntries(),n=r[r.length-1];n&&t("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{e>0&&t("CLS",Math.round(e*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&t("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,o=s(n.domainLookupEnd)-s(n.domainLookupStart);o>0&&this.captureVital("dns",o);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&t("TTFB",e.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(e?.domainLookupEnd)-r(e?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(e?.connectEnd)-r(e?.connectStart);s>0&&this.captureVital("tcp",s);let o=r(e?.responseEnd)-r(e?.responseStart);o>0&&this.captureVital("download",o);let d=r(e?.domComplete)-r(e?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(e?.loadEventEnd)-r(e?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r.duration;n>0&&t("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let t=(e="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,e));};if(typeof history<"u"){let e=history.pushState,r=history.replaceState;history.pushState=function(...n){e.apply(this,n),t("push");},history.replaceState=function(...n){r.apply(this,n),t("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>t("popstate"));}startNavTransaction(t,e){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:t,attributes:{"navigation.type":e,"http.url":typeof location<"u"?location.href:t}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let t=globalThis;typeof t.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=e=>{let r=e,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=e=>{let n=e.reason,s=n;if(!(n instanceof Error)){let o;if(typeof n=="string")o=n;else try{o=JSON.stringify(n);}catch{o=String(n);}s=new Error(o);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},t.addEventListener("error",this.errorHandler),t.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let t=globalThis;typeof t.removeEventListener=="function"&&(this.errorHandler&&(t.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(t.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let t=globalThis;if(this.originalFetch)return;this.originalFetch=t.fetch;let e=t.fetch.bind(globalThis),r=this;t.fetch=function(s,o){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=o??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return e(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},e(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let e=globalThis.XMLHttpRequest;if(!e||!e.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=e.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,o=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,o.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;o.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=o,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let e=globalThis.XMLHttpRequest?.prototype;if(!e)return;let r=Symbol.for("goodlogs.xhr.patched");e.__gl_orig_open&&(e.open=e.__gl_orig_open),e.__gl_orig_set_header&&(e.setRequestHeader=e.__gl_orig_set_header),e.__gl_orig_send&&(e.send=e.__gl_orig_send),delete e.__gl_orig_open,delete e.__gl_orig_set_header,delete e.__gl_orig_send,delete e[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=t=>{let r=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",o=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80);this.track(n||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};t.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),e.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(t,e,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:t,level:e,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var I=R;var L=class{constructor(t){if(!t.apiKey)throw new Error("apiKey is required");if(!t.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint),this.timeout=t.timeout??3e4,this.alerts=new $(this),this.slos=new P(this),this.ai=new A(this);}async _request(t,e,r){let n=`${this.endpoint}${e}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:t,headers:s,body:r?JSON.stringify(r):void 0,signal:o.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(t){return this._request("GET",t)}_post(t,e){return this._request("POST",t,e)}_put(t,e){return this._request("PUT",t,e)}_delete(t){return this._request("DELETE",t)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(t){return this._post("/v1/gql/query",{q:t})}gqlBatch(t){return this._post("/v1/gql",{queries:t})}gqlAutocomplete(t,e){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(t)}`;return e!==void 0&&(r+=`&cursor=${e}`),this._get(r)}nl2gql(t,e){return this._post("/v1/gql/nl",{prompt:t,mode:e})}},$=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/alerts")}create(t){return this.client._post("/v1/alerts",t)}update(t,e){return this.client._put(`/v1/alerts/${t}`,e)}delete(t){return this.client._delete(`/v1/alerts/${t}`)}mute(t,e){return this.client._post(`/v1/alerts/${t}/mute`,{minutes:e})}},P=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/slos")}create(t){return this.client._post("/v1/slos",t)}update(t,e){return this.client._put(`/v1/slos/${t}`,e)}delete(t){return this.client._delete(`/v1/slos/${t}`)}},A=class{constructor(t){this.client=t;}chat(t,e){return this.client._post("/v1/ai/chat",{message:t,session_id:e})}},T=class extends Error{constructor(e,r,n){super(r);this.status=e;this.code=n;this.name="GoodLogsApiError";}};var q="0.1.0";function Y(i,t){let e=y(t?.apiKey??"",t?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};t?.token&&(r.Authorization=`Bearer ${t.token}`),fetch(`${e}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function C(i){if(!i)return null;let t=i.trim().split("-");if(t.length!==4)return null;let[e,r,n,s]=t;return e.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(i,t){if(!i)return;let e=i[t]??i[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function Q(i){return function(e,r,n){let s=(e.method??"GET").toUpperCase(),o=e.originalUrl??e.url??"",d=C(N(e.headers,"traceparent")),a=i.startTransaction({op:"http.server",name:`${s} ${o}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":o}}),u=false,c=()=>{if(u)return;u=true;let l=e.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),e.goodlogs={span:a},n();}}function Z(i){return function(e,r,n){e.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),e.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function tt(i){return {intercept(t,e){let r=t.switchToHttp(),n=r.getRequest(),s=r.getResponse(),o=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=e.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function et(i){let t=globalThis.process;if(!t||typeof t.on!="function")return;let e=t,r=Symbol.for("goodlogs.node-process.patched");e[r]||(t.on("uncaughtException",n=>{try{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.flush();}catch{}}),t.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),e[r]=true);}var H=globalThis.URL;function k(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function nt(...i){let t=i[0],e=i[1],r="GET",n="";if(typeof t=="string")n=t,e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(k(t))n=t.toString(),e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(t&&typeof t=="object"){let o=t;r=String(o.method??r).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",u=o.port?`:${o.port}`:"";n=`${d}://${a}${u}${o.path??"/"}`;}return {method:r,url:n,isOurs:o=>!!o&&n.startsWith(o)}}function rt(i,t,e){let r=i[0]&&typeof i[0]=="object"&&!k(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!k(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(t in r.headers)&&!(t.toLowerCase()in r.headers)&&(r.headers[t]=e));}function st(i,t){let e=t?.endpoint??i.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let o=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=nt(...a);if(!c||l(e))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});rt(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=o(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
7
- export{I as GoodLogs,T as GoodLogsApiError,L as GoodLogsClient,x as REGION_URLS,Q as goodlogsExpress,Z as goodlogsFastify,tt as goodlogsNestInterceptor,st as instrumentNodeHttp,et as instrumentNodeProcess,C as parseTraceparent,y as resolveEndpoint,B as resolveRegion,Y as sendTelemetry};
5
+ [truncated \u2014 original ${t.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${n} chars`)));let i=K(),d={severity:e,message:s,properties:{...this.defaultContext,...D(this.sessionId,this.anonymousId,this.release,this.environment,this.userProperties),...i?{code_location:i}:{},...r},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(w,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(k,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(k,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(k,e);}setRelease(e){this.release=e;}getRelease(){return this.release}setEnvironment(e){this.environment=e;}getEnvironment(){return this.environment}setUser(e){this.identify(e.id),this.userProperties={...e};}getUser(){return {...this.userProperties}}track(e,t){if(this.disabled)return;let{distinctId:r,...n}=t??{},s={event:e,distinctId:r??this.anonymousId,properties:{...U(),...n,$session_id:this.sessionId,...this.release?{$release:this.release}:{},$environment:this.environment},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(e){if(this.disabled)return;let t={ts:e.ts??new Date().toISOString(),...e};this.breadcrumbBuffer.push(t),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(e,t){if(this.disabled)return;let r=this.buildErrorEntry(e,t);this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(r.message,{exception_type:r.exception_type,frames:r.frames});}captureMessage(e,t){if(this.disabled)return;let r={level:t?.level??"info",message:e,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(e);}buildErrorEntry(e,t){let r,n,s=[];if(e instanceof Error)r=e.name,n=e.message,s=Q(e.stack);else if(typeof e=="string")n=e;else try{n=JSON.stringify(e);}catch{n=String(e);}return {level:t?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:r,message:n,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id,release:this.release??void 0,environment:this.environment}}captureVital(e,t,r){if(this.disabled||!Number.isFinite(t)||t<0)return;let n=r?.rating??Y(e,t),s={metric:e,value_ms:e==="cls"?t:Math.round(t),rating:n,route:r?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:r?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:e.toUpperCase(),$value_ms:s.value_ms,$rating:n}});}startTransaction(e){return this.makeSpan(void 0,e)}startSpan(e){return this.makeSpan(void 0,e)}makeSpan(e,t){let r=t?.trace_id??t?.parent?.trace_id??e?.trace_id??W(),n=J(),s=t?.parent?.span_id??e?.span_id,i=Date.now(),d=new Date(i).toISOString(),a={...t?.attributes??{}},u="unset",c=[],l=false,f=this,g={span_id:n,trace_id:r,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){c.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(l)return;l=true;let h=Date.now(),p={span_id:n,trace_id:r,parent_span_id:s,name:t?.name,op:t?.op,status:u==="unset"?"ok":u,kind:t?.kind,attributes:a,events:c,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-i};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),r=this.errorBuffer.splice(0),n=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),i=[];this.useEnvelope?(e.length>0||t.length>0||r.length>0||n.length>0||s.length>0)&&i.push(this.sendEnvelope(e,t,r,n,s)):(e.length>0&&i.push(this.sendLogs(e)),t.length>0&&i.push(this.sendEvents(t))),await Promise.all(i);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(e){for(let r=0;r<e.length;r+=500){let s=e.slice(r,r+500).map(i=>({severity:i.severity,message:i.message,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/logs",s,i=>{for(let d of i)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(e){for(let r=0;r<e.length;r+=500){let s=e.slice(r,r+500).map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/events",s,i=>{for(let d of i)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(e,t,r,n,s){let d=[...e.map(a=>({kind:"log",entry:a})),...t.map(a=>({kind:"event",entry:a})),...r.map(a=>({kind:"error",entry:a})),...n.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),c=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),l=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[c,...l].join(`
6
+ `);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(e,t,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:e});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),i=Math.random()*500;return await new Promise(d=>setTimeout(d,s+i)),this.postEnvelopeWithRetry(e,t,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let i of t)i.kind==="log"?this.logBuffer.push(i.entry):i.kind==="event"?this.eventBuffer.push(i.entry):i.kind==="error"?this.errorBuffer.push(i.entry):i.kind==="vital"?this.vitalBuffer.push(i.entry):this.spanBuffer.push(i.entry);}}catch(n){if(r===0)for(let s of t)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(e,t,r,n=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(e,t,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(t);return}let i=await s.json().catch(()=>null);if(i&&i.rejected&&i.rejected>0){let d=t.slice(i.accepted??0);d.length>0&&r(d);}}catch(s){let i=s instanceof Error?s:new Error(String(s));n===0&&r(t),this.onError(i);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let e=(t,r)=>{if(this.useEnvelope)this.captureVital(t.toLowerCase(),r);else {let n=t==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:t,[n]:t==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(t=>{let r=t.getEntries()[0];r&&e("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let r=t.getEntries(),n=r[r.length-1];n&&e("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let t=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(t+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{t>0&&e("CLS",Math.round(t*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&e("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,i=s(n.domainLookupEnd)-s(n.domainLookupStart);i>0&&this.captureVital("dns",i);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let t=performance.getEntriesByType?.("navigation")?.[0];t?.responseStart&&e("TTFB",t.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(t?.domainLookupEnd)-r(t?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(t?.connectEnd)-r(t?.connectStart);s>0&&this.captureVital("tcp",s);let i=r(t?.responseEnd)-r(t?.responseStart);i>0&&this.captureVital("download",i);let d=r(t?.domComplete)-r(t?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(t?.loadEventEnd)-r(t?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r.duration;n>0&&e("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let e=(t="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,t));};if(typeof history<"u"){let t=history.pushState,r=history.replaceState;history.pushState=function(...n){t.apply(this,n),e("push");},history.replaceState=function(...n){r.apply(this,n),e("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>e("popstate"));}startNavTransaction(e,t){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:e,attributes:{"navigation.type":t,"http.url":typeof location<"u"?location.href:e}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let e=globalThis;typeof e.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=t=>{let r=t,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=t=>{let n=t.reason,s=n;if(!(n instanceof Error)){let i;if(typeof n=="string")i=n;else try{i=JSON.stringify(n);}catch{i=String(n);}s=new Error(i);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},e.addEventListener("error",this.errorHandler),e.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let e=globalThis;typeof e.removeEventListener=="function"&&(this.errorHandler&&(e.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(e.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let e=globalThis;if(this.originalFetch)return;this.originalFetch=e.fetch;let t=e.fetch.bind(globalThis),r=this;e.fetch=function(s,i){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=i??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return t(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let t=globalThis.XMLHttpRequest;if(!t||!t.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=t.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,i=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,i.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;i.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=i,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let t=globalThis.XMLHttpRequest?.prototype;if(!t)return;let r=Symbol.for("goodlogs.xhr.patched");t.__gl_orig_open&&(t.open=t.__gl_orig_open),t.__gl_orig_set_header&&(t.setRequestHeader=t.__gl_orig_set_header),t.__gl_orig_send&&(t.send=t.__gl_orig_send),delete t.__gl_orig_open,delete t.__gl_orig_set_header,delete t.__gl_orig_send,delete t[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e,r=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",i=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80),u=globalThis,c=u.innerWidth,l=u.innerHeight,f=u.scrollY,g=typeof document<"u"?document.documentElement?.scrollHeight:void 0;this.track(n||"$click",{properties:{$element_tag:s,$element_text:i||void 0,$element_href:d,$element_classes:a||void 0,$element_selector:X(r),$click_x:t.clientX,$click_y:t.clientY,$page_x:t.pageX,$page_y:t.pageY,$viewport_w:c,$viewport_h:l,$scroll_y:f,$doc_h:g,$url:typeof location<"u"?location.href:void 0,$pathname:typeof location<"u"?location.pathname:void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var x=R;var I=class{constructor(e){if(!e.apiKey)throw new Error("apiKey is required");if(!e.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint),this.timeout=e.timeout??3e4,this.alerts=new L(this),this.slos=new P(this),this.ai=new A(this);}async _request(e,t,r){let n=`${this.endpoint}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=new AbortController,d=setTimeout(()=>i.abort(),this.timeout);try{let a=await fetch(n,{method:e,headers:s,body:r?JSON.stringify(r):void 0,signal:i.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(e){return this._request("GET",e)}_post(e,t){return this._request("POST",e,t)}_put(e,t){return this._request("PUT",e,t)}_delete(e){return this._request("DELETE",e)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(e){return this._post("/v1/gql/query",{q:e})}gqlBatch(e){return this._post("/v1/gql",{queries:e})}gqlAutocomplete(e,t){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(e)}`;return t!==void 0&&(r+=`&cursor=${t}`),this._get(r)}nl2gql(e,t){return this._post("/v1/gql/nl",{prompt:e,mode:t})}},L=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/alerts")}create(e){return this.client._post("/v1/alerts",e)}update(e,t){return this.client._put(`/v1/alerts/${e}`,t)}delete(e){return this.client._delete(`/v1/alerts/${e}`)}mute(e,t){return this.client._post(`/v1/alerts/${e}/mute`,{minutes:t})}},P=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/slos")}create(e){return this.client._post("/v1/slos",e)}update(e,t){return this.client._put(`/v1/slos/${e}`,t)}delete(e){return this.client._delete(`/v1/slos/${e}`)}},A=class{constructor(e){this.client=e;}chat(e,t){return this.client._post("/v1/ai/chat",{message:e,session_id:t})}},T=class extends Error{constructor(t,r,n){super(r);this.status=t;this.code=n;this.name="GoodLogsApiError";}};var H="0.1.0";function Z(o,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":H};e?.token&&(r.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:o.source,event:o.event,level:o.level??"info",metadata:{...o.metadata,sdk_version:H}}),keepalive:true}).catch(()=>{});}function C(o){if(!o)return null;let e=o.trim().split("-");if(e.length!==4)return null;let[t,r,n,s]=e;return t.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(o,e){if(!o)return;let t=o[e]??o[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function ee(o){return function(t,r,n){let s=(t.method??"GET").toUpperCase(),i=t.originalUrl??t.url??"",d=C(N(t.headers,"traceparent")),a=o.startTransaction({op:"http.server",name:`${s} ${i}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":i}}),u=false,c=()=>{if(u)return;u=true;let l=t.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),t.goodlogs={span:a},n();}}function te(o){return function(t,r,n){t.addHook("onRequest",(s,i,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=o.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),t.addHook("onResponse",(s,i,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=i.statusCode??i.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function ne(o){return {intercept(e,t){let r=e.switchToHttp(),n=r.getRequest(),s=r.getResponse(),i=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=o.startTransaction({op:"http.server",name:`${i} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":i,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=t.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function re(o){let e=globalThis.process;if(!e||typeof e.on!="function")return;let t=e,r=Symbol.for("goodlogs.node-process.patched");t[r]||(e.on("uncaughtException",n=>{try{o.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),o.flush();}catch{}}),e.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());o.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[r]=true);}var q=globalThis.URL;function E(o){return !!q&&o instanceof q}var j=Symbol.for("goodlogs.node-http.patched");function se(...o){let e=o[0],t=o[1],r="GET",n="";if(typeof e=="string")n=e,t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(E(e))n=e.toString(),t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(e&&typeof e=="object"){let i=e;r=String(i.method??r).toUpperCase();let d=(i.protocol??"http:").replace(":",""),a=i.hostname??i.host??"localhost",u=i.port?`:${i.port}`:"";n=`${d}://${a}${u}${i.path??"/"}`;}return {method:r,url:n,isOurs:i=>!!i&&n.startsWith(i)}}function ie(o,e,t){let r=o[0]&&typeof o[0]=="object"&&!E(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!E(o[1])?o[1]:void 0;r&&(r.headers||(r.headers={}),!(e in r.headers)&&!(e.toLowerCase()in r.headers)&&(r.headers[e]=t));}function oe(o,e){let t=e?.endpoint??o.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let i=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=se(...a);if(!c||l(t))return i(...a);let f=o.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});ie(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=i(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
7
+ export{x as GoodLogs,T as GoodLogsApiError,I as GoodLogsClient,$ as REGION_URLS,ee as goodlogsExpress,te as goodlogsFastify,ne as goodlogsNestInterceptor,oe as instrumentNodeHttp,re as instrumentNodeProcess,C as parseTraceparent,y as resolveEndpoint,B as resolveRegion,Z as sendTelemetry};
package/dist/memory.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.cjs';
1
+ import { G as GoodLogs } from './client-CaWt4mri.cjs';
2
2
 
3
3
  /**
4
4
  * Memory Profiling — periodic JS heap sampling + per-script breakdown.
package/dist/memory.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.js';
1
+ import { G as GoodLogs } from './client-CaWt4mri.js';
2
2
 
3
3
  /**
4
4
  * Memory Profiling — periodic JS heap sampling + per-script breakdown.
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.cjs';
1
+ import { G as GoodLogs } from './client-CaWt4mri.cjs';
2
2
 
3
3
  /**
4
4
  * Continuous Profiling — browser JS Self-Profiling API.
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.js';
1
+ import { G as GoodLogs } from './client-CaWt4mri.js';
2
2
 
3
3
  /**
4
4
  * Continuous Profiling — browser JS Self-Profiling API.
package/dist/react.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ReactNode, ComponentType, FC } from 'react';
2
- import { G as GoodLogs } from './client-CkECCGvR.cjs';
2
+ import { G as GoodLogs } from './client-CaWt4mri.cjs';
3
3
 
4
4
  /**
5
5
  * React Profiler Integration — component render timing.
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ReactNode, ComponentType, FC } from 'react';
2
- import { G as GoodLogs } from './client-CkECCGvR.js';
2
+ import { G as GoodLogs } from './client-CaWt4mri.js';
3
3
 
4
4
  /**
5
5
  * React Profiler Integration — component render timing.
package/dist/replay.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var O=new Set([1,3,6]);function j(t){return t.every(e=>{if(e.type!==3)return false;let o=e.data?.source;return o!==void 0&&O.has(o)})}var w=null;async function V(t,e={}){if(typeof document>"u")return null;if(w)return w;let o=e.sampleRate??1;if(o<1&&Math.random()>o)return null;let i=e.rrwebRecord??await J();if(!i)return null;let r=t.endpoint,a=t.apiKey,p=t,C=e.flushIntervalMs??5e3,M=e.flushBytes??5e5,S=e.sessionTimeoutMs??1800*1e3,L=e.maxSessionMs??3600*1e3,s=p.sessionId,l=[],v=0,x=0,g=false,u=false,f=Date.now(),k=Date.now(),y=null,I=()=>{m(r,a,{session_id:s,distinct_id:p.getDistinctId(),start_url:typeof location<"u"?location.href:null,last_url:typeof location<"u"?location.href:null},e.onError);},R=()=>{d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);},d=async(n=false)=>{if(l.length===0)return;if(!n&&j(l)){l=[],v=0;return}let c=l,U=c[0].timestamp,D=c[c.length-1].timestamp,G=c.length;l=[],v=0;let q=x++;try{let h=JSON.stringify(c),H=await K(h),N=`${r}/v1/replay/chunks?session_id=${encodeURIComponent(s)}&seq=${q}&start_ts=${encodeURIComponent(new Date(U).toISOString())}&end_ts=${encodeURIComponent(new Date(D).toISOString())}&event_count=${G}`;await fetch(N,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/gzip","Content-Encoding":"gzip"},body:H,keepalive:!0});}catch(h){e.onError?.(h);}m(r,a,{session_id:s,last_url:typeof location<"u"?location.href:null,last_activity_at:new Date(D).toISOString(),has_error:g||void 0},e.onError);},b=()=>{R();try{y?.();}catch(n){e.onError?.(n);}p.newSession(),s=p.getSessionId(),x=0,g=false,f=Date.now(),k=Date.now(),I(),_();},_=()=>{y=i({emit:n=>{if(u)return;n.type===3&&O.has(n.data?.source??-1)||(f=Date.now()),l.push(n),v+=256,v>=M&&d();},checkoutEveryNms:6e4,maskAllInputs:e.maskAllInputs??true,blockSelector:e.blockSelector??"[data-gl-block]",maskTextSelector:e.maskTextSelector??"[data-gl-mask]",sampling:{mousemove:50,mouseInteraction:true,scroll:150,input:"last"}});},A=setInterval(()=>{globalThis.__gl_replay_has_error__&&(g=true);},1e3),P=()=>{if(!u){u=true,clearInterval($),clearInterval(z),clearInterval(A),document?.removeEventListener("visibilitychange",E),typeof window<"u"&&window.removeEventListener("beforeunload",T);try{y?.();}catch(n){e.onError?.(n);}R(),w=null;}};I(),_();let $=setInterval(()=>{d();},C),z=setInterval(()=>{if(u)return;let n=Date.now();if(n-f>S){b();return}if(n-k>L){b();return}},1e4),E=()=>{u||(document?.visibilityState==="hidden"?(d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError)):document?.visibilityState==="visible"&&(Date.now()-f>S?b():f=Date.now()));};document.addEventListener("visibilitychange",E);let T=()=>{d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);};typeof window<"u"&&window.addEventListener("beforeunload",T);let B={get sessionId(){return s},flush:()=>d(true),stop:P};return w=B,B}async function m(t,e,o,i){try{await fetch(`${t}/v1/replay/sessions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});}catch(r){i?.(r);}}async function K(t){if(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u")return t;let o=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip")),i=await new Response(o).arrayBuffer();return new Blob([i],{type:"application/gzip"})}async function J(){try{let t=await import('rrweb');return t.record??t.default?.record??null}catch{return null}}exports.startReplay=V;
1
+ 'use strict';var M=new Set([1,3,6]);function K(t){return t.every(e=>{if(e.type!==3)return false;let o=e.data?.source;return o!==void 0&&M.has(o)})}var g=null;async function F(t,e={}){if(typeof document>"u")return null;if(g)return g;let o=e.sampleRate??1;if(o<1&&Math.random()>o)return null;let i=e.rrwebRecord??await V();if(!i)return null;let r=t.endpoint,a=t.apiKey,p=t,L=e.flushIntervalMs??5e3,A=e.flushBytes??5e5,x=e.sessionTimeoutMs??1800*1e3,k=e.maxSessionMs??3600*1e3,s=p.sessionId,l=[],v=0,I=0,y=false,u=false,f=Date.now(),w=Date.now(),b=null,_=()=>{m(r,a,{session_id:s,distinct_id:p.getDistinctId(),started_at:new Date(w).toISOString(),start_url:typeof location<"u"?location.href:null,last_url:typeof location<"u"?location.href:null},e.onError);},R=()=>{let n=s;d(true),m(r,a,{session_id:n,ended_at:new Date().toISOString()},e.onError);},d=async(n=false)=>{if(l.length===0)return;if(!n&&K(l)){l=[],v=0;return}let c=l,G=c[0].timestamp,O=c[c.length-1].timestamp,q=c.length,C=s;l=[],v=0;let H=I++;try{let S=JSON.stringify(c),N=await J(S),j=`${r}/v1/replay/chunks?session_id=${encodeURIComponent(C)}&seq=${H}&start_ts=${encodeURIComponent(new Date(G).toISOString())}&end_ts=${encodeURIComponent(new Date(O).toISOString())}&event_count=${q}`;await fetch(j,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/gzip","Content-Encoding":"gzip"},body:N,keepalive:!0});}catch(S){e.onError?.(S);}m(r,a,{session_id:C,last_url:typeof location<"u"?location.href:null,last_activity_at:new Date(O).toISOString(),has_error:y||void 0},e.onError);},h=()=>{R();try{b?.();}catch(n){e.onError?.(n);}p.newSession(),s=p.getSessionId(),I=0,y=false,f=Date.now(),w=Date.now(),_(),E();},E=()=>{b=i({emit:n=>{if(u)return;n.type===3&&M.has(n.data?.source??-1)||(f=Date.now()),l.push(n),v+=256,v>=A&&d();},checkoutEveryNms:6e4,maskAllInputs:e.maskAllInputs??true,blockSelector:e.blockSelector??"[data-gl-block]",maskTextSelector:e.maskTextSelector??"[data-gl-mask]",sampling:{mousemove:50,mouseInteraction:true,scroll:150,input:"last"}});},P=setInterval(()=>{globalThis.__gl_replay_has_error__&&(y=true);},1e3),$=()=>{if(!u){u=true,clearInterval(z),clearInterval(U),clearInterval(P),document?.removeEventListener("visibilitychange",T),typeof window<"u"&&window.removeEventListener("beforeunload",B);try{b?.();}catch(n){e.onError?.(n);}R(),g=null;}};_(),E();let z=setInterval(()=>{d();},L),U=setInterval(()=>{if(u)return;let n=Date.now();if(n-f>x){h();return}if(n-w>k){h();return}},1e4),T=()=>{if(!u){if(document?.visibilityState==="hidden")d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);else if(document?.visibilityState==="visible"){let n=Date.now();n-f>x||n-w>k?h():f=n;}}};document.addEventListener("visibilitychange",T);let B=()=>{d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);};typeof window<"u"&&window.addEventListener("beforeunload",B);let D={get sessionId(){return s},flush:()=>d(true),stop:$};return g=D,D}async function m(t,e,o,i){try{await fetch(`${t}/v1/replay/sessions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});}catch(r){i?.(r);}}async function J(t){if(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u")return t;let o=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip")),i=await new Response(o).arrayBuffer();return new Blob([i],{type:"application/gzip"})}async function V(){try{let t=await import('rrweb');return t.record??t.default?.record??null}catch{return null}}exports.startReplay=F;
package/dist/replay.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.cjs';
1
+ import { G as GoodLogs } from './client-CaWt4mri.cjs';
2
2
 
3
3
  /**
4
4
  * Session Replay (rrweb) — optional, tree-split.
package/dist/replay.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-CkECCGvR.js';
1
+ import { G as GoodLogs } from './client-CaWt4mri.js';
2
2
 
3
3
  /**
4
4
  * Session Replay (rrweb) — optional, tree-split.
package/dist/replay.js CHANGED
@@ -1 +1 @@
1
- var O=new Set([1,3,6]);function j(t){return t.every(e=>{if(e.type!==3)return false;let o=e.data?.source;return o!==void 0&&O.has(o)})}var w=null;async function V(t,e={}){if(typeof document>"u")return null;if(w)return w;let o=e.sampleRate??1;if(o<1&&Math.random()>o)return null;let i=e.rrwebRecord??await J();if(!i)return null;let r=t.endpoint,a=t.apiKey,p=t,C=e.flushIntervalMs??5e3,M=e.flushBytes??5e5,S=e.sessionTimeoutMs??1800*1e3,L=e.maxSessionMs??3600*1e3,s=p.sessionId,l=[],v=0,x=0,g=false,u=false,f=Date.now(),k=Date.now(),y=null,I=()=>{m(r,a,{session_id:s,distinct_id:p.getDistinctId(),start_url:typeof location<"u"?location.href:null,last_url:typeof location<"u"?location.href:null},e.onError);},R=()=>{d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);},d=async(n=false)=>{if(l.length===0)return;if(!n&&j(l)){l=[],v=0;return}let c=l,U=c[0].timestamp,D=c[c.length-1].timestamp,G=c.length;l=[],v=0;let q=x++;try{let h=JSON.stringify(c),H=await K(h),N=`${r}/v1/replay/chunks?session_id=${encodeURIComponent(s)}&seq=${q}&start_ts=${encodeURIComponent(new Date(U).toISOString())}&end_ts=${encodeURIComponent(new Date(D).toISOString())}&event_count=${G}`;await fetch(N,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/gzip","Content-Encoding":"gzip"},body:H,keepalive:!0});}catch(h){e.onError?.(h);}m(r,a,{session_id:s,last_url:typeof location<"u"?location.href:null,last_activity_at:new Date(D).toISOString(),has_error:g||void 0},e.onError);},b=()=>{R();try{y?.();}catch(n){e.onError?.(n);}p.newSession(),s=p.getSessionId(),x=0,g=false,f=Date.now(),k=Date.now(),I(),_();},_=()=>{y=i({emit:n=>{if(u)return;n.type===3&&O.has(n.data?.source??-1)||(f=Date.now()),l.push(n),v+=256,v>=M&&d();},checkoutEveryNms:6e4,maskAllInputs:e.maskAllInputs??true,blockSelector:e.blockSelector??"[data-gl-block]",maskTextSelector:e.maskTextSelector??"[data-gl-mask]",sampling:{mousemove:50,mouseInteraction:true,scroll:150,input:"last"}});},A=setInterval(()=>{globalThis.__gl_replay_has_error__&&(g=true);},1e3),P=()=>{if(!u){u=true,clearInterval($),clearInterval(z),clearInterval(A),document?.removeEventListener("visibilitychange",E),typeof window<"u"&&window.removeEventListener("beforeunload",T);try{y?.();}catch(n){e.onError?.(n);}R(),w=null;}};I(),_();let $=setInterval(()=>{d();},C),z=setInterval(()=>{if(u)return;let n=Date.now();if(n-f>S){b();return}if(n-k>L){b();return}},1e4),E=()=>{u||(document?.visibilityState==="hidden"?(d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError)):document?.visibilityState==="visible"&&(Date.now()-f>S?b():f=Date.now()));};document.addEventListener("visibilitychange",E);let T=()=>{d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);};typeof window<"u"&&window.addEventListener("beforeunload",T);let B={get sessionId(){return s},flush:()=>d(true),stop:P};return w=B,B}async function m(t,e,o,i){try{await fetch(`${t}/v1/replay/sessions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});}catch(r){i?.(r);}}async function K(t){if(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u")return t;let o=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip")),i=await new Response(o).arrayBuffer();return new Blob([i],{type:"application/gzip"})}async function J(){try{let t=await import('rrweb');return t.record??t.default?.record??null}catch{return null}}export{V as startReplay};
1
+ var M=new Set([1,3,6]);function K(t){return t.every(e=>{if(e.type!==3)return false;let o=e.data?.source;return o!==void 0&&M.has(o)})}var g=null;async function F(t,e={}){if(typeof document>"u")return null;if(g)return g;let o=e.sampleRate??1;if(o<1&&Math.random()>o)return null;let i=e.rrwebRecord??await V();if(!i)return null;let r=t.endpoint,a=t.apiKey,p=t,L=e.flushIntervalMs??5e3,A=e.flushBytes??5e5,x=e.sessionTimeoutMs??1800*1e3,k=e.maxSessionMs??3600*1e3,s=p.sessionId,l=[],v=0,I=0,y=false,u=false,f=Date.now(),w=Date.now(),b=null,_=()=>{m(r,a,{session_id:s,distinct_id:p.getDistinctId(),started_at:new Date(w).toISOString(),start_url:typeof location<"u"?location.href:null,last_url:typeof location<"u"?location.href:null},e.onError);},R=()=>{let n=s;d(true),m(r,a,{session_id:n,ended_at:new Date().toISOString()},e.onError);},d=async(n=false)=>{if(l.length===0)return;if(!n&&K(l)){l=[],v=0;return}let c=l,G=c[0].timestamp,O=c[c.length-1].timestamp,q=c.length,C=s;l=[],v=0;let H=I++;try{let S=JSON.stringify(c),N=await J(S),j=`${r}/v1/replay/chunks?session_id=${encodeURIComponent(C)}&seq=${H}&start_ts=${encodeURIComponent(new Date(G).toISOString())}&end_ts=${encodeURIComponent(new Date(O).toISOString())}&event_count=${q}`;await fetch(j,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/gzip","Content-Encoding":"gzip"},body:N,keepalive:!0});}catch(S){e.onError?.(S);}m(r,a,{session_id:C,last_url:typeof location<"u"?location.href:null,last_activity_at:new Date(O).toISOString(),has_error:y||void 0},e.onError);},h=()=>{R();try{b?.();}catch(n){e.onError?.(n);}p.newSession(),s=p.getSessionId(),I=0,y=false,f=Date.now(),w=Date.now(),_(),E();},E=()=>{b=i({emit:n=>{if(u)return;n.type===3&&M.has(n.data?.source??-1)||(f=Date.now()),l.push(n),v+=256,v>=A&&d();},checkoutEveryNms:6e4,maskAllInputs:e.maskAllInputs??true,blockSelector:e.blockSelector??"[data-gl-block]",maskTextSelector:e.maskTextSelector??"[data-gl-mask]",sampling:{mousemove:50,mouseInteraction:true,scroll:150,input:"last"}});},P=setInterval(()=>{globalThis.__gl_replay_has_error__&&(y=true);},1e3),$=()=>{if(!u){u=true,clearInterval(z),clearInterval(U),clearInterval(P),document?.removeEventListener("visibilitychange",T),typeof window<"u"&&window.removeEventListener("beforeunload",B);try{b?.();}catch(n){e.onError?.(n);}R(),g=null;}};_(),E();let z=setInterval(()=>{d();},L),U=setInterval(()=>{if(u)return;let n=Date.now();if(n-f>x){h();return}if(n-w>k){h();return}},1e4),T=()=>{if(!u){if(document?.visibilityState==="hidden")d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);else if(document?.visibilityState==="visible"){let n=Date.now();n-f>x||n-w>k?h():f=n;}}};document.addEventListener("visibilitychange",T);let B=()=>{d(true),m(r,a,{session_id:s,ended_at:new Date().toISOString()},e.onError);};typeof window<"u"&&window.addEventListener("beforeunload",B);let D={get sessionId(){return s},flush:()=>d(true),stop:$};return g=D,D}async function m(t,e,o,i){try{await fetch(`${t}/v1/replay/sessions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0});}catch(r){i?.(r);}}async function J(t){if(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u")return t;let o=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip")),i=await new Response(o).arrayBuffer();return new Blob([i],{type:"application/gzip"})}async function V(){try{let t=await import('rrweb');return t.record??t.default?.record??null}catch{return null}}export{F as startReplay};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aj-2000-test/goodlogs-sdk",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "GoodLogs SDK — ingest logs/events + programmatic API client for queries, alerts, AI",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",