@aj-2000-test/goodlogs-sdk 0.4.3 → 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.
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:(e,t)=>(typeof require<"u"?require:e)[t]}):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 e=i.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function y(i,e){if(e)return e;let t=B(i);return x[t]||x.eu}var G=5e3,F=50,v="0.4.3",w="gl_anon_id",k="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)})}function U(){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 M(i,e){let t={$session_id:i,$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(i,e,t,r,n){let s=M(i,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>",o=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${o}:${d}`}}}catch{}}function V(){if(typeof localStorage<"u"){let i=localStorage.getItem(w);if(i)return i;let e=b();return localStorage.setItem(w,e),e}return b()}function X(){if(typeof sessionStorage<"u"){let i=sessionStorage.getItem(k);if(i)return i;let e=b();return sessionStorage.setItem(k,e),e}return b()}function z(){let i="";for(let e=0;e<32;e++)i+=(Math.random()*16|0).toString(16);return i}function W(){let i="";for(let e=0;e<16;e++)i+=(Math.random()*16|0).toString(16);return i}function J(i,e){switch(i){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 Y(i){if(!i)return [];let e=[];for(let t of i.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(),o=n[2];e.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];e.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 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=X(),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)+`
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 ${t.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${n} chars`)));let o=K(),d={severity:e,message:s,properties:{...this.defaultContext,...D(this.sessionId,this.anonymousId,this.release,this.environment,this.userProperties),...o?{code_location:o}:{},...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=Y(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??J(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??z(),n=W(),s=t?.parent?.span_id??e?.span_id,o=Date.now(),d=new Date(o).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-o};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),o=[];this.useEnvelope?(e.length>0||t.length>0||r.length>0||n.length>0||s.length>0)&&o.push(this.sendEnvelope(e,t,r,n,s)):(e.length>0&&o.push(this.sendLogs(e)),t.length>0&&o.push(this.sendEvents(t))),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(e){for(let r=0;r<e.length;r+=500){let s=e.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(e){for(let r=0;r<e.length;r+=500){let s=e.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(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),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),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 o of t)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 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 o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=t.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(t),this.onError(o);}}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,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 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 o=r(t?.responseEnd)-r(t?.responseStart);o>0&&this.captureVital("download",o);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 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{}},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,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 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,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 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 r=e.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 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 I=R;var L=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 $(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"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:e,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(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})}},$=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 q="0.1.0";function Q(i,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};e?.token&&(r.Authorization=`Bearer ${e.token}`),fetch(`${t}/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 e=i.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(i,e){if(!i)return;let t=i[e]??i[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function Z(i){return function(t,r,n){let s=(t.method??"GET").toUpperCase(),o=t.originalUrl??t.url??"",d=C(N(t.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=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 ee(i){return function(t,r,n){t.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();}),t.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 te(i){return {intercept(e,t){let r=e.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=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 ne(i){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{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.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)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[r]=true);}var H=globalThis.URL;function E(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function re(...i){let e=i[0],t=i[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 o=e;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 se(i,e,t){let r=i[0]&&typeof i[0]=="object"&&!E(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!E(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(e in r.headers)&&!(e.toLowerCase()in r.headers)&&(r.headers[e]=t));}function oe(i,e){let t=e?.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}=re(...a);if(!c||l(t))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});se(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=Z;exports.goodlogsFastify=ee;exports.goodlogsNestInterceptor=te;exports.instrumentNodeHttp=oe;exports.instrumentNodeProcess=ne;exports.parseTraceparent=C;exports.resolveEndpoint=y;exports.resolveRegion=B;exports.sendTelemetry=Q;
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.js CHANGED
@@ -1,7 +1,7 @@
1
- var S=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):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 e=i.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function y(i,e){if(e)return e;let t=B(i);return x[t]||x.eu}var G=5e3,F=50,v="0.4.3",w="gl_anon_id",k="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)})}function U(){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 M(i,e){let t={$session_id:i,$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(i,e,t,r,n){let s=M(i,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>",o=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${o}:${d}`}}}catch{}}function V(){if(typeof localStorage<"u"){let i=localStorage.getItem(w);if(i)return i;let e=b();return localStorage.setItem(w,e),e}return b()}function X(){if(typeof sessionStorage<"u"){let i=sessionStorage.getItem(k);if(i)return i;let e=b();return sessionStorage.setItem(k,e),e}return b()}function z(){let i="";for(let e=0;e<32;e++)i+=(Math.random()*16|0).toString(16);return i}function W(){let i="";for(let e=0;e<16;e++)i+=(Math.random()*16|0).toString(16);return i}function J(i,e){switch(i){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 Y(i){if(!i)return [];let e=[];for(let t of i.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(),o=n[2];e.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];e.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 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=X(),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)+`
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 ${t.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${n} chars`)));let o=K(),d={severity:e,message:s,properties:{...this.defaultContext,...D(this.sessionId,this.anonymousId,this.release,this.environment,this.userProperties),...o?{code_location:o}:{},...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=Y(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??J(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??z(),n=W(),s=t?.parent?.span_id??e?.span_id,o=Date.now(),d=new Date(o).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-o};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),o=[];this.useEnvelope?(e.length>0||t.length>0||r.length>0||n.length>0||s.length>0)&&o.push(this.sendEnvelope(e,t,r,n,s)):(e.length>0&&o.push(this.sendLogs(e)),t.length>0&&o.push(this.sendEvents(t))),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(e){for(let r=0;r<e.length;r+=500){let s=e.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(e){for(let r=0;r<e.length;r+=500){let s=e.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(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),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),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 o of t)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 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 o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=t.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(t),this.onError(o);}}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,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 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 o=r(t?.responseEnd)-r(t?.responseStart);o>0&&this.captureVital("download",o);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 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{}},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,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 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,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 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 r=e.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 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 I=R;var L=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 $(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"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:e,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(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})}},$=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 q="0.1.0";function Q(i,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};e?.token&&(r.Authorization=`Bearer ${e.token}`),fetch(`${t}/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 e=i.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(i,e){if(!i)return;let t=i[e]??i[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function Z(i){return function(t,r,n){let s=(t.method??"GET").toUpperCase(),o=t.originalUrl??t.url??"",d=C(N(t.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=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 ee(i){return function(t,r,n){t.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();}),t.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 te(i){return {intercept(e,t){let r=e.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=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 ne(i){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{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.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)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[r]=true);}var H=globalThis.URL;function E(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function re(...i){let e=i[0],t=i[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 o=e;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 se(i,e,t){let r=i[0]&&typeof i[0]=="object"&&!E(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!E(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(e in r.headers)&&!(e.toLowerCase()in r.headers)&&(r.headers[e]=t));}function oe(i,e){let t=e?.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}=re(...a);if(!c||l(t))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});se(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,Z as goodlogsExpress,ee as goodlogsFastify,te as goodlogsNestInterceptor,oe as instrumentNodeHttp,ne as instrumentNodeProcess,C as parseTraceparent,y as resolveEndpoint,B as resolveRegion,Q 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aj-2000-test/goodlogs-sdk",
3
- "version": "0.4.3",
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",