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

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/bin/goodlogs.cjs CHANGED
@@ -18,13 +18,16 @@ const fs = require("fs");
18
18
  const path = require("path");
19
19
 
20
20
  function parseArgs(argv) {
21
- const out = { _: [], release: null, apiKey: null, endpoint: "https://api.goodlogs.io", verbose: false };
21
+ const out = { _: [], release: null, apiKey: null, endpoint: "https://api.goodlogs.io", verbose: false, deleteAfter: false, dryRun: false, concurrency: 3 };
22
22
  for (let i = 2; i < argv.length; i++) {
23
23
  const a = argv[i];
24
24
  if (a === "--release") out.release = argv[++i];
25
25
  else if (a === "--api-key") out.apiKey = argv[++i];
26
26
  else if (a === "--endpoint") out.endpoint = argv[++i];
27
27
  else if (a === "-v" || a === "--verbose") out.verbose = true;
28
+ else if (a === "--delete-after") out.deleteAfter = true;
29
+ else if (a === "--dry-run") out.dryRun = true;
30
+ else if (a === "--concurrency") out.concurrency = parseInt(argv[++i]) || 3;
28
31
  else if (a === "--help" || a === "-h") { printHelp(); process.exit(0); }
29
32
  else out._.push(a);
30
33
  }
@@ -36,15 +39,31 @@ function printHelp() {
36
39
  "goodlogs — release helpers",
37
40
  "",
38
41
  "Usage:",
39
- " goodlogs upload-sourcemaps --release <name> --api-key <gl_sk_...> [--endpoint URL] <path>...",
42
+ " goodlogs upload-sourcemaps [options] <path>...",
40
43
  "",
41
- " --release Release identifier (e.g. v1.2.3 or commit SHA)",
42
- " --api-key Secret API key with 'ingest' scope",
43
- " --endpoint API endpoint (default https://api.goodlogs.io)",
44
- " -v Verbose output",
45
- " -h Show help",
44
+ "Options:",
45
+ " --release <name> Release identifier (e.g. v1.2.3, commit SHA)",
46
+ " Auto-detected from: git HEAD, package.json version",
47
+ " --api-key <key> Secret API key with 'ingest' scope",
48
+ " --endpoint <url> API endpoint (default https://api.goodlogs.io)",
49
+ " --delete-after Remove .map files after successful upload",
50
+ " --dry-run List files without uploading",
51
+ " --concurrency <n> Parallel uploads (default 3)",
52
+ " -v Verbose output",
53
+ " -h Show help",
46
54
  "",
47
- "Env: GOODLOGS_API_KEY, GOODLOGS_ENDPOINT, GOODLOGS_RELEASE override CLI flags.",
55
+ "Env vars: GOODLOGS_API_KEY, GOODLOGS_ENDPOINT, GOODLOGS_RELEASE",
56
+ "",
57
+ "Auto-detect (when no path given):",
58
+ " Next.js → .next/static/",
59
+ " Vite → dist/assets/",
60
+ " Webpack → dist/",
61
+ " Remix → build/client/",
62
+ "",
63
+ "Examples:",
64
+ " goodlogs upload-sourcemaps --release v1.2.3 .next/static/",
65
+ " goodlogs upload-sourcemaps --delete-after # auto-detect framework + release",
66
+ " GOODLOGS_API_KEY=gl_sk_... goodlogs upload-sourcemaps .",
48
67
  "",
49
68
  ].join("\n"));
50
69
  }
