@aj-2000-test/goodlogs-sdk 0.1.19 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var h={eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function m(r){let e=r.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function u(r,e){if(e)return e;let t=m(r);return h[t]||h.eu}var k=5e3,b=50,c="0.1.19",g="gl_anon_id",f="gl_session_id";function d(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function S(){let r={$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||(typeof screen<"u"&&(r.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(r.$language=navigator.language??""),typeof location<"u"&&(r.$url=location.href,r.$path=location.pathname,r.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(r.$referrer=document.referrer),document.title&&(r.$title=document.title))),r}function w(r,e){let t={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function E(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
- `);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let n=e[t]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let i=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(i){let s=i[1]||"<anonymous>",o=i[2]?.replace(/^.*[/\\]/,"")??"",a=i[3];return `${s}@${o}:${a}`}}}catch{}}function x(){if(typeof localStorage<"u"){let r=localStorage.getItem(g);if(r)return r;let e=d();return localStorage.setItem(g,e),e}return d()}function I(){if(typeof sessionStorage<"u"){let r=sessionStorage.getItem(f);if(r)return r;let e=d();return sessionStorage.setItem(f,e),e}return d()}var p=class{constructor(e){this.logBuffer=[];this.eventBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.apiKey=e.apiKey,this.endpoint=u(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??k,this.batchSize=e.batchSize??b,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.anonymousId=x(),this.sessionId=I(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture()),this.sendTelemetry("init","info"));}log(e,t,n){if(this.disabled)return;let i=65536,s=t;t.length>i&&(s=t.slice(0,i-100)+`
1
+ 'use strict';var p={eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function v(r){let e=r.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function u(r,e){if(e)return e;let t=v(r);return p[t]||p.eu}var b=5e3,k=50,c="0.1.20",g="gl_anon_id",f="gl_session_id";function d(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function S(){let r={$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||(typeof screen<"u"&&(r.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(r.$language=navigator.language??""),typeof location<"u"&&(r.$url=location.href,r.$path=location.pathname,r.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(r.$referrer=document.referrer),document.title&&(r.$title=document.title))),r}function E(r,e){let t={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function w(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
+ `);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let n=e[t]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let i=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(i){let o=i[1]||"<anonymous>",s=i[2]?.replace(/^.*[/\\]/,"")??"",a=i[3];return `${o}@${s}:${a}`}}}catch{}}function I(){if(typeof localStorage<"u"){let r=localStorage.getItem(g);if(r)return r;let e=d();return localStorage.setItem(g,e),e}return d()}function _(){if(typeof sessionStorage<"u"){let r=sessionStorage.getItem(f);if(r)return r;let e=d();return sessionStorage.setItem(f,e),e}return d()}var h=class{constructor(e){this.logBuffer=[];this.eventBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.apiKey=e.apiKey,this.endpoint=u(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??b,this.batchSize=e.batchSize??k,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.anonymousId=I(),this.sessionId=_(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture()),this.sendTelemetry("init","info"));}log(e,t,n){if(this.disabled)return;let i=65536,o=t;t.length>i&&(o=t.slice(0,i-100)+`
3
3
 
4
- [truncated \u2014 original ${t.length} chars, limit ${i}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${i} chars`)));let o={severity:e,message:s,metadata:n?.metadata,codeLocation:n?.codeLocation||E(),context:{...this.defaultContext,...w(this.sessionId,this.anonymousId),...n?.context},timestamp:new Date().toISOString()};this.logBuffer.push(o),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(g,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=d(),this.sessionId=d(),typeof localStorage<"u"&&localStorage.setItem(g,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(f,e);}track(e,t){if(this.disabled)return;let n={event:e,distinctId:t?.distinctId??this.anonymousId,properties:{...S(),...t?.properties,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(n),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n=[];e.length>0&&n.push(this.sendLogs(e)),t.length>0&&n.push(this.sendEvents(t)),await Promise.all(n);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(o=>({severity:o.severity,message:o.message,metadata:o.metadata,code_location:o.codeLocation,context:o.context,timestamp:o.timestamp}));await this.postWithRetry("/v1/logs",s,o=>{for(let a of o)this.logBuffer.push({severity:a.severity,message:a.message,metadata:a.metadata,codeLocation:a.code_location,context:a.context,timestamp:a.timestamp});});}}async sendEvents(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(o=>({event:o.event,distinctId:o.distinctId,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/events",s,o=>{for(let a of o)this.eventBuffer.push({event:a.event,distinctId:a.distinctId,properties:a.properties,timestamp:a.timestamp});});}}async postWithRetry(e,t,n,i=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(i<4){let a=Math.min(1e3*Math.pow(2,i),8e3),l=Math.random()*500;return await new Promise(y=>setTimeout(y,a+l)),this.postWithRetry(e,t,n,i+1)}this.onError(new Error(`GoodLogs rate limited after ${i} retries`));return}if(!s.ok){let a=await s.text().catch(()=>""),l=new Error(`GoodLogs API error ${s.status}: ${a}`);this.onError(l),s.status>=500&&i===0&&n(t);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let a=t.slice(o.accepted??0);a.length>0&&n(a);}}catch(s){let o=s instanceof Error?s:new Error(String(s));i===0&&n(t),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(!(typeof PerformanceObserver>"u")){try{new PerformanceObserver(e=>{let t=e.getEntries()[0];t&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let t=e.getEntries(),n=t[t.length-1];n&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(t=>{for(let n of t.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let t=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value:Math.round(e*1e3)/1e3}});};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t();});}}catch{}try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let t of e.getEntries()){let n=t.duration;n>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(n)}});}}).observe({type:"event",buffered:!0});}catch{}}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview");let e=()=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"));};if(typeof history<"u"){let t=history.pushState,n=history.replaceState;history.pushState=function(...i){t.apply(this,i),e();},history.replaceState=function(...i){n.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let n=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let i=n.getAttribute?.("data-gl-event"),s=n.tagName?.toLowerCase()??"",o=(n.textContent??"").trim().slice(0,50),a=n.getAttribute?.("href")??void 0,l=(n.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:a,$element_classes:l||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(i=>({severity:i.severity,message:i.message,metadata:i.metadata,code_location:i.codeLocation,context:i.context,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,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/${c}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...n,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var v="0.1.0";function _(r,e){let t=u(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":v};e?.token&&(n.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:v}}),keepalive:true}).catch(()=>{});}exports.GoodLogs=p;exports.REGION_URLS=h;exports.resolveEndpoint=u;exports.resolveRegion=m;exports.sendTelemetry=_;
4
+ [truncated \u2014 original ${t.length} chars, limit ${i}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${i} chars`)));let s=w(),a={severity:e,message:o,properties:{...this.defaultContext,...E(this.sessionId,this.anonymousId),...s?{code_location:s}:{},...n},timestamp:new Date().toISOString()};this.logBuffer.push(a),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(g,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=d(),this.sessionId=d(),typeof localStorage<"u"&&localStorage.setItem(g,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(f,e);}track(e,t){if(this.disabled)return;let{distinctId:n,...i}=t??{},o={event:e,distinctId:n??this.anonymousId,properties:{...S(),...i,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(o),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n=[];e.length>0&&n.push(this.sendLogs(e)),t.length>0&&n.push(this.sendEvents(t)),await Promise.all(n);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){for(let n=0;n<e.length;n+=500){let o=e.slice(n,n+500).map(s=>({severity:s.severity,message:s.message,properties:s.properties,timestamp:s.timestamp}));await this.postWithRetry("/v1/logs",o,s=>{for(let a of s)this.logBuffer.push({severity:a.severity,message:a.message,properties:a.properties,timestamp:a.timestamp});});}}async sendEvents(e){for(let n=0;n<e.length;n+=500){let o=e.slice(n,n+500).map(s=>({event:s.event,distinctId:s.distinctId,properties:s.properties,timestamp:s.timestamp}));await this.postWithRetry("/v1/events",o,s=>{for(let a of s)this.eventBuffer.push({event:a.event,distinctId:a.distinctId,properties:a.properties,timestamp:a.timestamp});});}}async postWithRetry(e,t,n,i=0){try{let o=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`},body:JSON.stringify({batch:t})});if(o.status===429||o.status===503){if(i<4){let a=Math.min(1e3*Math.pow(2,i),8e3),l=Math.random()*500;return await new Promise(y=>setTimeout(y,a+l)),this.postWithRetry(e,t,n,i+1)}this.onError(new Error(`GoodLogs rate limited after ${i} retries`));return}if(!o.ok){let a=await o.text().catch(()=>""),l=new Error(`GoodLogs API error ${o.status}: ${a}`);this.onError(l),o.status>=500&&i===0&&n(t);return}let s=await o.json().catch(()=>null);if(s&&s.rejected&&s.rejected>0){let a=t.slice(s.accepted??0);a.length>0&&n(a);}}catch(o){let s=o instanceof Error?o:new Error(String(o));i===0&&n(t),this.onError(s);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(!(typeof PerformanceObserver>"u")){try{new PerformanceObserver(e=>{let t=e.getEntries()[0];t&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let t=e.getEntries(),n=t[t.length-1];n&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(t=>{for(let n of t.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let t=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value:Math.round(e*1e3)/1e3}});};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t();});}}catch{}try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let t of e.getEntries()){let n=t.duration;n>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(n)}});}}).observe({type:"event",buffered:!0});}catch{}}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview");let e=()=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"));};if(typeof history<"u"){let t=history.pushState,n=history.replaceState;history.pushState=function(...i){t.apply(this,i),e();},history.replaceState=function(...i){n.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let n=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let i=n.getAttribute?.("data-gl-event"),o=n.tagName?.toLowerCase()??"",s=(n.textContent??"").trim().slice(0,50),a=n.getAttribute?.("href")??void 0,l=(n.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:o,$element_text:s||void 0,$element_href:a,$element_classes:l||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(i=>({severity:i.severity,message:i.message,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,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/${c}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...n,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var m="0.1.0";function $(r,e){let t=u(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":m};e?.token&&(n.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:m}}),keepalive:true}).catch(()=>{});}exports.GoodLogs=h;exports.REGION_URLS=p;exports.resolveEndpoint=u;exports.resolveRegion=v;exports.sendTelemetry=$;
package/dist/index.d.cts CHANGED
@@ -22,9 +22,7 @@ interface GoodLogsOptions {
22
22
  interface LogEntry {
23
23
  severity: Severity;
24
24
  message: string;
25
- metadata?: Record<string, unknown>;
26
- codeLocation?: string;
27
- context?: Record<string, unknown>;
25
+ properties?: Record<string, unknown>;
28
26
  timestamp?: string;
29
27
  }
30
28
  interface EventEntry {
@@ -52,36 +50,12 @@ declare class GoodLogs {
52
50
  private anonymousId;
53
51
  private sessionId;
54
52
  constructor(options: GoodLogsOptions);
55
- log(severity: Severity, message: string, opts?: {
56
- metadata?: Record<string, unknown>;
57
- codeLocation?: string;
58
- context?: Record<string, unknown>;
59
- }): void;
60
- debug(message: string, opts?: {
61
- metadata?: Record<string, unknown>;
62
- codeLocation?: string;
63
- context?: Record<string, unknown>;
64
- }): void;
65
- info(message: string, opts?: {
66
- metadata?: Record<string, unknown>;
67
- codeLocation?: string;
68
- context?: Record<string, unknown>;
69
- }): void;
70
- warn(message: string, opts?: {
71
- metadata?: Record<string, unknown>;
72
- codeLocation?: string;
73
- context?: Record<string, unknown>;
74
- }): void;
75
- error(message: string, opts?: {
76
- metadata?: Record<string, unknown>;
77
- codeLocation?: string;
78
- context?: Record<string, unknown>;
79
- }): void;
80
- fatal(message: string, opts?: {
81
- metadata?: Record<string, unknown>;
82
- codeLocation?: string;
83
- context?: Record<string, unknown>;
84
- }): void;
53
+ log(severity: Severity, message: string, properties?: Record<string, unknown>): void;
54
+ debug(message: string, properties?: Record<string, unknown>): void;
55
+ info(message: string, properties?: Record<string, unknown>): void;
56
+ warn(message: string, properties?: Record<string, unknown>): void;
57
+ error(message: string, properties?: Record<string, unknown>): void;
58
+ fatal(message: string, properties?: Record<string, unknown>): void;
85
59
  /** Set the user ID for all subsequent events. Replaces the anonymous ID. */
86
60
  identify(userId: string): void;
87
61
  /** Get the current anonymous/user ID. */
@@ -94,9 +68,8 @@ declare class GoodLogs {
94
68
  newSession(): void;
95
69
  /** Set a specific session ID. */
96
70
  setSessionId(id: string): void;
97
- track(event: string, opts?: {
71
+ track(event: string, properties?: Record<string, unknown> & {
98
72
  distinctId?: string;
99
- properties?: Record<string, unknown>;
100
73
  }): void;
101
74
  flush(): Promise<void>;
102
75
  /** Flush remaining data and stop the timer */
package/dist/index.d.ts CHANGED
@@ -22,9 +22,7 @@ interface GoodLogsOptions {
22
22
  interface LogEntry {
23
23
  severity: Severity;
24
24
  message: string;
25
- metadata?: Record<string, unknown>;
26
- codeLocation?: string;
27
- context?: Record<string, unknown>;
25
+ properties?: Record<string, unknown>;
28
26
  timestamp?: string;
29
27
  }
30
28
  interface EventEntry {
@@ -52,36 +50,12 @@ declare class GoodLogs {
52
50
  private anonymousId;
53
51
  private sessionId;
54
52
  constructor(options: GoodLogsOptions);
55
- log(severity: Severity, message: string, opts?: {
56
- metadata?: Record<string, unknown>;
57
- codeLocation?: string;
58
- context?: Record<string, unknown>;
59
- }): void;
60
- debug(message: string, opts?: {
61
- metadata?: Record<string, unknown>;
62
- codeLocation?: string;
63
- context?: Record<string, unknown>;
64
- }): void;
65
- info(message: string, opts?: {
66
- metadata?: Record<string, unknown>;
67
- codeLocation?: string;
68
- context?: Record<string, unknown>;
69
- }): void;
70
- warn(message: string, opts?: {
71
- metadata?: Record<string, unknown>;
72
- codeLocation?: string;
73
- context?: Record<string, unknown>;
74
- }): void;
75
- error(message: string, opts?: {
76
- metadata?: Record<string, unknown>;
77
- codeLocation?: string;
78
- context?: Record<string, unknown>;
79
- }): void;
80
- fatal(message: string, opts?: {
81
- metadata?: Record<string, unknown>;
82
- codeLocation?: string;
83
- context?: Record<string, unknown>;
84
- }): void;
53
+ log(severity: Severity, message: string, properties?: Record<string, unknown>): void;
54
+ debug(message: string, properties?: Record<string, unknown>): void;
55
+ info(message: string, properties?: Record<string, unknown>): void;
56
+ warn(message: string, properties?: Record<string, unknown>): void;
57
+ error(message: string, properties?: Record<string, unknown>): void;
58
+ fatal(message: string, properties?: Record<string, unknown>): void;
85
59
  /** Set the user ID for all subsequent events. Replaces the anonymous ID. */
86
60
  identify(userId: string): void;
87
61
  /** Get the current anonymous/user ID. */
@@ -94,9 +68,8 @@ declare class GoodLogs {
94
68
  newSession(): void;
95
69
  /** Set a specific session ID. */
96
70
  setSessionId(id: string): void;
97
- track(event: string, opts?: {
71
+ track(event: string, properties?: Record<string, unknown> & {
98
72
  distinctId?: string;
99
- properties?: Record<string, unknown>;
100
73
  }): void;
101
74
  flush(): Promise<void>;
102
75
  /** Flush remaining data and stop the timer */
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var h={eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function m(r){let e=r.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function u(r,e){if(e)return e;let t=m(r);return h[t]||h.eu}var k=5e3,b=50,c="0.1.19",g="gl_anon_id",f="gl_session_id";function d(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function S(){let r={$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||(typeof screen<"u"&&(r.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(r.$language=navigator.language??""),typeof location<"u"&&(r.$url=location.href,r.$path=location.pathname,r.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(r.$referrer=document.referrer),document.title&&(r.$title=document.title))),r}function w(r,e){let t={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function E(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
- `);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let n=e[t]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let i=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(i){let s=i[1]||"<anonymous>",o=i[2]?.replace(/^.*[/\\]/,"")??"",a=i[3];return `${s}@${o}:${a}`}}}catch{}}function x(){if(typeof localStorage<"u"){let r=localStorage.getItem(g);if(r)return r;let e=d();return localStorage.setItem(g,e),e}return d()}function I(){if(typeof sessionStorage<"u"){let r=sessionStorage.getItem(f);if(r)return r;let e=d();return sessionStorage.setItem(f,e),e}return d()}var p=class{constructor(e){this.logBuffer=[];this.eventBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.apiKey=e.apiKey,this.endpoint=u(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??k,this.batchSize=e.batchSize??b,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.anonymousId=x(),this.sessionId=I(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture()),this.sendTelemetry("init","info"));}log(e,t,n){if(this.disabled)return;let i=65536,s=t;t.length>i&&(s=t.slice(0,i-100)+`
1
+ var p={eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function v(r){let e=r.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function u(r,e){if(e)return e;let t=v(r);return p[t]||p.eu}var b=5e3,k=50,c="0.1.20",g="gl_anon_id",f="gl_session_id";function d(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function S(){let r={$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||(typeof screen<"u"&&(r.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(r.$language=navigator.language??""),typeof location<"u"&&(r.$url=location.href,r.$path=location.pathname,r.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(r.$referrer=document.referrer),document.title&&(r.$title=document.title))),r}function E(r,e){let t={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function w(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
+ `);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let n=e[t]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let i=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(i){let o=i[1]||"<anonymous>",s=i[2]?.replace(/^.*[/\\]/,"")??"",a=i[3];return `${o}@${s}:${a}`}}}catch{}}function I(){if(typeof localStorage<"u"){let r=localStorage.getItem(g);if(r)return r;let e=d();return localStorage.setItem(g,e),e}return d()}function _(){if(typeof sessionStorage<"u"){let r=sessionStorage.getItem(f);if(r)return r;let e=d();return sessionStorage.setItem(f,e),e}return d()}var h=class{constructor(e){this.logBuffer=[];this.eventBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.apiKey=e.apiKey,this.endpoint=u(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??b,this.batchSize=e.batchSize??k,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.anonymousId=I(),this.sessionId=_(),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture()),this.sendTelemetry("init","info"));}log(e,t,n){if(this.disabled)return;let i=65536,o=t;t.length>i&&(o=t.slice(0,i-100)+`
3
3
 
4
- [truncated \u2014 original ${t.length} chars, limit ${i}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${i} chars`)));let o={severity:e,message:s,metadata:n?.metadata,codeLocation:n?.codeLocation||E(),context:{...this.defaultContext,...w(this.sessionId,this.anonymousId),...n?.context},timestamp:new Date().toISOString()};this.logBuffer.push(o),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(g,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=d(),this.sessionId=d(),typeof localStorage<"u"&&localStorage.setItem(g,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(f,e);}track(e,t){if(this.disabled)return;let n={event:e,distinctId:t?.distinctId??this.anonymousId,properties:{...S(),...t?.properties,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(n),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n=[];e.length>0&&n.push(this.sendLogs(e)),t.length>0&&n.push(this.sendEvents(t)),await Promise.all(n);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(o=>({severity:o.severity,message:o.message,metadata:o.metadata,code_location:o.codeLocation,context:o.context,timestamp:o.timestamp}));await this.postWithRetry("/v1/logs",s,o=>{for(let a of o)this.logBuffer.push({severity:a.severity,message:a.message,metadata:a.metadata,codeLocation:a.code_location,context:a.context,timestamp:a.timestamp});});}}async sendEvents(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(o=>({event:o.event,distinctId:o.distinctId,properties:o.properties,timestamp:o.timestamp}));await this.postWithRetry("/v1/events",s,o=>{for(let a of o)this.eventBuffer.push({event:a.event,distinctId:a.distinctId,properties:a.properties,timestamp:a.timestamp});});}}async postWithRetry(e,t,n,i=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(i<4){let a=Math.min(1e3*Math.pow(2,i),8e3),l=Math.random()*500;return await new Promise(y=>setTimeout(y,a+l)),this.postWithRetry(e,t,n,i+1)}this.onError(new Error(`GoodLogs rate limited after ${i} retries`));return}if(!s.ok){let a=await s.text().catch(()=>""),l=new Error(`GoodLogs API error ${s.status}: ${a}`);this.onError(l),s.status>=500&&i===0&&n(t);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let a=t.slice(o.accepted??0);a.length>0&&n(a);}}catch(s){let o=s instanceof Error?s:new Error(String(s));i===0&&n(t),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(!(typeof PerformanceObserver>"u")){try{new PerformanceObserver(e=>{let t=e.getEntries()[0];t&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let t=e.getEntries(),n=t[t.length-1];n&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(t=>{for(let n of t.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let t=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value:Math.round(e*1e3)/1e3}});};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t();});}}catch{}try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let t of e.getEntries()){let n=t.duration;n>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(n)}});}}).observe({type:"event",buffered:!0});}catch{}}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview");let e=()=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"));};if(typeof history<"u"){let t=history.pushState,n=history.replaceState;history.pushState=function(...i){t.apply(this,i),e();},history.replaceState=function(...i){n.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let n=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let i=n.getAttribute?.("data-gl-event"),s=n.tagName?.toLowerCase()??"",o=(n.textContent??"").trim().slice(0,50),a=n.getAttribute?.("href")??void 0,l=(n.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:a,$element_classes:l||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(i=>({severity:i.severity,message:i.message,metadata:i.metadata,code_location:i.codeLocation,context:i.context,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,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/${c}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...n,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var v="0.1.0";function _(r,e){let t=u(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":v};e?.token&&(n.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:v}}),keepalive:true}).catch(()=>{});}export{p as GoodLogs,h as REGION_URLS,u as resolveEndpoint,m as resolveRegion,_ as sendTelemetry};
4
+ [truncated \u2014 original ${t.length} chars, limit ${i}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${i} chars`)));let s=w(),a={severity:e,message:o,properties:{...this.defaultContext,...E(this.sessionId,this.anonymousId),...s?{code_location:s}:{},...n},timestamp:new Date().toISOString()};this.logBuffer.push(a),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(g,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=d(),this.sessionId=d(),typeof localStorage<"u"&&localStorage.setItem(g,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(f,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(f,e);}track(e,t){if(this.disabled)return;let{distinctId:n,...i}=t??{},o={event:e,distinctId:n??this.anonymousId,properties:{...S(),...i,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(o),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n=[];e.length>0&&n.push(this.sendLogs(e)),t.length>0&&n.push(this.sendEvents(t)),await Promise.all(n);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){for(let n=0;n<e.length;n+=500){let o=e.slice(n,n+500).map(s=>({severity:s.severity,message:s.message,properties:s.properties,timestamp:s.timestamp}));await this.postWithRetry("/v1/logs",o,s=>{for(let a of s)this.logBuffer.push({severity:a.severity,message:a.message,properties:a.properties,timestamp:a.timestamp});});}}async sendEvents(e){for(let n=0;n<e.length;n+=500){let o=e.slice(n,n+500).map(s=>({event:s.event,distinctId:s.distinctId,properties:s.properties,timestamp:s.timestamp}));await this.postWithRetry("/v1/events",o,s=>{for(let a of s)this.eventBuffer.push({event:a.event,distinctId:a.distinctId,properties:a.properties,timestamp:a.timestamp});});}}async postWithRetry(e,t,n,i=0){try{let o=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`},body:JSON.stringify({batch:t})});if(o.status===429||o.status===503){if(i<4){let a=Math.min(1e3*Math.pow(2,i),8e3),l=Math.random()*500;return await new Promise(y=>setTimeout(y,a+l)),this.postWithRetry(e,t,n,i+1)}this.onError(new Error(`GoodLogs rate limited after ${i} retries`));return}if(!o.ok){let a=await o.text().catch(()=>""),l=new Error(`GoodLogs API error ${o.status}: ${a}`);this.onError(l),o.status>=500&&i===0&&n(t);return}let s=await o.json().catch(()=>null);if(s&&s.rejected&&s.rejected>0){let a=t.slice(s.accepted??0);a.length>0&&n(a);}}catch(o){let s=o instanceof Error?o:new Error(String(o));i===0&&n(t),this.onError(s);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(!(typeof PerformanceObserver>"u")){try{new PerformanceObserver(e=>{let t=e.getEntries()[0];t&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let t=e.getEntries(),n=t[t.length-1];n&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(t=>{for(let n of t.getEntries())n.hadRecentInput||(e+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let t=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value:Math.round(e*1e3)/1e3}});};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t();});}}catch{}try{if(typeof performance<"u"){let e=performance.getEntriesByType?.("navigation")?.[0];e?.responseStart&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let t of e.getEntries()){let n=t.duration;n>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(n)}});}}).observe({type:"event",buffered:!0});}catch{}}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview");let e=()=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"));};if(typeof history<"u"){let t=history.pushState,n=history.replaceState;history.pushState=function(...i){t.apply(this,i),e();},history.replaceState=function(...i){n.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let n=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let i=n.getAttribute?.("data-gl-event"),o=n.tagName?.toLowerCase()??"",s=(n.textContent??"").trim().slice(0,50),a=n.getAttribute?.("href")??void 0,l=(n.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:o,$element_text:s||void 0,$element_href:a,$element_classes:l||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(i=>({severity:i.severity,message:i.message,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,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/${c}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...n,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var m="0.1.0";function $(r,e){let t=u(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":m};e?.token&&(n.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:m}}),keepalive:true}).catch(()=>{});}export{h as GoodLogs,p as REGION_URLS,u as resolveEndpoint,v as resolveRegion,$ as sendTelemetry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aj-2000-test/goodlogs-sdk",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "description": "GoodLogs SDK — send logs and events to GoodLogs from Node.js and browsers",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",