@aj-2000-test/goodlogs-sdk 0.1.15 → 0.1.16

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,2 +1,2 @@
1
- 'use strict';var f={eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function h(r){let e=r.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function l(r,e){if(e)return e;let n=h(r);return f[n]||f.eu}var y=5e3,b=50,c="0.1.15",g="gl_anon_id",u="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 k(){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 S(r,e){let n={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(n.$url=location.href,n.$path=location.pathname),n}function w(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
- `);if(!e)return;for(let n=3;n<Math.min(e.length,8);n++){let t=e[n]?.trim();if(!t||t.includes("goodlogs")&&(t.includes("client.")||t.includes("index.")))continue;let i=t.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(u);if(r)return r;let e=d();return sessionStorage.setItem(u,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=l(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??y,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,n,t){if(this.disabled)return;let i={severity:e,message:n,metadata:t?.metadata,codeLocation:t?.codeLocation||w(),context:{...this.defaultContext,...S(this.sessionId,this.anonymousId),...t?.context},timestamp:new Date().toISOString()};this.logBuffer.push(i),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,n){this.log("debug",e,n);}info(e,n){this.log("info",e,n);}warn(e,n){this.log("warn",e,n);}error(e,n){this.log("error",e,n);}fatal(e,n){this.log("fatal",e,n);}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(u,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(u,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(u,e);}track(e,n){if(this.disabled)return;let t={event:e,distinctId:n?.distinctId??this.anonymousId,properties:{...k(),...n?.properties,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(t),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),n=this.eventBuffer.splice(0),t=[];e.length>0&&t.push(this.sendLogs(e)),n.length>0&&t.push(this.sendEvents(n)),await Promise.all(t);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){let n=e.map(t=>({severity:t.severity,message:t.message,metadata:t.metadata,code_location:t.codeLocation,context:t.context,timestamp:t.timestamp}));await this.postWithRetry("/v1/logs",n,t=>{for(let i of t)this.logBuffer.push({severity:i.severity,message:i.message,metadata:i.metadata,codeLocation:i.code_location,context:i.context,timestamp:i.timestamp});});}async sendEvents(e){let n=e.map(t=>({event:t.event,distinctId:t.distinctId,properties:t.properties,timestamp:t.timestamp}));await this.postWithRetry("/v1/events",n,t=>{for(let i of t)this.eventBuffer.push({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp});});}async postWithRetry(e,n,t,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:n})});if(s.status===429||s.status===503){if(i<2)return await new Promise(a=>setTimeout(a,1e3*(i+1))),this.postWithRetry(e,n,t,i+1);t(n);return}if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`GoodLogs API error ${s.status}: ${a}`)}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let a=n.slice(o.accepted??0);a.length>0&&t(a);}}catch(s){let o=s instanceof Error?s:new Error(String(s));i===0&&t(n),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 n=e.getEntries()[0];n&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let n=e.getEntries(),t=n[n.length-1];t&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(n=>{for(let t of n.getEntries())t.hadRecentInput||(e+=t.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value: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&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let n of e.getEntries()){let t=n.duration;t>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(t)}});}}).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 n=history.pushState,t=history.replaceState;history.pushState=function(...i){n.apply(this,i),e();},history.replaceState=function(...i){t.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!t)return;let i=t.getAttribute?.("data-gl-event"),s=t.tagName?.toLowerCase()??"",o=(t.textContent??"").trim().slice(0,50),a=t.getAttribute?.("href")??void 0,v=(t.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:a,$element_classes:v||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),n=this.eventBuffer.splice(0),t={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:t,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(()=>{}),n.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:t,body:JSON.stringify({batch:n.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,n,t){!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:n,metadata:{...t,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var m="0.1.0";function E(r,e){let n=l(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),t={"Content-Type":"application/json","X-GoodLogs-SDK":m};e?.token&&(t.Authorization=`Bearer ${e.token}`),fetch(`${n}/v1/telemetry`,{method:"POST",headers:t,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:m}}),keepalive:true}).catch(()=>{});}exports.GoodLogs=p;exports.REGION_URLS=f;exports.resolveEndpoint=l;exports.resolveRegion=h;exports.sendTelemetry=E;
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 m(r){let e=r.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function l(r,e){if(e)return e;let n=m(r);return p[n]||p.eu}var y=5e3,k=50,c="0.1.16",f="gl_anon_id",u="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 b(){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 S(r,e){let n={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(n.$url=location.href,n.$path=location.pathname),n}function w(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
+ `);if(!e)return;for(let n=3;n<Math.min(e.length,8);n++){let t=e[n]?.trim();if(!t||t.includes("goodlogs")&&(t.includes("client.")||t.includes("index.")))continue;let i=t.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(f);if(r)return r;let e=d();return localStorage.setItem(f,e),e}return d()}function I(){if(typeof sessionStorage<"u"){let r=sessionStorage.getItem(u);if(r)return r;let e=d();return sessionStorage.setItem(u,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=l(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??y,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=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,n,t){if(this.disabled)return;let i={severity:e,message:n,metadata:t?.metadata,codeLocation:t?.codeLocation||w(),context:{...this.defaultContext,...S(this.sessionId,this.anonymousId),...t?.context},timestamp:new Date().toISOString()};this.logBuffer.push(i),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,n){this.log("debug",e,n);}info(e,n){this.log("info",e,n);}warn(e,n){this.log("warn",e,n);}error(e,n){this.log("error",e,n);}fatal(e,n){this.log("fatal",e,n);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(f,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=d(),this.sessionId=d(),typeof localStorage<"u"&&localStorage.setItem(f,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(u,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(u,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(u,e);}track(e,n){if(this.disabled)return;let t={event:e,distinctId:n?.distinctId??this.anonymousId,properties:{...b(),...n?.properties,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(t),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),n=this.eventBuffer.splice(0),t=[];e.length>0&&t.push(this.sendLogs(e)),n.length>0&&t.push(this.sendEvents(n)),await Promise.all(t);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){let n=e.map(t=>({severity:t.severity,message:t.message,metadata:t.metadata,code_location:t.codeLocation,context:t.context,timestamp:t.timestamp}));await this.postWithRetry("/v1/logs",n,t=>{for(let i of t)this.logBuffer.push({severity:i.severity,message:i.message,metadata:i.metadata,codeLocation:i.code_location,context:i.context,timestamp:i.timestamp});});}async sendEvents(e){let n=e.map(t=>({event:t.event,distinctId:t.distinctId,properties:t.properties,timestamp:t.timestamp}));await this.postWithRetry("/v1/events",n,t=>{for(let i of t)this.eventBuffer.push({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp});});}async postWithRetry(e,n,t,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:n})});if(s.status===429||s.status===503){if(i<2)return await new Promise(a=>setTimeout(a,1e3*(i+1))),this.postWithRetry(e,n,t,i+1);t(n);return}if(!s.ok){let a=await s.text().catch(()=>""),g=new Error(`GoodLogs API error ${s.status}: ${a}`);this.onError(g),s.status>=500&&i===0&&t(n);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let a=n.slice(o.accepted??0);a.length>0&&t(a);}}catch(s){let o=s instanceof Error?s:new Error(String(s));i===0&&t(n),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 n=e.getEntries()[0];n&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let n=e.getEntries(),t=n[n.length-1];t&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(n=>{for(let t of n.getEntries())t.hadRecentInput||(e+=t.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value: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&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let n of e.getEntries()){let t=n.duration;t>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(t)}});}}).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 n=history.pushState,t=history.replaceState;history.pushState=function(...i){n.apply(this,i),e();},history.replaceState=function(...i){t.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!t)return;let i=t.getAttribute?.("data-gl-event"),s=t.tagName?.toLowerCase()??"",o=(t.textContent??"").trim().slice(0,50),a=t.getAttribute?.("href")??void 0,g=(t.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:a,$element_classes:g||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),n=this.eventBuffer.splice(0),t={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:t,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(()=>{}),n.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:t,body:JSON.stringify({batch:n.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,n,t){!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:n,metadata:{...t,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var v="0.1.0";function E(r,e){let n=l(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),t={"Content-Type":"application/json","X-GoodLogs-SDK":v};e?.token&&(t.Authorization=`Bearer ${e.token}`),fetch(`${n}/v1/telemetry`,{method:"POST",headers:t,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:v}}),keepalive:true}).catch(()=>{});}exports.GoodLogs=h;exports.REGION_URLS=p;exports.resolveEndpoint=l;exports.resolveRegion=m;exports.sendTelemetry=E;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var f={eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function h(r){let e=r.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function l(r,e){if(e)return e;let n=h(r);return f[n]||f.eu}var y=5e3,b=50,c="0.1.15",g="gl_anon_id",u="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 k(){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 S(r,e){let n={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(n.$url=location.href,n.$path=location.pathname),n}function w(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
- `);if(!e)return;for(let n=3;n<Math.min(e.length,8);n++){let t=e[n]?.trim();if(!t||t.includes("goodlogs")&&(t.includes("client.")||t.includes("index.")))continue;let i=t.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(u);if(r)return r;let e=d();return sessionStorage.setItem(u,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=l(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??y,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,n,t){if(this.disabled)return;let i={severity:e,message:n,metadata:t?.metadata,codeLocation:t?.codeLocation||w(),context:{...this.defaultContext,...S(this.sessionId,this.anonymousId),...t?.context},timestamp:new Date().toISOString()};this.logBuffer.push(i),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,n){this.log("debug",e,n);}info(e,n){this.log("info",e,n);}warn(e,n){this.log("warn",e,n);}error(e,n){this.log("error",e,n);}fatal(e,n){this.log("fatal",e,n);}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(u,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(u,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(u,e);}track(e,n){if(this.disabled)return;let t={event:e,distinctId:n?.distinctId??this.anonymousId,properties:{...k(),...n?.properties,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(t),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),n=this.eventBuffer.splice(0),t=[];e.length>0&&t.push(this.sendLogs(e)),n.length>0&&t.push(this.sendEvents(n)),await Promise.all(t);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){let n=e.map(t=>({severity:t.severity,message:t.message,metadata:t.metadata,code_location:t.codeLocation,context:t.context,timestamp:t.timestamp}));await this.postWithRetry("/v1/logs",n,t=>{for(let i of t)this.logBuffer.push({severity:i.severity,message:i.message,metadata:i.metadata,codeLocation:i.code_location,context:i.context,timestamp:i.timestamp});});}async sendEvents(e){let n=e.map(t=>({event:t.event,distinctId:t.distinctId,properties:t.properties,timestamp:t.timestamp}));await this.postWithRetry("/v1/events",n,t=>{for(let i of t)this.eventBuffer.push({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp});});}async postWithRetry(e,n,t,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:n})});if(s.status===429||s.status===503){if(i<2)return await new Promise(a=>setTimeout(a,1e3*(i+1))),this.postWithRetry(e,n,t,i+1);t(n);return}if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`GoodLogs API error ${s.status}: ${a}`)}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let a=n.slice(o.accepted??0);a.length>0&&t(a);}}catch(s){let o=s instanceof Error?s:new Error(String(s));i===0&&t(n),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 n=e.getEntries()[0];n&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let n=e.getEntries(),t=n[n.length-1];t&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(n=>{for(let t of n.getEntries())t.hadRecentInput||(e+=t.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value: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&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let n of e.getEntries()){let t=n.duration;t>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(t)}});}}).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 n=history.pushState,t=history.replaceState;history.pushState=function(...i){n.apply(this,i),e();},history.replaceState=function(...i){t.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!t)return;let i=t.getAttribute?.("data-gl-event"),s=t.tagName?.toLowerCase()??"",o=(t.textContent??"").trim().slice(0,50),a=t.getAttribute?.("href")??void 0,v=(t.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:a,$element_classes:v||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),n=this.eventBuffer.splice(0),t={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:t,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(()=>{}),n.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:t,body:JSON.stringify({batch:n.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,n,t){!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:n,metadata:{...t,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var m="0.1.0";function E(r,e){let n=l(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),t={"Content-Type":"application/json","X-GoodLogs-SDK":m};e?.token&&(t.Authorization=`Bearer ${e.token}`),fetch(`${n}/v1/telemetry`,{method:"POST",headers:t,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:m}}),keepalive:true}).catch(()=>{});}export{p as GoodLogs,f as REGION_URLS,l as resolveEndpoint,h as resolveRegion,E as sendTelemetry};
1
+ var p={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 l(r,e){if(e)return e;let n=m(r);return p[n]||p.eu}var y=5e3,k=50,c="0.1.16",f="gl_anon_id",u="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 b(){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 S(r,e){let n={$session_id:r,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:c};return typeof navigator>"u"||typeof location<"u"&&(n.$url=location.href,n.$path=location.pathname),n}function w(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
2
+ `);if(!e)return;for(let n=3;n<Math.min(e.length,8);n++){let t=e[n]?.trim();if(!t||t.includes("goodlogs")&&(t.includes("client.")||t.includes("index.")))continue;let i=t.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(f);if(r)return r;let e=d();return localStorage.setItem(f,e),e}return d()}function I(){if(typeof sessionStorage<"u"){let r=sessionStorage.getItem(u);if(r)return r;let e=d();return sessionStorage.setItem(u,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=l(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??y,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=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,n,t){if(this.disabled)return;let i={severity:e,message:n,metadata:t?.metadata,codeLocation:t?.codeLocation||w(),context:{...this.defaultContext,...S(this.sessionId,this.anonymousId),...t?.context},timestamp:new Date().toISOString()};this.logBuffer.push(i),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,n){this.log("debug",e,n);}info(e,n){this.log("info",e,n);}warn(e,n){this.log("warn",e,n);}error(e,n){this.log("error",e,n);}fatal(e,n){this.log("fatal",e,n);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(f,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=d(),this.sessionId=d(),typeof localStorage<"u"&&localStorage.setItem(f,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(u,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=d(),typeof sessionStorage<"u"&&sessionStorage.setItem(u,this.sessionId);}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(u,e);}track(e,n){if(this.disabled)return;let t={event:e,distinctId:n?.distinctId??this.anonymousId,properties:{...b(),...n?.properties,$session_id:this.sessionId},timestamp:new Date().toISOString()};this.eventBuffer.push(t),this.eventBuffer.length>=this.batchSize&&this.flush();}async flush(){let e=this.logBuffer.splice(0),n=this.eventBuffer.splice(0),t=[];e.length>0&&t.push(this.sendLogs(e)),n.length>0&&t.push(this.sendEvents(n)),await Promise.all(t);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),await this.flush();}async sendLogs(e){let n=e.map(t=>({severity:t.severity,message:t.message,metadata:t.metadata,code_location:t.codeLocation,context:t.context,timestamp:t.timestamp}));await this.postWithRetry("/v1/logs",n,t=>{for(let i of t)this.logBuffer.push({severity:i.severity,message:i.message,metadata:i.metadata,codeLocation:i.code_location,context:i.context,timestamp:i.timestamp});});}async sendEvents(e){let n=e.map(t=>({event:t.event,distinctId:t.distinctId,properties:t.properties,timestamp:t.timestamp}));await this.postWithRetry("/v1/events",n,t=>{for(let i of t)this.eventBuffer.push({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp});});}async postWithRetry(e,n,t,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:n})});if(s.status===429||s.status===503){if(i<2)return await new Promise(a=>setTimeout(a,1e3*(i+1))),this.postWithRetry(e,n,t,i+1);t(n);return}if(!s.ok){let a=await s.text().catch(()=>""),g=new Error(`GoodLogs API error ${s.status}: ${a}`);this.onError(g),s.status>=500&&i===0&&t(n);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let a=n.slice(o.accepted??0);a.length>0&&t(a);}}catch(s){let o=s instanceof Error?s:new Error(String(s));i===0&&t(n),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 n=e.getEntries()[0];n&&this.track("$web_vital",{properties:{$metric:"FCP",$value_ms:Math.round(n.startTime)}});}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(e=>{let n=e.getEntries(),t=n[n.length-1];t&&this.track("$web_vital",{properties:{$metric:"LCP",$value_ms:Math.round(t.startTime)}});}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let e=0;if(new PerformanceObserver(n=>{for(let t of n.getEntries())t.hadRecentInput||(e+=t.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{e>0&&this.track("$web_vital",{properties:{$metric:"CLS",$value: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&&this.track("$web_vital",{properties:{$metric:"TTFB",$value_ms:Math.round(e.responseStart)}});}}catch{}try{new PerformanceObserver(e=>{for(let n of e.getEntries()){let t=n.duration;t>0&&this.track("$web_vital",{properties:{$metric:"INP",$value_ms:Math.round(t)}});}}).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 n=history.pushState,t=history.replaceState;history.pushState=function(...i){n.apply(this,i),e();},history.replaceState=function(...i){t.apply(this,i),e();};}typeof addEventListener<"u"&&addEventListener("popstate",e);}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!t)return;let i=t.getAttribute?.("data-gl-event"),s=t.tagName?.toLowerCase()??"",o=(t.textContent??"").trim().slice(0,50),a=t.getAttribute?.("href")??void 0,g=(t.className??"").toString().slice(0,80);this.track(i||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:a,$element_classes:g||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),n=this.eventBuffer.splice(0),t={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${c}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:t,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(()=>{}),n.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:t,body:JSON.stringify({batch:n.map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,n,t){!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:n,metadata:{...t,sdk_version:c}}),keepalive:true}).catch(()=>{});}};var v="0.1.0";function E(r,e){let n=l(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),t={"Content-Type":"application/json","X-GoodLogs-SDK":v};e?.token&&(t.Authorization=`Bearer ${e.token}`),fetch(`${n}/v1/telemetry`,{method:"POST",headers:t,body:JSON.stringify({source:r.source,event:r.event,level:r.level??"info",metadata:{...r.metadata,sdk_version:v}}),keepalive:true}).catch(()=>{});}export{h as GoodLogs,p as REGION_URLS,l as resolveEndpoint,m as resolveRegion,E as sendTelemetry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aj-2000-test/goodlogs-sdk",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
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",