@@ -170,7 +170,7 @@ declare class GoodLogs {
170
170
  private buildErrorEntry;
171
171
  /** Send a Web Vitals sample. Routed as type:vital when useEnvelope=true;
172
172
  * falls back to a tracked event in legacy mode. */
173
- captureVital(metric: "lcp" | "inp" | "cls" | "fcp" | "ttfb" | "tbt" | "longtask", value_ms: number, extra?: {
173
+ captureVital(metric: "lcp" | "inp" | "cls" | "fcp" | "ttfb" | "tbt" | "longtask" | "dns" | "tcp" | "download" | "dom_processing" | "page_load", value_ms: number, extra?: {
174
174
  route?: string;
175
175
  rating?: "good" | "needs-improvement" | "poor";
176
176
  attributes?: Record<string, unknown>;
@@ -170,7 +170,7 @@ declare class GoodLogs {
170
170
  private buildErrorEntry;
171
171
  /** Send a Web Vitals sample. Routed as type:vital when useEnvelope=true;
172
172
  * falls back to a tracked event in legacy mode. */
173
- captureVital(metric: "lcp" | "inp" | "cls" | "fcp" | "ttfb" | "tbt" | "longtask", value_ms: number, extra?: {
173
+ captureVital(metric: "lcp" | "inp" | "cls" | "fcp" | "ttfb" | "tbt" | "longtask" | "dns" | "tcp" | "download" | "dom_processing" | "page_load", value_ms: number, extra?: {
174
174
  route?: string;
175
175
  rating?: "good" | "needs-improvement" | "poor";
176
176
  attributes?: Record<string, unknown>;
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- 'use strict';var S=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var I={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 t=o.split("_");return t.length>=4&&t[0]==="gl"?t[2]:"eu"}function y(o,t){if(t)return t;let e=B(o);return I[e]||I.eu}var G=5e3,F=50,v="0.4.0",w="gl_anon_id",_="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let t=Math.random()*16|0;return (o==="x"?t:t&3|8).toString(16)})}function M(){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 U(o,t){let e={$session_id:o,$distinct_id:t,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(e.$url=location.href,e.$path=location.pathname),e}function D(){if(!(typeof document<"u"))try{let t=new Error().stack?.split(`
2
- `);if(!t)return;for(let e=3;e<Math.min(t.length,8);e++){let n=t[e]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let r=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(r){let s=r[1]||"<anonymous>",i=r[2]?.replace(/^.*[/\\]/,"")??"",d=r[3];return `${s}@${i}:${d}`}}}catch{}}function K(){if(typeof localStorage<"u"){let o=localStorage.getItem(w);if(o)return o;let t=b();return localStorage.setItem(w,t),t}return b()}function X(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(_);if(o)return o;let t=b();return sessionStorage.setItem(_,t),t}return b()}function z(){let o="";for(let t=0;t<32;t++)o+=(Math.random()*16|0).toString(16);return o}function V(){let o="";for(let t=0;t<16;t++)o+=(Math.random()*16|0).toString(16);return o}function W(o,t){switch(o){case "lcp":return t<=2500?"good":t<=4e3?"needs-improvement":"poor";case "inp":return t<=200?"good":t<=500?"needs-improvement":"poor";case "cls":return t<=.1?"good":t<=.25?"needs-improvement":"poor";case "fcp":return t<=1800?"good":t<=3e3?"needs-improvement":"poor";case "ttfb":return t<=800?"good":t<=1800?"needs-improvement":"poor";default:return}}function J(o){if(!o)return [];let t=[];for(let e of o.split(`
3
- `)){let n=e.trim();if(!n||n.startsWith("Error")||n.startsWith("at Error"))continue;let r=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(n);if(r){let s=r[1]?.trim(),i=r[2];t.push({function:s&&s!=="<anonymous>"?s:void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")&&!i.startsWith("internal/")});continue}if(r=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(n),r){let s=r[1]?.trim(),i=r[2];t.push({function:s||void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")});}}return t}var R=class R{constructor(t){this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint).replace(/\/+$/,""),this.flushInterval=t.flushInterval??G,this.batchSize=t.batchSize??F,this.defaultContext=t.defaultContext??{},this.onError=t.onError??(()=>{}),this.disabled=t.disabled??false,this.telemetry=t.telemetry??true,this.useEnvelope=t.useEnvelope??false,this.autoFetch=t.autoFetch??(this.useEnvelope&&t.autocapture!==false),this.anonymousId=K(),this.sessionId=X(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),t.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(t,e,n){if(this.disabled)return;let r=65536,s=e;e.length>r&&(s=e.slice(0,r-100)+`
1
+ 'use strict';var S=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var x={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(i){let t=i.split("_");return t.length>=4&&t[0]==="gl"?t[2]:"eu"}function y(i,t){if(t)return t;let e=B(i);return x[e]||x.eu}var G=5e3,F=50,v="0.4.2",w="gl_anon_id",E="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return (i==="x"?t:t&3|8).toString(16)})}function M(){let i={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(i.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(i.$language=navigator.language??""),typeof location<"u"&&(i.$url=location.href,i.$path=location.pathname,i.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(i.$referrer=document.referrer),document.title&&(i.$title=document.title))),i}function U(i,t){let e={$session_id:i,$distinct_id:t,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(e.$url=location.href,e.$path=location.pathname),e}function D(){if(!(typeof document<"u"))try{let t=new Error().stack?.split(`
2
+ `);if(!t)return;for(let e=3;e<Math.min(t.length,8);e++){let r=t[e]?.trim();if(!r||r.includes("goodlogs")&&(r.includes("client.")||r.includes("index.")))continue;let n=r.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(n){let s=n[1]||"<anonymous>",o=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${o}:${d}`}}}catch{}}function K(){if(typeof localStorage<"u"){let i=localStorage.getItem(w);if(i)return i;let t=b();return localStorage.setItem(w,t),t}return b()}function V(){if(typeof sessionStorage<"u"){let i=sessionStorage.getItem(E);if(i)return i;let t=b();return sessionStorage.setItem(E,t),t}return b()}function X(){let i="";for(let t=0;t<32;t++)i+=(Math.random()*16|0).toString(16);return i}function z(){let i="";for(let t=0;t<16;t++)i+=(Math.random()*16|0).toString(16);return i}function W(i,t){switch(i){case "lcp":return t<=2500?"good":t<=4e3?"needs-improvement":"poor";case "inp":return t<=200?"good":t<=500?"needs-improvement":"poor";case "cls":return t<=.1?"good":t<=.25?"needs-improvement":"poor";case "fcp":return t<=1800?"good":t<=3e3?"needs-improvement":"poor";case "ttfb":return t<=800?"good":t<=1800?"needs-improvement":"poor";case "dns":return t<=20?"good":t<=100?"needs-improvement":"poor";case "tcp":return t<=50?"good":t<=200?"needs-improvement":"poor";case "download":return t<=100?"good":t<=500?"needs-improvement":"poor";case "dom_processing":return t<=500?"good":t<=1500?"needs-improvement":"poor";case "page_load":return t<=1e3?"good":t<=3e3?"needs-improvement":"poor";default:return}}function J(i){if(!i)return [];let t=[];for(let e of i.split(`
3
+ `)){let r=e.trim();if(!r||r.startsWith("Error")||r.startsWith("at Error"))continue;let n=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(r);if(n){let s=n[1]?.trim(),o=n[2];t.push({function:s&&s!=="<anonymous>"?s:void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")&&!o.startsWith("internal/")});continue}if(n=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(r),n){let s=n[1]?.trim(),o=n[2];t.push({function:s||void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")});}}return t}var R=class R{constructor(t){this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint).replace(/\/+$/,""),this.flushInterval=t.flushInterval??G,this.batchSize=t.batchSize??F,this.defaultContext=t.defaultContext??{},this.onError=t.onError??(()=>{}),this.disabled=t.disabled??false,this.telemetry=t.telemetry??true,this.useEnvelope=t.useEnvelope??false,this.autoFetch=t.autoFetch??(this.useEnvelope&&t.autocapture!==false),this.anonymousId=K(),this.sessionId=V(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),t.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(t,e,r){if(this.disabled)return;let n=65536,s=e;e.length>n&&(s=e.slice(0,n-100)+`
4
4
 
5
- [truncated \u2014 original ${e.length} chars, limit ${r}]`,this.onError(new Error(`Log message truncated from ${e.length} to ${r} chars`)));let i=D(),d={severity:t,message:s,properties:{...this.defaultContext,...U(this.sessionId,this.anonymousId),...i?{code_location:i}:{},...n},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(t,e){this.log("debug",t,e);}info(t,e){this.log("info",t,e);}warn(t,e){this.log("warn",t,e);}error(t,e){this.log("error",t,e);}fatal(t,e){this.log("fatal",t,e);}identify(t){this.anonymousId=t,typeof localStorage<"u"&&localStorage.setItem(w,t);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId);}setSessionId(t){this.sessionId=t,typeof sessionStorage<"u"&&sessionStorage.setItem(_,t);}track(t,e){if(this.disabled)return;let{distinctId:n,...r}=e??{},s={event:t,distinctId:n??this.anonymousId,properties:{...M(),...r,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(t){if(this.disabled)return;let e={ts:t.ts??new Date().toISOString(),...t};this.breadcrumbBuffer.push(e),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(t,e){if(this.disabled)return;let n=this.buildErrorEntry(t,e);this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(n.message,{exception_type:n.exception_type,frames:n.frames});}captureMessage(t,e){if(this.disabled)return;let n={level:e?.level??"info",message:t,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(t);}buildErrorEntry(t,e){let n,r,s=[];if(t instanceof Error)n=t.name,r=t.message,s=J(t.stack);else if(typeof t=="string")r=t;else try{r=JSON.stringify(t);}catch{r=String(t);}return {level:e?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:n,message:r,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id}}captureVital(t,e,n){if(this.disabled||!Number.isFinite(e)||e<0)return;let r=n?.rating??W(t,e),s={metric:t,value_ms:t==="cls"?e:Math.round(e),rating:r,route:n?.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:n?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:t.toUpperCase(),$value_ms:s.value_ms,$rating:r}});}startTransaction(t){return this.makeSpan(void 0,t)}startSpan(t){return this.makeSpan(void 0,t)}makeSpan(t,e){let n=e?.trace_id??e?.parent?.trace_id??t?.trace_id??z(),r=V(),s=e?.parent?.span_id??t?.span_id,i=Date.now(),d=new Date(i).toISOString(),a={...e?.attributes??{}},c="unset",u=[],h=false,f=this,g={span_id:r,trace_id:n,setAttribute(p,l){a[p]=l;},setStatus(p){c=p;},addEvent(p,l){u.push({ts:new Date().toISOString(),name:p,attributes:l});},startChild(p){return f.makeSpan(g,p)},finish(){if(h)return;h=true;let p=Date.now(),l={span_id:r,trace_id:n,parent_span_id:s,name:e?.name,op:e?.op,status:c==="unset"?"ok":c,kind:e?.kind,attributes:a,events:u,start_time:d,end_time:new Date(p).toISOString(),timestamp:d,duration_ms:p-i};f.useEnvelope&&(f.spanBuffer.push(l),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),n=this.errorBuffer.splice(0),r=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),i=[];this.useEnvelope?(t.length>0||e.length>0||n.length>0||r.length>0||s.length>0)&&i.push(this.sendEnvelope(t,e,n,r,s)):(t.length>0&&i.push(this.sendLogs(t)),e.length>0&&i.push(this.sendEvents(e))),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(t){for(let n=0;n<t.length;n+=500){let s=t.slice(n,n+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(t){for(let n=0;n<t.length;n+=500){let s=t.slice(n,n+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(t,e,n,r,s){let d=[...t.map(a=>({kind:"log",entry:a})),...e.map(a=>({kind:"event",entry:a})),...n.map(a=>({kind:"error",entry:a})),...r.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let c=d.slice(a,a+1e3),u=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),h=c.map(g=>{if(g.kind==="log"){let l=g.entry;return JSON.stringify({type:"log",severity:l.severity,message:l.message,properties:l.properties,timestamp:l.timestamp})}if(g.kind==="event"){let l=g.entry;return JSON.stringify({type:"event",event:l.event,distinctId:l.distinctId,properties:l.properties,timestamp:l.timestamp})}if(g.kind==="error"){let l=g.entry;return JSON.stringify({type:"error",...l})}if(g.kind==="vital"){let l=g.entry;return JSON.stringify({type:"vital",...l})}let p=g.entry;return JSON.stringify({type:"span",...p})}),f=[u,...h].join(`
6
- `);await this.postEnvelopeWithRetry(f,c);}}async postEnvelopeWithRetry(t,e,n=0){try{let r=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:t});if(r.status===429||r.status===503){if(n<4){let s=Math.min(1e3*Math.pow(2,n),8e3),i=Math.random()*500;return await new Promise(d=>setTimeout(d,s+i)),this.postEnvelopeWithRetry(t,e,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!r.ok){let s=await r.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${r.status}: ${s}`)),r.status>=500&&n===0)for(let i of e)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(r){if(n===0)for(let s of e)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(r instanceof Error?r:new Error(String(r)));}}async postWithRetry(t,e,n,r=0){try{let s=await fetch(`${this.endpoint}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:e})});if(s.status===429||s.status===503){if(r<4){let d=Math.min(1e3*Math.pow(2,r),8e3),a=Math.random()*500;return await new Promise(c=>setTimeout(c,d+a)),this.postWithRetry(t,e,n,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} 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&&r===0&&n(e);return}let i=await s.json().catch(()=>null);if(i&&i.rejected&&i.rejected>0){let d=e.slice(i.accepted??0);d.length>0&&n(d);}}catch(s){let i=s instanceof Error?s:new Error(String(s));r===0&&n(e),this.onError(i);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let t=this.timer;typeof t?.unref=="function"&&t.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let t=(e,n)=>{if(this.useEnvelope)this.captureVital(e.toLowerCase(),n);else {let r=e==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:e,[r]:e==="CLS"?n:Math.round(n)}});}};try{new PerformanceObserver(e=>{let n=e.getEntries()[0];n&&t("FCP",n.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let n=e.getEntries(),r=n[n.length-1];r&&t("LCP",r.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(n=>{for(let r of n.getEntries())r.hadRecentInput||(e+=r.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{e>0&&t("CLS",Math.round(e*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n();});}}catch{}try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&t("TTFB",e.responseStart);}}catch{}try{new PerformanceObserver(e=>{for(let n of e.getEntries()){let r=n.duration;r>0&&t("INP",r);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let t=(e="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,e));};if(typeof history<"u"){let e=history.pushState,n=history.replaceState;history.pushState=function(...r){e.apply(this,r),t("push");},history.replaceState=function(...r){n.apply(this,r),t("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>t("popstate"));}startNavTransaction(t,e){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:t,attributes:{"navigation.type":e,"http.url":typeof location<"u"?location.href:t}});let n=this.navTransaction;setTimeout(()=>{this.navTransaction===n&&(n.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let t=globalThis;typeof t.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=e=>{let n=e,r=n.error??new Error(n.message??"Uncaught error");try{this.captureException(r,{tags:{source:"window.onerror"},extra:n.filename?{filename:n.filename,lineno:n.lineno,colno:n.colno}:void 0});}catch{}},this.rejectionHandler=e=>{let r=e.reason,s=r;if(!(r instanceof Error)){let i;if(typeof r=="string")i=r;else try{i=JSON.stringify(r);}catch{i=String(r);}s=new Error(i);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},t.addEventListener("error",this.errorHandler),t.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let t=globalThis;typeof t.removeEventListener=="function"&&(this.errorHandler&&(t.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(t.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let t=globalThis;if(this.originalFetch)return;this.originalFetch=t.fetch;let e=t.fetch.bind(globalThis),n=this;t.fetch=function(s,i){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let h=s;d=h.url??"",a=h.method??a;}let c=i??{};if(c.method?a=String(c.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(n.endpoint))return e(s,c);let u=n.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:n.navTransaction??void 0});try{let h=`00-${u.trace_id}-${u.span_id}-01`,f={...c},g=f.headers??{};return f.headers={...g,traceparent:h},e(s,f).then(p=>{let l=p;return typeof l.status=="number"&&u.setAttribute("http.status_code",l.status),u.setStatus(l.ok===!1?"error":"ok"),u.finish(),p}).catch(p=>{throw u.setStatus("error"),u.setAttribute("error.message",p instanceof Error?p.message:String(p)),u.finish(),p})}catch(h){throw u.setStatus("error"),u.finish(),h}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let e=globalThis.XMLHttpRequest;if(!e||!e.prototype)return;let n=Symbol.for("goodlogs.xhr.patched"),r=e.prototype;if(r[n]){this.xhrPatched=true;return}let s=r.open,i=r.setRequestHeader,d=r.send,a=this;r.open=function(u,h,...f){return this.__gl_method=typeof u=="string"?u.toUpperCase():"GET",this.__gl_url=typeof h=="string"?h:String(h??""),this.__gl_headers_set=false,s.apply(this,[u,h,...f])},r.setRequestHeader=function(u,h){return this.__gl_headers_set=true,i.apply(this,[u,h])},r.send=function(u){let h=this.__gl_url||"",f=this.__gl_method||"GET";if(h.startsWith(a.endpoint))return d.apply(this,[u]);let g=a.startSpan({op:"http.client",name:`${f} ${h}`,attributes:{"http.method":f,"http.url":h},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;i.apply(this,["traceparent",m]);}catch{}let p=(m,E,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(E?"ok":"error"),g.finish();},l=this.addEventListener;return typeof l=="function"?(l.call(this,"load",()=>{let m=Number(this.status||0);p(m,m>0&&m<500);}),l.call(this,"error",()=>p(0,false,"network error")),l.call(this,"abort",()=>p(0,false,"aborted")),l.call(this,"timeout",()=>p(0,false,"timeout"))):p(0,true),d.apply(this,[u])},r[n]=true,r.__gl_orig_open=s,r.__gl_orig_set_header=i,r.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let e=globalThis.XMLHttpRequest?.prototype;if(!e)return;let n=Symbol.for("goodlogs.xhr.patched");e.__gl_orig_open&&(e.open=e.__gl_orig_open),e.__gl_orig_set_header&&(e.setRequestHeader=e.__gl_orig_set_header),e.__gl_orig_send&&(e.send=e.__gl_orig_send),delete e.__gl_orig_open,delete e.__gl_orig_set_header,delete e.__gl_orig_send,delete e[n],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=t=>{let n=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let r=n.getAttribute?.("data-gl-event"),s=n.tagName?.toLowerCase()??"",i=(n.textContent??"").trim().slice(0,50),d=n.getAttribute?.("href")??void 0,a=(n.className??"").toString().slice(0,80);this.track(r||"$click",{properties:{$element_tag:s,$element_text:i||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};t.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(r=>({severity:r.severity,message:r.message,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{}),e.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(r=>({event:r.event,distinctId:r.distinctId,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(t,e,n){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:t,level:e,metadata:{...n,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var C=R;var $=class{constructor(t){if(!t.apiKey)throw new Error("apiKey is required");if(!t.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint),this.timeout=t.timeout??3e4,this.alerts=new L(this),this.slos=new P(this),this.ai=new A(this);}async _request(t,e,n){let r=`${this.endpoint}${e}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=new AbortController,d=setTimeout(()=>i.abort(),this.timeout);try{let a=await fetch(r,{method:t,headers:s,body:n?JSON.stringify(n):void 0,signal:i.signal});if(!a.ok){let c=await a.json().catch(()=>({})),u=c?.error?.message??`API error ${a.status}`;throw new T(a.status,u,c?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(t){return this._request("GET",t)}_post(t,e){return this._request("POST",t,e)}_put(t,e){return this._request("PUT",t,e)}_delete(t){return this._request("DELETE",t)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(t){return this._post("/v1/gql/query",{q:t})}gqlBatch(t){return this._post("/v1/gql",{queries:t})}gqlAutocomplete(t,e){let n=`/v1/gql/autocomplete?q=${encodeURIComponent(t)}`;return e!==void 0&&(n+=`&cursor=${e}`),this._get(n)}nl2gql(t,e){return this._post("/v1/gql/nl",{prompt:t,mode:e})}},L=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/alerts")}create(t){return this.client._post("/v1/alerts",t)}update(t,e){return this.client._put(`/v1/alerts/${t}`,e)}delete(t){return this.client._delete(`/v1/alerts/${t}`)}mute(t,e){return this.client._post(`/v1/alerts/${t}/mute`,{minutes:e})}},P=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/slos")}create(t){return this.client._post("/v1/slos",t)}update(t,e){return this.client._put(`/v1/slos/${t}`,e)}delete(t){return this.client._delete(`/v1/slos/${t}`)}},A=class{constructor(t){this.client=t;}chat(t,e){return this.client._post("/v1/ai/chat",{message:t,session_id:e})}},T=class extends Error{constructor(e,n,r){super(n);this.status=e;this.code=r;this.name="GoodLogsApiError";}};var q="0.1.0";function Y(o,t){let e=y(t?.apiKey??"",t?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":q};t?.token&&(n.Authorization=`Bearer ${t.token}`),fetch(`${e}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:o.source,event:o.event,level:o.level??"info",metadata:{...o.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function x(o){if(!o)return null;let t=o.trim().split("-");if(t.length!==4)return null;let[e,n,r,s]=t;return e.length!==2||n.length!==32||r.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(n)||!/^[0-9a-f]+$/.test(r)?null:{trace_id:n,parent_span_id:r}}function N(o,t){if(!o)return;let e=o[t]??o[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function Q(o){return function(e,n,r){let s=(e.method??"GET").toUpperCase(),i=e.originalUrl??e.url??"",d=x(N(e.headers,"traceparent")),a=o.startTransaction({op:"http.server",name:`${s} ${i}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":i}}),c=false,u=()=>{if(c)return;c=true;let h=e.route?.path;h&&a.setAttribute("http.route",h);let f=n.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};n.on("finish",u),n.on("close",u),e.goodlogs={span:a},r();}}function Z(o){return function(e,n,r){e.addHook("onRequest",(s,i,d)=>{let a=(s.method??"GET").toUpperCase(),c=s.url??"",u=x(N(s.headers,"traceparent")),h=o.startTransaction({op:"http.server",name:`${a} ${c}`,trace_id:u?.trace_id,attributes:{"http.method":a,"http.url":c}});s.__goodlogsSpan=h,d();}),e.addHook("onResponse",(s,i,d)=>{let a=s.__goodlogsSpan;if(a){let c=s.routerPath??s.routeOptions?.url;c&&a.setAttribute("http.route",c);let u=i.statusCode??i.raw?.statusCode??200;a.setAttribute("http.status_code",u),a.setStatus(u>=500?"error":"ok"),a.finish();}d();}),r();}}function tt(o){return {intercept(t,e){let n=t.switchToHttp(),r=n.getRequest(),s=n.getResponse(),i=(r.method??"GET").toUpperCase(),d=r.originalUrl??r.url??"",a=x(N(r.headers,"traceparent")),c=o.startTransaction({op:"http.server",name:`${i} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":i,"http.url":d}}),u=false,h=(g,p)=>{if(u)return;u=true;let l=r.route?.path;l&&c.setAttribute("http.route",l);let m=g??s.statusCode??200;c.setAttribute("http.status_code",m),c.setStatus(p||m>=500?"error":"ok"),c.finish();};s.on("finish",()=>h()),s.on("close",()=>h());let f=e.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:p=>{c.setAttribute("error.message",p instanceof Error?p.message:String(p)),h(500,true);},complete:()=>h()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function et(o){let t=globalThis.process;if(!t||typeof t.on!="function")return;let e=t,n=Symbol.for("goodlogs.node-process.patched");e[n]||(t.on("uncaughtException",r=>{try{o.captureException(r instanceof Error?r:new Error(String(r)),{tags:{source:"uncaughtException"},level:"fatal"}),o.flush();}catch{}}),t.on("unhandledRejection",r=>{try{let s=r instanceof Error?r:new Error(typeof r=="string"?r:(()=>{try{return JSON.stringify(r)}catch{return String(r)}})());o.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),e[n]=true);}var H=globalThis.URL;function k(o){return !!H&&o instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function nt(...o){let t=o[0],e=o[1],n="GET",r="";if(typeof t=="string")r=t,e&&typeof e=="object"&&!k(e)&&(n=String(e.method??n).toUpperCase());else if(k(t))r=t.toString(),e&&typeof e=="object"&&!k(e)&&(n=String(e.method??n).toUpperCase());else if(t&&typeof t=="object"){let i=t;n=String(i.method??n).toUpperCase();let d=(i.protocol??"http:").replace(":",""),a=i.hostname??i.host??"localhost",c=i.port?`:${i.port}`:"";r=`${d}://${a}${c}${i.path??"/"}`;}return {method:n,url:r,isOurs:i=>!!i&&r.startsWith(i)}}function rt(o,t,e){let n=o[0]&&typeof o[0]=="object"&&!k(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!k(o[1])?o[1]:void 0;n&&(n.headers||(n.headers={}),!(t in n.headers)&&!(t.toLowerCase()in n.headers)&&(n.headers[t]=e));}function st(o,t){let e=t?.endpoint??o.endpoint??"",n=r=>{let s=r;if(s[j])return;s[j]=true;let i=r.request.bind(r);r.request=function(...a){let{method:c,url:u,isOurs:h}=nt(...a);if(!u||h(e))return i(...a);let f=o.startTransaction({op:"http.client",name:`${c} ${u}`,attributes:{"http.method":c,"http.url":u}});rt(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,p=(m,E)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),E?(f.setAttribute("error.message",E.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},l=i(...a);return l.on("response",m=>p(m.statusCode)),l.on("error",m=>p(void 0,m)),l.on("close",()=>p()),l};};if(typeof S=="function"){try{let r=S("http");n(r);}catch{}try{let r=S("https");n(r);}catch{}}}
7
- exports.GoodLogs=C;exports.GoodLogsApiError=T;exports.GoodLogsClient=$;exports.REGION_URLS=I;exports.goodlogsExpress=Q;exports.goodlogsFastify=Z;exports.goodlogsNestInterceptor=tt;exports.instrumentNodeHttp=st;exports.instrumentNodeProcess=et;exports.parseTraceparent=x;exports.resolveEndpoint=y;exports.resolveRegion=B;exports.sendTelemetry=Y;
5
+ [truncated \u2014 original ${e.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${e.length} to ${n} chars`)));let o=D(),d={severity:t,message:s,properties:{...this.defaultContext,...U(this.sessionId,this.anonymousId),...o?{code_location:o}:{},...r},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(t,e){this.log("debug",t,e);}info(t,e){this.log("info",t,e);}warn(t,e){this.log("warn",t,e);}error(t,e){this.log("error",t,e);}fatal(t,e){this.log("fatal",t,e);}identify(t){this.anonymousId=t,typeof localStorage<"u"&&localStorage.setItem(w,t);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}setSessionId(t){this.sessionId=t,typeof sessionStorage<"u"&&sessionStorage.setItem(E,t);}track(t,e){if(this.disabled)return;let{distinctId:r,...n}=e??{},s={event:t,distinctId:r??this.anonymousId,properties:{...M(),...n,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(t){if(this.disabled)return;let e={ts:t.ts??new Date().toISOString(),...t};this.breadcrumbBuffer.push(e),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(t,e){if(this.disabled)return;let r=this.buildErrorEntry(t,e);this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(r.message,{exception_type:r.exception_type,frames:r.frames});}captureMessage(t,e){if(this.disabled)return;let r={level:e?.level??"info",message:t,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(t);}buildErrorEntry(t,e){let r,n,s=[];if(t instanceof Error)r=t.name,n=t.message,s=J(t.stack);else if(typeof t=="string")n=t;else try{n=JSON.stringify(t);}catch{n=String(t);}return {level:e?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:r,message:n,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id}}captureVital(t,e,r){if(this.disabled||!Number.isFinite(e)||e<0)return;let n=r?.rating??W(t,e),s={metric:t,value_ms:t==="cls"?e:Math.round(e),rating:n,route:r?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:r?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:t.toUpperCase(),$value_ms:s.value_ms,$rating:n}});}startTransaction(t){return this.makeSpan(void 0,t)}startSpan(t){return this.makeSpan(void 0,t)}makeSpan(t,e){let r=e?.trace_id??e?.parent?.trace_id??t?.trace_id??X(),n=z(),s=e?.parent?.span_id??t?.span_id,o=Date.now(),d=new Date(o).toISOString(),a={...e?.attributes??{}},u="unset",c=[],l=false,f=this,g={span_id:n,trace_id:r,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){c.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(l)return;l=true;let h=Date.now(),p={span_id:n,trace_id:r,parent_span_id:s,name:e?.name,op:e?.op,status:u==="unset"?"ok":u,kind:e?.kind,attributes:a,events:c,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-o};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r=this.errorBuffer.splice(0),n=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),o=[];this.useEnvelope?(t.length>0||e.length>0||r.length>0||n.length>0||s.length>0)&&o.push(this.sendEnvelope(t,e,r,n,s)):(t.length>0&&o.push(this.sendLogs(t)),e.length>0&&o.push(this.sendEvents(e))),await Promise.all(o);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({severity:o.severity,message:o.message,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/logs",s,o=>{for(let d of o)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({event:o.event,distinctId:o.distinctId,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/events",s,o=>{for(let d of o)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(t,e,r,n,s){let d=[...t.map(a=>({kind:"log",entry:a})),...e.map(a=>({kind:"event",entry:a})),...r.map(a=>({kind:"error",entry:a})),...n.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),c=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),l=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[c,...l].join(`
6
+ `);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(t,e,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:t});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),this.postEnvelopeWithRetry(t,e,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let o of e)o.kind==="log"?this.logBuffer.push(o.entry):o.kind==="event"?this.eventBuffer.push(o.entry):o.kind==="error"?this.errorBuffer.push(o.entry):o.kind==="vital"?this.vitalBuffer.push(o.entry):this.spanBuffer.push(o.entry);}}catch(n){if(r===0)for(let s of e)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(t,e,r,n=0){try{let s=await fetch(`${this.endpoint}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:e})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(t,e,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(e);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=e.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(e),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let t=this.timer;typeof t?.unref=="function"&&t.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let t=(e,r)=>{if(this.useEnvelope)this.captureVital(e.toLowerCase(),r);else {let n=e==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:e,[n]:e==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(e=>{let r=e.getEntries()[0];r&&t("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let r=e.getEntries(),n=r[r.length-1];n&&t("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{e>0&&t("CLS",Math.round(e*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&t("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,o=s(n.domainLookupEnd)-s(n.domainLookupStart);o>0&&this.captureVital("dns",o);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&t("TTFB",e.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(e?.domainLookupEnd)-r(e?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(e?.connectEnd)-r(e?.connectStart);s>0&&this.captureVital("tcp",s);let o=r(e?.responseEnd)-r(e?.responseStart);o>0&&this.captureVital("download",o);let d=r(e?.domComplete)-r(e?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(e?.loadEventEnd)-r(e?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r.duration;n>0&&t("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let t=(e="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,e));};if(typeof history<"u"){let e=history.pushState,r=history.replaceState;history.pushState=function(...n){e.apply(this,n),t("push");},history.replaceState=function(...n){r.apply(this,n),t("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>t("popstate"));}startNavTransaction(t,e){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:t,attributes:{"navigation.type":e,"http.url":typeof location<"u"?location.href:t}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let t=globalThis;typeof t.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=e=>{let r=e,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=e=>{let n=e.reason,s=n;if(!(n instanceof Error)){let o;if(typeof n=="string")o=n;else try{o=JSON.stringify(n);}catch{o=String(n);}s=new Error(o);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},t.addEventListener("error",this.errorHandler),t.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let t=globalThis;typeof t.removeEventListener=="function"&&(this.errorHandler&&(t.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(t.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let t=globalThis;if(this.originalFetch)return;this.originalFetch=t.fetch;let e=t.fetch.bind(globalThis),r=this;t.fetch=function(s,o){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=o??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return e(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},e(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let e=globalThis.XMLHttpRequest;if(!e||!e.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=e.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,o=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,o.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;o.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=o,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let e=globalThis.XMLHttpRequest?.prototype;if(!e)return;let r=Symbol.for("goodlogs.xhr.patched");e.__gl_orig_open&&(e.open=e.__gl_orig_open),e.__gl_orig_set_header&&(e.setRequestHeader=e.__gl_orig_set_header),e.__gl_orig_send&&(e.send=e.__gl_orig_send),delete e.__gl_orig_open,delete e.__gl_orig_set_header,delete e.__gl_orig_send,delete e[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=t=>{let r=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",o=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80);this.track(n||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};t.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),e.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(t,e,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:t,level:e,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var I=R;var L=class{constructor(t){if(!t.apiKey)throw new Error("apiKey is required");if(!t.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint),this.timeout=t.timeout??3e4,this.alerts=new $(this),this.slos=new P(this),this.ai=new A(this);}async _request(t,e,r){let n=`${this.endpoint}${e}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:t,headers:s,body:r?JSON.stringify(r):void 0,signal:o.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(t){return this._request("GET",t)}_post(t,e){return this._request("POST",t,e)}_put(t,e){return this._request("PUT",t,e)}_delete(t){return this._request("DELETE",t)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(t){return this._post("/v1/gql/query",{q:t})}gqlBatch(t){return this._post("/v1/gql",{queries:t})}gqlAutocomplete(t,e){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(t)}`;return e!==void 0&&(r+=`&cursor=${e}`),this._get(r)}nl2gql(t,e){return this._post("/v1/gql/nl",{prompt:t,mode:e})}},$=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/alerts")}create(t){return this.client._post("/v1/alerts",t)}update(t,e){return this.client._put(`/v1/alerts/${t}`,e)}delete(t){return this.client._delete(`/v1/alerts/${t}`)}mute(t,e){return this.client._post(`/v1/alerts/${t}/mute`,{minutes:e})}},P=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/slos")}create(t){return this.client._post("/v1/slos",t)}update(t,e){return this.client._put(`/v1/slos/${t}`,e)}delete(t){return this.client._delete(`/v1/slos/${t}`)}},A=class{constructor(t){this.client=t;}chat(t,e){return this.client._post("/v1/ai/chat",{message:t,session_id:e})}},T=class extends Error{constructor(e,r,n){super(r);this.status=e;this.code=n;this.name="GoodLogsApiError";}};var q="0.1.0";function Y(i,t){let e=y(t?.apiKey??"",t?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};t?.token&&(r.Authorization=`Bearer ${t.token}`),fetch(`${e}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function C(i){if(!i)return null;let t=i.trim().split("-");if(t.length!==4)return null;let[e,r,n,s]=t;return e.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(i,t){if(!i)return;let e=i[t]??i[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function Q(i){return function(e,r,n){let s=(e.method??"GET").toUpperCase(),o=e.originalUrl??e.url??"",d=C(N(e.headers,"traceparent")),a=i.startTransaction({op:"http.server",name:`${s} ${o}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":o}}),u=false,c=()=>{if(u)return;u=true;let l=e.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),e.goodlogs={span:a},n();}}function Z(i){return function(e,r,n){e.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),e.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function tt(i){return {intercept(t,e){let r=t.switchToHttp(),n=r.getRequest(),s=r.getResponse(),o=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=e.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function et(i){let t=globalThis.process;if(!t||typeof t.on!="function")return;let e=t,r=Symbol.for("goodlogs.node-process.patched");e[r]||(t.on("uncaughtException",n=>{try{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.flush();}catch{}}),t.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),e[r]=true);}var H=globalThis.URL;function k(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function nt(...i){let t=i[0],e=i[1],r="GET",n="";if(typeof t=="string")n=t,e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(k(t))n=t.toString(),e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(t&&typeof t=="object"){let o=t;r=String(o.method??r).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",u=o.port?`:${o.port}`:"";n=`${d}://${a}${u}${o.path??"/"}`;}return {method:r,url:n,isOurs:o=>!!o&&n.startsWith(o)}}function rt(i,t,e){let r=i[0]&&typeof i[0]=="object"&&!k(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!k(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(t in r.headers)&&!(t.toLowerCase()in r.headers)&&(r.headers[t]=e));}function st(i,t){let e=t?.endpoint??i.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let o=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=nt(...a);if(!c||l(e))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});rt(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=o(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
7
+ exports.GoodLogs=I;exports.GoodLogsApiError=T;exports.GoodLogsClient=L;exports.REGION_URLS=x;exports.goodlogsExpress=Q;exports.goodlogsFastify=Z;exports.goodlogsNestInterceptor=tt;exports.instrumentNodeHttp=st;exports.instrumentNodeProcess=et;exports.parseTraceparent=C;exports.resolveEndpoint=y;exports.resolveRegion=B;exports.sendTelemetry=Y;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { G as GoodLogs } from './client-w3t1Yzjd.cjs';
2
- export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-w3t1Yzjd.cjs';
1
+ import { G as GoodLogs } from './client-CkECCGvR.cjs';
2
+ export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CkECCGvR.cjs';
3
3
 
4
4
  interface LogRecord {
5
5
  id: number;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { G as GoodLogs } from './client-w3t1Yzjd.js';
2
- export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-w3t1Yzjd.js';
1
+ import { G as GoodLogs } from './client-CkECCGvR.js';
2
+ export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CkECCGvR.js';
3
3
 
4
4
  interface LogRecord {
5
5
  id: number;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var S=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var I={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 t=o.split("_");return t.length>=4&&t[0]==="gl"?t[2]:"eu"}function y(o,t){if(t)return t;let e=B(o);return I[e]||I.eu}var G=5e3,F=50,v="0.4.0",w="gl_anon_id",_="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let t=Math.random()*16|0;return (o==="x"?t:t&3|8).toString(16)})}function M(){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 U(o,t){let e={$session_id:o,$distinct_id:t,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(e.$url=location.href,e.$path=location.pathname),e}function D(){if(!(typeof document<"u"))try{let t=new Error().stack?.split(`
2
- `);if(!t)return;for(let e=3;e<Math.min(t.length,8);e++){let n=t[e]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let r=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(r){let s=r[1]||"<anonymous>",i=r[2]?.replace(/^.*[/\\]/,"")??"",d=r[3];return `${s}@${i}:${d}`}}}catch{}}function K(){if(typeof localStorage<"u"){let o=localStorage.getItem(w);if(o)return o;let t=b();return localStorage.setItem(w,t),t}return b()}function X(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(_);if(o)return o;let t=b();return sessionStorage.setItem(_,t),t}return b()}function z(){let o="";for(let t=0;t<32;t++)o+=(Math.random()*16|0).toString(16);return o}function V(){let o="";for(let t=0;t<16;t++)o+=(Math.random()*16|0).toString(16);return o}function W(o,t){switch(o){case "lcp":return t<=2500?"good":t<=4e3?"needs-improvement":"poor";case "inp":return t<=200?"good":t<=500?"needs-improvement":"poor";case "cls":return t<=.1?"good":t<=.25?"needs-improvement":"poor";case "fcp":return t<=1800?"good":t<=3e3?"needs-improvement":"poor";case "ttfb":return t<=800?"good":t<=1800?"needs-improvement":"poor";default:return}}function J(o){if(!o)return [];let t=[];for(let e of o.split(`
3
- `)){let n=e.trim();if(!n||n.startsWith("Error")||n.startsWith("at Error"))continue;let r=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(n);if(r){let s=r[1]?.trim(),i=r[2];t.push({function:s&&s!=="<anonymous>"?s:void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")&&!i.startsWith("internal/")});continue}if(r=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(n),r){let s=r[1]?.trim(),i=r[2];t.push({function:s||void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")});}}return t}var R=class R{constructor(t){this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint).replace(/\/+$/,""),this.flushInterval=t.flushInterval??G,this.batchSize=t.batchSize??F,this.defaultContext=t.defaultContext??{},this.onError=t.onError??(()=>{}),this.disabled=t.disabled??false,this.telemetry=t.telemetry??true,this.useEnvelope=t.useEnvelope??false,this.autoFetch=t.autoFetch??(this.useEnvelope&&t.autocapture!==false),this.anonymousId=K(),this.sessionId=X(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),t.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(t,e,n){if(this.disabled)return;let r=65536,s=e;e.length>r&&(s=e.slice(0,r-100)+`
1
+ var S=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var x={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(i){let t=i.split("_");return t.length>=4&&t[0]==="gl"?t[2]:"eu"}function y(i,t){if(t)return t;let e=B(i);return x[e]||x.eu}var G=5e3,F=50,v="0.4.2",w="gl_anon_id",E="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return (i==="x"?t:t&3|8).toString(16)})}function M(){let i={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(i.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(i.$language=navigator.language??""),typeof location<"u"&&(i.$url=location.href,i.$path=location.pathname,i.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(i.$referrer=document.referrer),document.title&&(i.$title=document.title))),i}function U(i,t){let e={$session_id:i,$distinct_id:t,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(e.$url=location.href,e.$path=location.pathname),e}function D(){if(!(typeof document<"u"))try{let t=new Error().stack?.split(`
2
+ `);if(!t)return;for(let e=3;e<Math.min(t.length,8);e++){let r=t[e]?.trim();if(!r||r.includes("goodlogs")&&(r.includes("client.")||r.includes("index.")))continue;let n=r.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(n){let s=n[1]||"<anonymous>",o=n[2]?.replace(/^.*[/\\]/,"")??"",d=n[3];return `${s}@${o}:${d}`}}}catch{}}function K(){if(typeof localStorage<"u"){let i=localStorage.getItem(w);if(i)return i;let t=b();return localStorage.setItem(w,t),t}return b()}function V(){if(typeof sessionStorage<"u"){let i=sessionStorage.getItem(E);if(i)return i;let t=b();return sessionStorage.setItem(E,t),t}return b()}function X(){let i="";for(let t=0;t<32;t++)i+=(Math.random()*16|0).toString(16);return i}function z(){let i="";for(let t=0;t<16;t++)i+=(Math.random()*16|0).toString(16);return i}function W(i,t){switch(i){case "lcp":return t<=2500?"good":t<=4e3?"needs-improvement":"poor";case "inp":return t<=200?"good":t<=500?"needs-improvement":"poor";case "cls":return t<=.1?"good":t<=.25?"needs-improvement":"poor";case "fcp":return t<=1800?"good":t<=3e3?"needs-improvement":"poor";case "ttfb":return t<=800?"good":t<=1800?"needs-improvement":"poor";case "dns":return t<=20?"good":t<=100?"needs-improvement":"poor";case "tcp":return t<=50?"good":t<=200?"needs-improvement":"poor";case "download":return t<=100?"good":t<=500?"needs-improvement":"poor";case "dom_processing":return t<=500?"good":t<=1500?"needs-improvement":"poor";case "page_load":return t<=1e3?"good":t<=3e3?"needs-improvement":"poor";default:return}}function J(i){if(!i)return [];let t=[];for(let e of i.split(`
3
+ `)){let r=e.trim();if(!r||r.startsWith("Error")||r.startsWith("at Error"))continue;let n=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(r);if(n){let s=n[1]?.trim(),o=n[2];t.push({function:s&&s!=="<anonymous>"?s:void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")&&!o.startsWith("internal/")});continue}if(n=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(r),n){let s=n[1]?.trim(),o=n[2];t.push({function:s||void 0,filename:o,lineno:Number(n[3]),colno:Number(n[4]),abs_path:o,in_app:!o.includes("node_modules/")&&!o.includes("/dist/")});}}return t}var R=class R{constructor(t){this.originalFetch=null;this.xhrPatched=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint).replace(/\/+$/,""),this.flushInterval=t.flushInterval??G,this.batchSize=t.batchSize??F,this.defaultContext=t.defaultContext??{},this.onError=t.onError??(()=>{}),this.disabled=t.disabled??false,this.telemetry=t.telemetry??true,this.useEnvelope=t.useEnvelope??false,this.autoFetch=t.autoFetch??(this.useEnvelope&&t.autocapture!==false),this.anonymousId=K(),this.sessionId=V(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),t.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(t,e,r){if(this.disabled)return;let n=65536,s=e;e.length>n&&(s=e.slice(0,n-100)+`
4
4
 
5
- [truncated \u2014 original ${e.length} chars, limit ${r}]`,this.onError(new Error(`Log message truncated from ${e.length} to ${r} chars`)));let i=D(),d={severity:t,message:s,properties:{...this.defaultContext,...U(this.sessionId,this.anonymousId),...i?{code_location:i}:{},...n},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(t,e){this.log("debug",t,e);}info(t,e){this.log("info",t,e);}warn(t,e){this.log("warn",t,e);}error(t,e){this.log("error",t,e);}fatal(t,e){this.log("fatal",t,e);}identify(t){this.anonymousId=t,typeof localStorage<"u"&&localStorage.setItem(w,t);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId);}setSessionId(t){this.sessionId=t,typeof sessionStorage<"u"&&sessionStorage.setItem(_,t);}track(t,e){if(this.disabled)return;let{distinctId:n,...r}=e??{},s={event:t,distinctId:n??this.anonymousId,properties:{...M(),...r,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(t){if(this.disabled)return;let e={ts:t.ts??new Date().toISOString(),...t};this.breadcrumbBuffer.push(e),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(t,e){if(this.disabled)return;let n=this.buildErrorEntry(t,e);this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(n.message,{exception_type:n.exception_type,frames:n.frames});}captureMessage(t,e){if(this.disabled)return;let n={level:e?.level??"info",message:t,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(t);}buildErrorEntry(t,e){let n,r,s=[];if(t instanceof Error)n=t.name,r=t.message,s=J(t.stack);else if(typeof t=="string")r=t;else try{r=JSON.stringify(t);}catch{r=String(t);}return {level:e?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:n,message:r,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id}}captureVital(t,e,n){if(this.disabled||!Number.isFinite(e)||e<0)return;let r=n?.rating??W(t,e),s={metric:t,value_ms:t==="cls"?e:Math.round(e),rating:r,route:n?.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:n?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:t.toUpperCase(),$value_ms:s.value_ms,$rating:r}});}startTransaction(t){return this.makeSpan(void 0,t)}startSpan(t){return this.makeSpan(void 0,t)}makeSpan(t,e){let n=e?.trace_id??e?.parent?.trace_id??t?.trace_id??z(),r=V(),s=e?.parent?.span_id??t?.span_id,i=Date.now(),d=new Date(i).toISOString(),a={...e?.attributes??{}},c="unset",u=[],h=false,f=this,g={span_id:r,trace_id:n,setAttribute(p,l){a[p]=l;},setStatus(p){c=p;},addEvent(p,l){u.push({ts:new Date().toISOString(),name:p,attributes:l});},startChild(p){return f.makeSpan(g,p)},finish(){if(h)return;h=true;let p=Date.now(),l={span_id:r,trace_id:n,parent_span_id:s,name:e?.name,op:e?.op,status:c==="unset"?"ok":c,kind:e?.kind,attributes:a,events:u,start_time:d,end_time:new Date(p).toISOString(),timestamp:d,duration_ms:p-i};f.useEnvelope&&(f.spanBuffer.push(l),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),n=this.errorBuffer.splice(0),r=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),i=[];this.useEnvelope?(t.length>0||e.length>0||n.length>0||r.length>0||s.length>0)&&i.push(this.sendEnvelope(t,e,n,r,s)):(t.length>0&&i.push(this.sendLogs(t)),e.length>0&&i.push(this.sendEvents(e))),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(t){for(let n=0;n<t.length;n+=500){let s=t.slice(n,n+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(t){for(let n=0;n<t.length;n+=500){let s=t.slice(n,n+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(t,e,n,r,s){let d=[...t.map(a=>({kind:"log",entry:a})),...e.map(a=>({kind:"event",entry:a})),...n.map(a=>({kind:"error",entry:a})),...r.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let c=d.slice(a,a+1e3),u=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),h=c.map(g=>{if(g.kind==="log"){let l=g.entry;return JSON.stringify({type:"log",severity:l.severity,message:l.message,properties:l.properties,timestamp:l.timestamp})}if(g.kind==="event"){let l=g.entry;return JSON.stringify({type:"event",event:l.event,distinctId:l.distinctId,properties:l.properties,timestamp:l.timestamp})}if(g.kind==="error"){let l=g.entry;return JSON.stringify({type:"error",...l})}if(g.kind==="vital"){let l=g.entry;return JSON.stringify({type:"vital",...l})}let p=g.entry;return JSON.stringify({type:"span",...p})}),f=[u,...h].join(`
6
- `);await this.postEnvelopeWithRetry(f,c);}}async postEnvelopeWithRetry(t,e,n=0){try{let r=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:t});if(r.status===429||r.status===503){if(n<4){let s=Math.min(1e3*Math.pow(2,n),8e3),i=Math.random()*500;return await new Promise(d=>setTimeout(d,s+i)),this.postEnvelopeWithRetry(t,e,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!r.ok){let s=await r.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${r.status}: ${s}`)),r.status>=500&&n===0)for(let i of e)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(r){if(n===0)for(let s of e)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(r instanceof Error?r:new Error(String(r)));}}async postWithRetry(t,e,n,r=0){try{let s=await fetch(`${this.endpoint}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:e})});if(s.status===429||s.status===503){if(r<4){let d=Math.min(1e3*Math.pow(2,r),8e3),a=Math.random()*500;return await new Promise(c=>setTimeout(c,d+a)),this.postWithRetry(t,e,n,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} 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&&r===0&&n(e);return}let i=await s.json().catch(()=>null);if(i&&i.rejected&&i.rejected>0){let d=e.slice(i.accepted??0);d.length>0&&n(d);}}catch(s){let i=s instanceof Error?s:new Error(String(s));r===0&&n(e),this.onError(i);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let t=this.timer;typeof t?.unref=="function"&&t.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let t=(e,n)=>{if(this.useEnvelope)this.captureVital(e.toLowerCase(),n);else {let r=e==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:e,[r]:e==="CLS"?n:Math.round(n)}});}};try{new PerformanceObserver(e=>{let n=e.getEntries()[0];n&&t("FCP",n.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let n=e.getEntries(),r=n[n.length-1];r&&t("LCP",r.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(n=>{for(let r of n.getEntries())r.hadRecentInput||(e+=r.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{e>0&&t("CLS",Math.round(e*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n();});}}catch{}try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&t("TTFB",e.responseStart);}}catch{}try{new PerformanceObserver(e=>{for(let n of e.getEntries()){let r=n.duration;r>0&&t("INP",r);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let t=(e="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,e));};if(typeof history<"u"){let e=history.pushState,n=history.replaceState;history.pushState=function(...r){e.apply(this,r),t("push");},history.replaceState=function(...r){n.apply(this,r),t("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>t("popstate"));}startNavTransaction(t,e){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:t,attributes:{"navigation.type":e,"http.url":typeof location<"u"?location.href:t}});let n=this.navTransaction;setTimeout(()=>{this.navTransaction===n&&(n.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let t=globalThis;typeof t.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=e=>{let n=e,r=n.error??new Error(n.message??"Uncaught error");try{this.captureException(r,{tags:{source:"window.onerror"},extra:n.filename?{filename:n.filename,lineno:n.lineno,colno:n.colno}:void 0});}catch{}},this.rejectionHandler=e=>{let r=e.reason,s=r;if(!(r instanceof Error)){let i;if(typeof r=="string")i=r;else try{i=JSON.stringify(r);}catch{i=String(r);}s=new Error(i);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},t.addEventListener("error",this.errorHandler),t.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let t=globalThis;typeof t.removeEventListener=="function"&&(this.errorHandler&&(t.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(t.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let t=globalThis;if(this.originalFetch)return;this.originalFetch=t.fetch;let e=t.fetch.bind(globalThis),n=this;t.fetch=function(s,i){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let h=s;d=h.url??"",a=h.method??a;}let c=i??{};if(c.method?a=String(c.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(n.endpoint))return e(s,c);let u=n.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:n.navTransaction??void 0});try{let h=`00-${u.trace_id}-${u.span_id}-01`,f={...c},g=f.headers??{};return f.headers={...g,traceparent:h},e(s,f).then(p=>{let l=p;return typeof l.status=="number"&&u.setAttribute("http.status_code",l.status),u.setStatus(l.ok===!1?"error":"ok"),u.finish(),p}).catch(p=>{throw u.setStatus("error"),u.setAttribute("error.message",p instanceof Error?p.message:String(p)),u.finish(),p})}catch(h){throw u.setStatus("error"),u.finish(),h}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let e=globalThis.XMLHttpRequest;if(!e||!e.prototype)return;let n=Symbol.for("goodlogs.xhr.patched"),r=e.prototype;if(r[n]){this.xhrPatched=true;return}let s=r.open,i=r.setRequestHeader,d=r.send,a=this;r.open=function(u,h,...f){return this.__gl_method=typeof u=="string"?u.toUpperCase():"GET",this.__gl_url=typeof h=="string"?h:String(h??""),this.__gl_headers_set=false,s.apply(this,[u,h,...f])},r.setRequestHeader=function(u,h){return this.__gl_headers_set=true,i.apply(this,[u,h])},r.send=function(u){let h=this.__gl_url||"",f=this.__gl_method||"GET";if(h.startsWith(a.endpoint))return d.apply(this,[u]);let g=a.startSpan({op:"http.client",name:`${f} ${h}`,attributes:{"http.method":f,"http.url":h},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;i.apply(this,["traceparent",m]);}catch{}let p=(m,E,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(E?"ok":"error"),g.finish();},l=this.addEventListener;return typeof l=="function"?(l.call(this,"load",()=>{let m=Number(this.status||0);p(m,m>0&&m<500);}),l.call(this,"error",()=>p(0,false,"network error")),l.call(this,"abort",()=>p(0,false,"aborted")),l.call(this,"timeout",()=>p(0,false,"timeout"))):p(0,true),d.apply(this,[u])},r[n]=true,r.__gl_orig_open=s,r.__gl_orig_set_header=i,r.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let e=globalThis.XMLHttpRequest?.prototype;if(!e)return;let n=Symbol.for("goodlogs.xhr.patched");e.__gl_orig_open&&(e.open=e.__gl_orig_open),e.__gl_orig_set_header&&(e.setRequestHeader=e.__gl_orig_set_header),e.__gl_orig_send&&(e.send=e.__gl_orig_send),delete e.__gl_orig_open,delete e.__gl_orig_set_header,delete e.__gl_orig_send,delete e[n],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=t=>{let n=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let r=n.getAttribute?.("data-gl-event"),s=n.tagName?.toLowerCase()??"",i=(n.textContent??"").trim().slice(0,50),d=n.getAttribute?.("href")??void 0,a=(n.className??"").toString().slice(0,80);this.track(r||"$click",{properties:{$element_tag:s,$element_text:i||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};t.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(r=>({severity:r.severity,message:r.message,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{}),e.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(r=>({event:r.event,distinctId:r.distinctId,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(t,e,n){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:t,level:e,metadata:{...n,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var C=R;var $=class{constructor(t){if(!t.apiKey)throw new Error("apiKey is required");if(!t.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint),this.timeout=t.timeout??3e4,this.alerts=new L(this),this.slos=new P(this),this.ai=new A(this);}async _request(t,e,n){let r=`${this.endpoint}${e}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=new AbortController,d=setTimeout(()=>i.abort(),this.timeout);try{let a=await fetch(r,{method:t,headers:s,body:n?JSON.stringify(n):void 0,signal:i.signal});if(!a.ok){let c=await a.json().catch(()=>({})),u=c?.error?.message??`API error ${a.status}`;throw new T(a.status,u,c?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(t){return this._request("GET",t)}_post(t,e){return this._request("POST",t,e)}_put(t,e){return this._request("PUT",t,e)}_delete(t){return this._request("DELETE",t)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(t){return this._post("/v1/gql/query",{q:t})}gqlBatch(t){return this._post("/v1/gql",{queries:t})}gqlAutocomplete(t,e){let n=`/v1/gql/autocomplete?q=${encodeURIComponent(t)}`;return e!==void 0&&(n+=`&cursor=${e}`),this._get(n)}nl2gql(t,e){return this._post("/v1/gql/nl",{prompt:t,mode:e})}},L=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/alerts")}create(t){return this.client._post("/v1/alerts",t)}update(t,e){return this.client._put(`/v1/alerts/${t}`,e)}delete(t){return this.client._delete(`/v1/alerts/${t}`)}mute(t,e){return this.client._post(`/v1/alerts/${t}/mute`,{minutes:e})}},P=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/slos")}create(t){return this.client._post("/v1/slos",t)}update(t,e){return this.client._put(`/v1/slos/${t}`,e)}delete(t){return this.client._delete(`/v1/slos/${t}`)}},A=class{constructor(t){this.client=t;}chat(t,e){return this.client._post("/v1/ai/chat",{message:t,session_id:e})}},T=class extends Error{constructor(e,n,r){super(n);this.status=e;this.code=r;this.name="GoodLogsApiError";}};var q="0.1.0";function Y(o,t){let e=y(t?.apiKey??"",t?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":q};t?.token&&(n.Authorization=`Bearer ${t.token}`),fetch(`${e}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:o.source,event:o.event,level:o.level??"info",metadata:{...o.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function x(o){if(!o)return null;let t=o.trim().split("-");if(t.length!==4)return null;let[e,n,r,s]=t;return e.length!==2||n.length!==32||r.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(n)||!/^[0-9a-f]+$/.test(r)?null:{trace_id:n,parent_span_id:r}}function N(o,t){if(!o)return;let e=o[t]??o[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function Q(o){return function(e,n,r){let s=(e.method??"GET").toUpperCase(),i=e.originalUrl??e.url??"",d=x(N(e.headers,"traceparent")),a=o.startTransaction({op:"http.server",name:`${s} ${i}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":i}}),c=false,u=()=>{if(c)return;c=true;let h=e.route?.path;h&&a.setAttribute("http.route",h);let f=n.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};n.on("finish",u),n.on("close",u),e.goodlogs={span:a},r();}}function Z(o){return function(e,n,r){e.addHook("onRequest",(s,i,d)=>{let a=(s.method??"GET").toUpperCase(),c=s.url??"",u=x(N(s.headers,"traceparent")),h=o.startTransaction({op:"http.server",name:`${a} ${c}`,trace_id:u?.trace_id,attributes:{"http.method":a,"http.url":c}});s.__goodlogsSpan=h,d();}),e.addHook("onResponse",(s,i,d)=>{let a=s.__goodlogsSpan;if(a){let c=s.routerPath??s.routeOptions?.url;c&&a.setAttribute("http.route",c);let u=i.statusCode??i.raw?.statusCode??200;a.setAttribute("http.status_code",u),a.setStatus(u>=500?"error":"ok"),a.finish();}d();}),r();}}function tt(o){return {intercept(t,e){let n=t.switchToHttp(),r=n.getRequest(),s=n.getResponse(),i=(r.method??"GET").toUpperCase(),d=r.originalUrl??r.url??"",a=x(N(r.headers,"traceparent")),c=o.startTransaction({op:"http.server",name:`${i} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":i,"http.url":d}}),u=false,h=(g,p)=>{if(u)return;u=true;let l=r.route?.path;l&&c.setAttribute("http.route",l);let m=g??s.statusCode??200;c.setAttribute("http.status_code",m),c.setStatus(p||m>=500?"error":"ok"),c.finish();};s.on("finish",()=>h()),s.on("close",()=>h());let f=e.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:p=>{c.setAttribute("error.message",p instanceof Error?p.message:String(p)),h(500,true);},complete:()=>h()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function et(o){let t=globalThis.process;if(!t||typeof t.on!="function")return;let e=t,n=Symbol.for("goodlogs.node-process.patched");e[n]||(t.on("uncaughtException",r=>{try{o.captureException(r instanceof Error?r:new Error(String(r)),{tags:{source:"uncaughtException"},level:"fatal"}),o.flush();}catch{}}),t.on("unhandledRejection",r=>{try{let s=r instanceof Error?r:new Error(typeof r=="string"?r:(()=>{try{return JSON.stringify(r)}catch{return String(r)}})());o.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),e[n]=true);}var H=globalThis.URL;function k(o){return !!H&&o instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function nt(...o){let t=o[0],e=o[1],n="GET",r="";if(typeof t=="string")r=t,e&&typeof e=="object"&&!k(e)&&(n=String(e.method??n).toUpperCase());else if(k(t))r=t.toString(),e&&typeof e=="object"&&!k(e)&&(n=String(e.method??n).toUpperCase());else if(t&&typeof t=="object"){let i=t;n=String(i.method??n).toUpperCase();let d=(i.protocol??"http:").replace(":",""),a=i.hostname??i.host??"localhost",c=i.port?`:${i.port}`:"";r=`${d}://${a}${c}${i.path??"/"}`;}return {method:n,url:r,isOurs:i=>!!i&&r.startsWith(i)}}function rt(o,t,e){let n=o[0]&&typeof o[0]=="object"&&!k(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!k(o[1])?o[1]:void 0;n&&(n.headers||(n.headers={}),!(t in n.headers)&&!(t.toLowerCase()in n.headers)&&(n.headers[t]=e));}function st(o,t){let e=t?.endpoint??o.endpoint??"",n=r=>{let s=r;if(s[j])return;s[j]=true;let i=r.request.bind(r);r.request=function(...a){let{method:c,url:u,isOurs:h}=nt(...a);if(!u||h(e))return i(...a);let f=o.startTransaction({op:"http.client",name:`${c} ${u}`,attributes:{"http.method":c,"http.url":u}});rt(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,p=(m,E)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),E?(f.setAttribute("error.message",E.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},l=i(...a);return l.on("response",m=>p(m.statusCode)),l.on("error",m=>p(void 0,m)),l.on("close",()=>p()),l};};if(typeof S=="function"){try{let r=S("http");n(r);}catch{}try{let r=S("https");n(r);}catch{}}}
7
- export{C as GoodLogs,T as GoodLogsApiError,$ as GoodLogsClient,I as REGION_URLS,Q as goodlogsExpress,Z as goodlogsFastify,tt as goodlogsNestInterceptor,st as instrumentNodeHttp,et as instrumentNodeProcess,x as parseTraceparent,y as resolveEndpoint,B as resolveRegion,Y as sendTelemetry};
5
+ [truncated \u2014 original ${e.length} chars, limit ${n}]`,this.onError(new Error(`Log message truncated from ${e.length} to ${n} chars`)));let o=D(),d={severity:t,message:s,properties:{...this.defaultContext,...U(this.sessionId,this.anonymousId),...o?{code_location:o}:{},...r},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(t,e){this.log("debug",t,e);}info(t,e){this.log("info",t,e);}warn(t,e){this.log("warn",t,e);}error(t,e){this.log("error",t,e);}fatal(t,e){this.log("fatal",t,e);}identify(t){this.anonymousId=t,typeof localStorage<"u"&&localStorage.setItem(w,t);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(E,this.sessionId);}setSessionId(t){this.sessionId=t,typeof sessionStorage<"u"&&sessionStorage.setItem(E,t);}track(t,e){if(this.disabled)return;let{distinctId:r,...n}=e??{},s={event:t,distinctId:r??this.anonymousId,properties:{...M(),...n,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(t){if(this.disabled)return;let e={ts:t.ts??new Date().toISOString(),...t};this.breadcrumbBuffer.push(e),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(t,e){if(this.disabled)return;let r=this.buildErrorEntry(t,e);this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(r.message,{exception_type:r.exception_type,frames:r.frames});}captureMessage(t,e){if(this.disabled)return;let r={level:e?.level??"info",message:t,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(r),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(t);}buildErrorEntry(t,e){let r,n,s=[];if(t instanceof Error)r=t.name,n=t.message,s=J(t.stack);else if(typeof t=="string")n=t;else try{n=JSON.stringify(t);}catch{n=String(t);}return {level:e?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:r,message:n,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:e?.fingerprint,tags:e?.tags,extra:e?.extra,user_id:e?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id}}captureVital(t,e,r){if(this.disabled||!Number.isFinite(e)||e<0)return;let n=r?.rating??W(t,e),s={metric:t,value_ms:t==="cls"?e:Math.round(e),rating:n,route:r?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:r?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:t.toUpperCase(),$value_ms:s.value_ms,$rating:n}});}startTransaction(t){return this.makeSpan(void 0,t)}startSpan(t){return this.makeSpan(void 0,t)}makeSpan(t,e){let r=e?.trace_id??e?.parent?.trace_id??t?.trace_id??X(),n=z(),s=e?.parent?.span_id??t?.span_id,o=Date.now(),d=new Date(o).toISOString(),a={...e?.attributes??{}},u="unset",c=[],l=false,f=this,g={span_id:n,trace_id:r,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){c.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(l)return;l=true;let h=Date.now(),p={span_id:n,trace_id:r,parent_span_id:s,name:e?.name,op:e?.op,status:u==="unset"?"ok":u,kind:e?.kind,attributes:a,events:c,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-o};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r=this.errorBuffer.splice(0),n=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0),o=[];this.useEnvelope?(t.length>0||e.length>0||r.length>0||n.length>0||s.length>0)&&o.push(this.sendEnvelope(t,e,r,n,s)):(t.length>0&&o.push(this.sendLogs(t)),e.length>0&&o.push(this.sendEvents(e))),await Promise.all(o);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({severity:o.severity,message:o.message,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/logs",s,o=>{for(let d of o)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(t){for(let r=0;r<t.length;r+=500){let s=t.slice(r,r+500).map(o=>({event:o.event,distinctId:o.distinctId,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/events",s,o=>{for(let d of o)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(t,e,r,n,s){let d=[...t.map(a=>({kind:"log",entry:a})),...e.map(a=>({kind:"event",entry:a})),...r.map(a=>({kind:"error",entry:a})),...n.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),c=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),l=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[c,...l].join(`
6
+ `);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(t,e,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:t});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),this.postEnvelopeWithRetry(t,e,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let o of e)o.kind==="log"?this.logBuffer.push(o.entry):o.kind==="event"?this.eventBuffer.push(o.entry):o.kind==="error"?this.errorBuffer.push(o.entry):o.kind==="vital"?this.vitalBuffer.push(o.entry):this.spanBuffer.push(o.entry);}}catch(n){if(r===0)for(let s of e)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(t,e,r,n=0){try{let s=await fetch(`${this.endpoint}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:e})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(t,e,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(e);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=e.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(e),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let t=this.timer;typeof t?.unref=="function"&&t.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let t=(e,r)=>{if(this.useEnvelope)this.captureVital(e.toLowerCase(),r);else {let n=e==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:e,[n]:e==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(e=>{let r=e.getEntries()[0];r&&t("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let r=e.getEntries(),n=r[r.length-1];n&&t("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{e>0&&t("CLS",Math.round(e*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&t("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,o=s(n.domainLookupEnd)-s(n.domainLookupStart);o>0&&this.captureVital("dns",o);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&t("TTFB",e.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(e?.domainLookupEnd)-r(e?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(e?.connectEnd)-r(e?.connectStart);s>0&&this.captureVital("tcp",s);let o=r(e?.responseEnd)-r(e?.responseStart);o>0&&this.captureVital("download",o);let d=r(e?.domComplete)-r(e?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(e?.loadEventEnd)-r(e?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(e=>{for(let r of e.getEntries()){let n=r.duration;n>0&&t("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let t=(e="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,e));};if(typeof history<"u"){let e=history.pushState,r=history.replaceState;history.pushState=function(...n){e.apply(this,n),t("push");},history.replaceState=function(...n){r.apply(this,n),t("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>t("popstate"));}startNavTransaction(t,e){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:t,attributes:{"navigation.type":e,"http.url":typeof location<"u"?location.href:t}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let t=globalThis;typeof t.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=e=>{let r=e,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=e=>{let n=e.reason,s=n;if(!(n instanceof Error)){let o;if(typeof n=="string")o=n;else try{o=JSON.stringify(n);}catch{o=String(n);}s=new Error(o);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},t.addEventListener("error",this.errorHandler),t.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let t=globalThis;typeof t.removeEventListener=="function"&&(this.errorHandler&&(t.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(t.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let t=globalThis;if(this.originalFetch)return;this.originalFetch=t.fetch;let e=t.fetch.bind(globalThis),r=this;t.fetch=function(s,o){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=o??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return e(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},e(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let e=globalThis.XMLHttpRequest;if(!e||!e.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=e.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,o=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,o.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;o.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=o,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let e=globalThis.XMLHttpRequest?.prototype;if(!e)return;let r=Symbol.for("goodlogs.xhr.patched");e.__gl_orig_open&&(e.open=e.__gl_orig_open),e.__gl_orig_set_header&&(e.setRequestHeader=e.__gl_orig_set_header),e.__gl_orig_send&&(e.send=e.__gl_orig_send),delete e.__gl_orig_open,delete e.__gl_orig_set_header,delete e.__gl_orig_send,delete e[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=t=>{let r=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",o=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80);this.track(n||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let t=this.logBuffer.splice(0),e=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};t.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),e.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(t,e,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:t,level:e,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var I=R;var L=class{constructor(t){if(!t.apiKey)throw new Error("apiKey is required");if(!t.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=t.apiKey,this.endpoint=y(t.apiKey,t.endpoint),this.timeout=t.timeout??3e4,this.alerts=new $(this),this.slos=new P(this),this.ai=new A(this);}async _request(t,e,r){let n=`${this.endpoint}${e}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:t,headers:s,body:r?JSON.stringify(r):void 0,signal:o.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(t){return this._request("GET",t)}_post(t,e){return this._request("POST",t,e)}_put(t,e){return this._request("PUT",t,e)}_delete(t){return this._request("DELETE",t)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(t){return this._post("/v1/gql/query",{q:t})}gqlBatch(t){return this._post("/v1/gql",{queries:t})}gqlAutocomplete(t,e){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(t)}`;return e!==void 0&&(r+=`&cursor=${e}`),this._get(r)}nl2gql(t,e){return this._post("/v1/gql/nl",{prompt:t,mode:e})}},$=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/alerts")}create(t){return this.client._post("/v1/alerts",t)}update(t,e){return this.client._put(`/v1/alerts/${t}`,e)}delete(t){return this.client._delete(`/v1/alerts/${t}`)}mute(t,e){return this.client._post(`/v1/alerts/${t}/mute`,{minutes:e})}},P=class{constructor(t){this.client=t;}list(){return this.client._get("/v1/slos")}create(t){return this.client._post("/v1/slos",t)}update(t,e){return this.client._put(`/v1/slos/${t}`,e)}delete(t){return this.client._delete(`/v1/slos/${t}`)}},A=class{constructor(t){this.client=t;}chat(t,e){return this.client._post("/v1/ai/chat",{message:t,session_id:e})}},T=class extends Error{constructor(e,r,n){super(r);this.status=e;this.code=n;this.name="GoodLogsApiError";}};var q="0.1.0";function Y(i,t){let e=y(t?.apiKey??"",t?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};t?.token&&(r.Authorization=`Bearer ${t.token}`),fetch(`${e}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function C(i){if(!i)return null;let t=i.trim().split("-");if(t.length!==4)return null;let[e,r,n,s]=t;return e.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(i,t){if(!i)return;let e=i[t]??i[t.toLowerCase()];return Array.isArray(e)?e[0]:e}function Q(i){return function(e,r,n){let s=(e.method??"GET").toUpperCase(),o=e.originalUrl??e.url??"",d=C(N(e.headers,"traceparent")),a=i.startTransaction({op:"http.server",name:`${s} ${o}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":o}}),u=false,c=()=>{if(u)return;u=true;let l=e.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),e.goodlogs={span:a},n();}}function Z(i){return function(e,r,n){e.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),e.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function tt(i){return {intercept(t,e){let r=t.switchToHttp(),n=r.getRequest(),s=r.getResponse(),o=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=e.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function et(i){let t=globalThis.process;if(!t||typeof t.on!="function")return;let e=t,r=Symbol.for("goodlogs.node-process.patched");e[r]||(t.on("uncaughtException",n=>{try{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.flush();}catch{}}),t.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),e[r]=true);}var H=globalThis.URL;function k(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function nt(...i){let t=i[0],e=i[1],r="GET",n="";if(typeof t=="string")n=t,e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(k(t))n=t.toString(),e&&typeof e=="object"&&!k(e)&&(r=String(e.method??r).toUpperCase());else if(t&&typeof t=="object"){let o=t;r=String(o.method??r).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",u=o.port?`:${o.port}`:"";n=`${d}://${a}${u}${o.path??"/"}`;}return {method:r,url:n,isOurs:o=>!!o&&n.startsWith(o)}}function rt(i,t,e){let r=i[0]&&typeof i[0]=="object"&&!k(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!k(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(t in r.headers)&&!(t.toLowerCase()in r.headers)&&(r.headers[t]=e));}function st(i,t){let e=t?.endpoint??i.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let o=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=nt(...a);if(!c||l(e))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});rt(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=o(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
7
+ export{I as GoodLogs,T as GoodLogsApiError,L as GoodLogsClient,x as REGION_URLS,Q as goodlogsExpress,Z as goodlogsFastify,tt as goodlogsNestInterceptor,st as instrumentNodeHttp,et as instrumentNodeProcess,C as parseTraceparent,y as resolveEndpoint,B as resolveRegion,Y as sendTelemetry};
@@ -0,0 +1 @@
1
+ 'use strict';function P(a,o={}){let n=typeof performance<"u"?performance.memory:null;if(!n)return null;let c=a.endpoint,y=a.apiKey,p=o.intervalMs??1e4,d=o.flushIntervalMs??3e4,b=o.enableBreakdown??true,r=[],s=null,i=false,f=b&&typeof performance.measureUserAgentSpecificMemory=="function",g=()=>{try{return globalThis.location?.pathname??null}catch{return null}},l=async()=>{if(i)return;let t=n.usedJSHeapSize,v=n.totalJSHeapSize,S=n.jsHeapSizeLimit,k=s!==null?t-s:null;s=t;let m;if(f)try{m=(await performance.measureUserAgentSpecificMemory()).breakdown.filter(e=>e.bytes>0&&e.attribution.length>0).map(e=>({url:e.attribution[0]?.url||"unknown",bytes:e.bytes,types:e.types})).sort((e,w)=>w.bytes-e.bytes).slice(0,20);}catch{}r.push({timestamp:new Date().toISOString(),used_bytes:t,total_bytes:v,limit_bytes:S,breakdown:m,delta_bytes:k,route:g()});},u=()=>{if(r.length===0)return;let t=r;r=[];try{fetch(`${c}/v1/profiles/memory`,{method:"POST",headers:{Authorization:`Bearer ${y}`,"Content-Type":"application/json"},body:JSON.stringify({batch:t}),keepalive:!0}).catch(()=>{});}catch{}},h=setInterval(()=>{l();},p),M=setInterval(u,d);return l(),{stop:()=>{i=true,clearInterval(h),clearInterval(M),u();}}}exports.startMemoryProfiling=P;
@@ -0,0 +1,37 @@
1
+ import { G as GoodLogs } from './client-CkECCGvR.cjs';
2
+
3
+ /**
4
+ * Memory Profiling — periodic JS heap sampling + per-script breakdown.
5
+ *
6
+ * Usage:
7
+ * import { startMemoryProfiling } from "@aj-2000-test/goodlogs-sdk/profiling";
8
+ * startMemoryProfiling(gl, { intervalMs: 10000 });
9
+ *
10
+ * Uses two browser APIs (both Chromium-only):
11
+ * 1. performance.memory — usedJSHeapSize snapshots (no headers needed)
12
+ * 2. performance.measureUserAgentSpecificMemory() — per-script breakdown
13
+ * (needs Cross-Origin-Opener-Policy + Cross-Origin-Embedder-Policy)
14
+ *
15
+ * Ships samples to POST /v1/profiles/memory every flushIntervalMs.
16
+ */
17
+
18
+ interface MemoryProfilingOptions {
19
+ /** Sampling interval in ms (default 10000 = 10s). */
20
+ intervalMs?: number;
21
+ /** Flush interval in ms (default 30000 = 30s). */
22
+ flushIntervalMs?: number;
23
+ /** Try to use measureUserAgentSpecificMemory for breakdown (default true). */
24
+ enableBreakdown?: boolean;
25
+ /** Called on errors. */
26
+ onError?: (err: unknown) => void;
27
+ }
28
+ interface MemoryProfilingHandle {
29
+ stop: () => void;
30
+ }
31
+ /**
32
+ * Start periodic memory sampling.
33
+ * Returns null if performance.memory is not available (non-Chromium browsers).
34
+ */
35
+ declare function startMemoryProfiling(gl: GoodLogs, options?: MemoryProfilingOptions): MemoryProfilingHandle | null;
36
+
37
+ export { type MemoryProfilingHandle, type MemoryProfilingOptions, startMemoryProfiling };
@@ -0,0 +1,37 @@
1
+ import { G as GoodLogs } from './client-CkECCGvR.js';
2
+
3
+ /**
4
+ * Memory Profiling — periodic JS heap sampling + per-script breakdown.
5
+ *
6
+ * Usage:
7
+ * import { startMemoryProfiling } from "@aj-2000-test/goodlogs-sdk/profiling";
8
+ * startMemoryProfiling(gl, { intervalMs: 10000 });
9
+ *
10
+ * Uses two browser APIs (both Chromium-only):
11
+ * 1. performance.memory — usedJSHeapSize snapshots (no headers needed)
12
+ * 2. performance.measureUserAgentSpecificMemory() — per-script breakdown
13
+ * (needs Cross-Origin-Opener-Policy + Cross-Origin-Embedder-Policy)
14
+ *
15
+ * Ships samples to POST /v1/profiles/memory every flushIntervalMs.
16
+ */
17
+
18
+ interface MemoryProfilingOptions {
19
+ /** Sampling interval in ms (default 10000 = 10s). */
20
+ intervalMs?: number;
21
+ /** Flush interval in ms (default 30000 = 30s). */
22
+ flushIntervalMs?: number;
23
+ /** Try to use measureUserAgentSpecificMemory for breakdown (default true). */
24
+ enableBreakdown?: boolean;
25
+ /** Called on errors. */
26
+ onError?: (err: unknown) => void;
27
+ }
28
+ interface MemoryProfilingHandle {
29
+ stop: () => void;
30
+ }
31
+ /**
32
+ * Start periodic memory sampling.
33
+ * Returns null if performance.memory is not available (non-Chromium browsers).
34
+ */
35
+ declare function startMemoryProfiling(gl: GoodLogs, options?: MemoryProfilingOptions): MemoryProfilingHandle | null;
36
+
37
+ export { type MemoryProfilingHandle, type MemoryProfilingOptions, startMemoryProfiling };
package/dist/memory.js ADDED
@@ -0,0 +1 @@
1
+ function P(a,o={}){let n=typeof performance<"u"?performance.memory:null;if(!n)return null;let c=a.endpoint,y=a.apiKey,p=o.intervalMs??1e4,d=o.flushIntervalMs??3e4,b=o.enableBreakdown??true,r=[],s=null,i=false,f=b&&typeof performance.measureUserAgentSpecificMemory=="function",g=()=>{try{return globalThis.location?.pathname??null}catch{return null}},l=async()=>{if(i)return;let t=n.usedJSHeapSize,v=n.totalJSHeapSize,S=n.jsHeapSizeLimit,k=s!==null?t-s:null;s=t;let m;if(f)try{m=(await performance.measureUserAgentSpecificMemory()).breakdown.filter(e=>e.bytes>0&&e.attribution.length>0).map(e=>({url:e.attribution[0]?.url||"unknown",bytes:e.bytes,types:e.types})).sort((e,w)=>w.bytes-e.bytes).slice(0,20);}catch{}r.push({timestamp:new Date().toISOString(),used_bytes:t,total_bytes:v,limit_bytes:S,breakdown:m,delta_bytes:k,route:g()});},u=()=>{if(r.length===0)return;let t=r;r=[];try{fetch(`${c}/v1/profiles/memory`,{method:"POST",headers:{Authorization:`Bearer ${y}`,"Content-Type":"application/json"},body:JSON.stringify({batch:t}),keepalive:!0}).catch(()=>{});}catch{}},h=setInterval(()=>{l();},p),M=setInterval(u,d);return l(),{stop:()=>{i=true,clearInterval(h),clearInterval(M),u();}}}export{P as startMemoryProfiling};
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-w3t1Yzjd.cjs';
1
+ import { G as GoodLogs } from './client-CkECCGvR.cjs';
2
2
 
3
3
  /**
4
4
  * Continuous Profiling — browser JS Self-Profiling API.
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-w3t1Yzjd.js';
1
+ import { G as GoodLogs } from './client-CkECCGvR.js';
2
2
 
3
3
  /**
4
4
  * Continuous Profiling — browser JS Self-Profiling API.
package/dist/react.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var react=require('react');var r=null,i=[],d=null,p=3e3,g=200,h=1;function l(){d||(d=setInterval(u,p),typeof window<"u"&&window.addEventListener("beforeunload",()=>u()));}function u(){if(!r||i.length===0)return;let e=i;i=[];let t=r.endpoint,n=r.apiKey;try{fetch(`${t}/v1/profiles/renders`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({batch:e}),keepalive:!0}).catch(()=>{});}catch{}}function y(){return typeof window>"u"?null:window.location?.pathname??null}function f(e){return (t,n,o,s,b,m)=>{o<h||(i.push({component:e||t,phase:n,actual_ms:Math.round(o*100)/100,base_ms:Math.round(s*100)/100,commit_time:Math.round(m*100)/100,route:y(),timestamp:new Date().toISOString()}),i.length>=g&&u());}}function R(e){r=e,l();}function P({gl:e,id:t,children:n}){return e&&!r&&(r=e,l()),r&&!d&&l(),react.createElement(react.Profiler,{id:t,onRender:f(t)},n)}function _(e,t){let n=t||e.displayName||e.name||"Unknown",o=s=>react.createElement(react.Profiler,{id:n,onRender:f(n)},react.createElement(e,s));return o.displayName=`withProfiler(${n})`,o}exports.GoodLogsProfiler=P;exports.initReactProfiler=R;exports.withProfiler=_;
1
+ 'use strict';var react=require('react');var u=react.createContext({parent:null,depth:0}),o=null,l=[],c=null,P=3e3,w=200,x=.1;function p(){c||(c=setInterval(f,P),typeof window<"u"&&window.addEventListener("beforeunload",()=>f()));}function f(){if(!o||l.length===0)return;let e=l;l=[];let t=o.endpoint,n=o.apiKey;try{fetch(`${t}/v1/profiles/renders`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({batch:e}),keepalive:!0}).catch(()=>{});}catch{}}function R(){return typeof window>"u"?null:window.location?.pathname??null}function h(e,t,n){return (r,a,i,d,v,y)=>{i<x||(l.push({component:e||r,phase:a,actual_ms:Math.round(i*100)/100,base_ms:Math.round(d*100)/100,commit_time:Math.round(y*100)/100,route:R(),timestamp:new Date().toISOString(),parent:t,depth:n}),l.length>=w&&f());}}function _(e){o=e,p();}function k({gl:e,id:t,children:n}){e&&!o&&(o=e,p()),o&&!c&&p();let r=react.useContext(u),a={parent:t,depth:r.depth+1};return react.createElement(u.Provider,{value:a},react.createElement(react.Profiler,{id:t,onRender:h(t,r.parent,r.depth)},n))}function L(e,t){let n=t||e.displayName||e.name||"Unknown",r=a=>{let i=react.useContext(u),d={parent:n,depth:i.depth+1};return react.createElement(u.Provider,{value:d},react.createElement(react.Profiler,{id:n,onRender:h(n,i.parent,i.depth)},react.createElement(e,a)))};return r.displayName=`withProfiler(${n})`,r}exports.GoodLogsProfiler=k;exports.initReactProfiler=_;exports.withProfiler=L;
package/dist/react.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ReactNode, ComponentType, FC } from 'react';
2
- import { G as GoodLogs } from './client-w3t1Yzjd.cjs';
2
+ import { G as GoodLogs } from './client-CkECCGvR.cjs';
3
3
 
4
4
  /**
5
5
  * React Profiler Integration — component render timing.
@@ -27,13 +27,7 @@ import { G as GoodLogs } from './client-w3t1Yzjd.cjs';
27
27
  declare function initReactProfiler(gl: GoodLogs): void;
28
28
  /**
29
29
  * React Profiler wrapper component. Wraps children in React.Profiler
30
- * and reports render timings to GoodLogs.
31
- *
32
- * ```tsx
33
- * <GoodLogsProfiler gl={gl} id="Checkout">
34
- * <CheckoutForm />
35
- * </GoodLogsProfiler>
36
- * ```
30
+ * and reports render timings with parent-child tracking.
37
31
  */
38
32
  declare function GoodLogsProfiler({ gl, id, children, }: {
39
33
  gl?: GoodLogs;
@@ -41,11 +35,7 @@ declare function GoodLogsProfiler({ gl, id, children, }: {
41
35
  children: ReactNode;
42
36
  }): ReactNode;
43
37
  /**
44
- * HOC: wraps a component with React.Profiler.
45
- *
46
- * ```tsx
47
- * const ProfiledApp = withProfiler(App, "App")
48
- * ```
38
+ * HOC: wraps a component with React.Profiler + parent-child context.
49
39
  */
50
40
  declare function withProfiler<P extends Record<string, unknown>>(Component: ComponentType<P>, displayName?: string): FC<P>;
51
41
 
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ReactNode, ComponentType, FC } from 'react';
2
- import { G as GoodLogs } from './client-w3t1Yzjd.js';
2
+ import { G as GoodLogs } from './client-CkECCGvR.js';
3
3
 
4
4
  /**
5
5
  * React Profiler Integration — component render timing.
@@ -27,13 +27,7 @@ import { G as GoodLogs } from './client-w3t1Yzjd.js';
27
27
  declare function initReactProfiler(gl: GoodLogs): void;
28
28
  /**
29
29
  * React Profiler wrapper component. Wraps children in React.Profiler
30
- * and reports render timings to GoodLogs.
31
- *
32
- * ```tsx
33
- * <GoodLogsProfiler gl={gl} id="Checkout">
34
- * <CheckoutForm />
35
- * </GoodLogsProfiler>
36
- * ```
30
+ * and reports render timings with parent-child tracking.
37
31
  */
38
32
  declare function GoodLogsProfiler({ gl, id, children, }: {
39
33
  gl?: GoodLogs;
@@ -41,11 +35,7 @@ declare function GoodLogsProfiler({ gl, id, children, }: {
41
35
  children: ReactNode;
42
36
  }): ReactNode;
43
37
  /**
44
- * HOC: wraps a component with React.Profiler.
45
- *
46
- * ```tsx
47
- * const ProfiledApp = withProfiler(App, "App")
48
- * ```
38
+ * HOC: wraps a component with React.Profiler + parent-child context.
49
39
  */
50
40
  declare function withProfiler<P extends Record<string, unknown>>(Component: ComponentType<P>, displayName?: string): FC<P>;
51
41
 
package/dist/react.js CHANGED
@@ -1 +1 @@
1
- import {createElement,Profiler}from'react';var r=null,i=[],d=null,p=3e3,g=200,h=1;function l(){d||(d=setInterval(u,p),typeof window<"u"&&window.addEventListener("beforeunload",()=>u()));}function u(){if(!r||i.length===0)return;let e=i;i=[];let t=r.endpoint,n=r.apiKey;try{fetch(`${t}/v1/profiles/renders`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({batch:e}),keepalive:!0}).catch(()=>{});}catch{}}function y(){return typeof window>"u"?null:window.location?.pathname??null}function f(e){return (t,n,o,s,b,m)=>{o<h||(i.push({component:e||t,phase:n,actual_ms:Math.round(o*100)/100,base_ms:Math.round(s*100)/100,commit_time:Math.round(m*100)/100,route:y(),timestamp:new Date().toISOString()}),i.length>=g&&u());}}function R(e){r=e,l();}function P({gl:e,id:t,children:n}){return e&&!r&&(r=e,l()),r&&!d&&l(),createElement(Profiler,{id:t,onRender:f(t)},n)}function _(e,t){let n=t||e.displayName||e.name||"Unknown",o=s=>createElement(Profiler,{id:n,onRender:f(n)},createElement(e,s));return o.displayName=`withProfiler(${n})`,o}export{P as GoodLogsProfiler,R as initReactProfiler,_ as withProfiler};
1
+ import {createContext,useContext,createElement,Profiler}from'react';var u=createContext({parent:null,depth:0}),o=null,l=[],c=null,P=3e3,w=200,x=.1;function p(){c||(c=setInterval(f,P),typeof window<"u"&&window.addEventListener("beforeunload",()=>f()));}function f(){if(!o||l.length===0)return;let e=l;l=[];let t=o.endpoint,n=o.apiKey;try{fetch(`${t}/v1/profiles/renders`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({batch:e}),keepalive:!0}).catch(()=>{});}catch{}}function R(){return typeof window>"u"?null:window.location?.pathname??null}function h(e,t,n){return (r,a,i,d,v,y)=>{i<x||(l.push({component:e||r,phase:a,actual_ms:Math.round(i*100)/100,base_ms:Math.round(d*100)/100,commit_time:Math.round(y*100)/100,route:R(),timestamp:new Date().toISOString(),parent:t,depth:n}),l.length>=w&&f());}}function _(e){o=e,p();}function k({gl:e,id:t,children:n}){e&&!o&&(o=e,p()),o&&!c&&p();let r=useContext(u),a={parent:t,depth:r.depth+1};return createElement(u.Provider,{value:a},createElement(Profiler,{id:t,onRender:h(t,r.parent,r.depth)},n))}function L(e,t){let n=t||e.displayName||e.name||"Unknown",r=a=>{let i=useContext(u),d={parent:n,depth:i.depth+1};return createElement(u.Provider,{value:d},createElement(Profiler,{id:n,onRender:h(n,i.parent,i.depth)},createElement(e,a)))};return r.displayName=`withProfiler(${n})`,r}export{k as GoodLogsProfiler,_ as initReactProfiler,L as withProfiler};
package/dist/replay.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-w3t1Yzjd.cjs';
1
+ import { G as GoodLogs } from './client-CkECCGvR.cjs';
2
2
 
3
3
  /**
4
4
  * Session Replay (rrweb) — optional, tree-split.
package/dist/replay.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { G as GoodLogs } from './client-w3t1Yzjd.js';
1
+ import { G as GoodLogs } from './client-CkECCGvR.js';
2
2
 
3
3
  /**
4
4
  * Session Replay (rrweb) — optional, tree-split.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aj-2000-test/goodlogs-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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",
@@ -22,6 +22,11 @@
22
22
  "require": "./dist/profiling.cjs",
23
23
  "types": "./dist/profiling.d.ts"
24
24
  },
25
+ "./memory": {
26
+ "import": "./dist/memory.js",
27
+ "require": "./dist/memory.cjs",
28
+ "types": "./dist/memory.d.ts"
29
+ },
25
30
  "./react": {
26
31
  "import": "./dist/react.js",
27
32
  "require": "./dist/react.cjs",