@ultron-dev/tracker 0.1.1 → 0.1.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/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var Z=Object.defineProperty,J=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var B=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var H=(t,e,r)=>e in t?Z(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))te.call(e,r)&&H(t,r,e[r]);if(B)for(var r of B(e))re.call(e,r)&&H(t,r,e[r]);return t},D=(t,e)=>J(t,ee(e));var V="__ultron_sid__";function F(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var b=null;function m(){if(b)return b;try{let t=sessionStorage.getItem(V);if(t)return b=t,t;let e=F();return sessionStorage.setItem(V,e),b=e,e}catch(t){return b||(b=F()),b}}function y(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function w(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function E(){var t;try{let e=window.innerWidth,r=window.innerHeight,o=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${o}`}catch(e){return ""}}function v(){var t,e;try{let o=navigator.connection;return o&&(e=(t=o.type)!=null?t:o.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var O=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},o=`${this.config.endpoint}/api/ingest`;try{let u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!u.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",u.status);}catch(u){this.config.debug&&console.warn("[Ultron] Flush error:",u),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,o={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(o)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(u){this.config.debug&&console.warn("[Ultron] flushSync error:",u);}}};var R={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},L=500,X=["image/","audio/","video/","font/","application/octet-stream"];function P(t,e,r){return e?"cors":t>=500?"server_error":t>=400?"client_error":r?"slow":"network_failure"}function ne(t){try{let e=new URL(t);return e.origin===window.location.origin?e.pathname+(e.search||""):t}catch(e){return t}}function q(t){try{let e=Object.fromEntries(new URL(t).searchParams.entries());return Object.keys(e).length>0?e:null}catch(e){return null}}function U(t){try{return new URL(t).pathname}catch(e){return t.split("?")[0]}}async function oe(t){var e;try{let r=(e=t.headers.get("content-type"))!=null?e:"";if(X.some(n=>r.includes(n)))return null;let u=await t.clone().text();return u.slice(0,L)+(u.length>L?"\u2026":"")}catch(r){return null}}function j(t){try{let r=performance.getEntriesByType("resource").filter(o=>o.name===t).pop();return !r||!r.responseEnd?null:{dns:Math.round(r.domainLookupEnd-r.domainLookupStart),tcp:Math.round(r.connectEnd-r.connectStart),tls:r.secureConnectionStart>0?Math.round(r.connectEnd-r.secureConnectionStart):0,ttfb:Math.round(r.responseStart-r.requestStart),transfer:Math.round(r.responseEnd-r.responseStart),total:Math.round(r.responseEnd-r.startTime)}}catch(e){return null}}function I(t,e,r,o,u){var i,c;let n=ne(e),s=`${o}ms`;switch(u){case "cors":return `CORS blocked: ${t} ${n}`;case "server_error":return `Server error ${r} (${(i=R[r])!=null?i:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "client_error":return `Client error ${r} (${(c=R[r])!=null?c:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "slow":return `Slow response: ${t} ${n} \u2014 ${s}`;case "network_failure":return `Network failure: ${t} ${n}`}}function $(t,e){let r=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:e,timestamp:Date.now()}}function K(t){try{return t.startsWith("http")?new URL(t).origin!==window.location.origin:!1}catch(e){return false}}function ie(t,e){return K(t)&&(e.includes("Failed to fetch")||e.includes("NetworkError")||e.includes("Load failed"))}function Q(t,e){try{let r=new URL(e).hostname,o=t.startsWith("http")?new URL(t).hostname:null;if(o&&o===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function G(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,o=window.fetch.bind(window);window.fetch=async function(i,c){var k;let a=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(Q(a,e.endpoint))return o(i,c);let S=((k=c==null?void 0:c.method)!=null?k:i instanceof Request?i.method:"GET").toUpperCase(),_=Date.now();try{let d=await o(i,c),l=Date.now()-_,f=l>r;if(!d.ok||f){let p=d.ok?0:d.status,h=P(p,!1,f);oe(d).then(T=>{var x;t.enqueue($(I(S,a,p,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:p,status_text:(x=R[p])!=null?x:null,duration:l,slow:f,cors:!1,response_body:T,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));});}return d}catch(d){let l=Date.now()-_,f=String(d),p=ie(a,f),h=P(0,p,false);throw t.enqueue($(I(S,a,0,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:0,status_text:null,duration:l,slow:false,cors:p,error:f,response_body:null,timing:null,page:window.location.pathname,referrer:document.referrer||null})),d}};let u=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,c,...a){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(c),u.call(this,i,c,...a)},XMLHttpRequest.prototype.send=function(...i){var _,k;let c=(_=this.__ultron_method)!=null?_:"GET",a=(k=this.__ultron_url)!=null?k:"",S=Date.now();return Q(a,e.endpoint)||this.addEventListener("loadend",()=>{var h,T;let d=Date.now()-S,l=this.status,f=d>r,p=l===0&&K(a);if(l===0||l>=400||f){let x=P(l,p,f),M=null;try{let N=(h=this.getResponseHeader("content-type"))!=null?h:"";!X.some(Y=>N.includes(Y))&&typeof this.responseText=="string"&&(M=this.responseText.slice(0,L)+(this.responseText.length>L?"\u2026":""));}catch(N){}t.enqueue($(I(c,a,l,d,x),{category:x,endpoint:U(a),request_url:a,params:q(a),method:c,status:l,status_text:(T=R[l])!=null?T:null,duration:d,slow:f,cors:p,response_body:M,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));}}),n.apply(this,i)};}var se={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function ae(t,e,r){let o=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function ce(t,e){let r=se[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function W(t,e){var u;let r=(u=e.reportAllVitals)!=null?u:false;function o(n,s){let i=ce(n,s);(r||i!=="good")&&t.enqueue(ae(n,s,i));}if(typeof PerformanceObserver!="undefined"){try{let n=0,s=new PerformanceObserver(i=>{let c=i.getEntries();n=c[c.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("LCP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.hadRecentInput||(n+=a.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(o("CLS",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.duration>n&&(n=a.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("INP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(o("FCP",i.startTime),n.disconnect());});n.observe({type:"paint",buffered:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries()){let c=i;o("TTFB",c.responseStart-c.requestStart),n.disconnect();}});n.observe({type:"navigation",buffered:!0});}catch(n){}}}var ue=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function z(t,e){let r=navigator.userAgent;function o(u){let n=u.target;if(!n||!ue.has(n.tagName))return;let s=n.src||n.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${n.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:{tag:n.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",o,true),()=>window.removeEventListener("error",o,true)}var C=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new O(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=z(this.queue,this.config),G(this.queue,this.config),W(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let o=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,o,u,n,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,o,u,n,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let o=r.reason,u=o instanceof Error?o:new Error(String(o));e.capturing||e.captureError(u);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var g=null;function Pe(t){if(g&&g.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=D(A({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return g=new C(e),g.init(),g}function qe(t,e){if(!g){console.warn("[Ultron] captureError called before initTracker");return}g.captureError(t,e);}function Ue(){g&&(g.destroy(),g=null);}
|
|
1
|
+
'use strict';var Z=Object.defineProperty,J=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var B=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var H=(t,e,r)=>e in t?Z(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))te.call(e,r)&&H(t,r,e[r]);if(B)for(var r of B(e))re.call(e,r)&&H(t,r,e[r]);return t},D=(t,e)=>J(t,ee(e));var V="__ultron_sid__";function F(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var b=null;function m(){if(b)return b;try{let t=sessionStorage.getItem(V);if(t)return b=t,t;let e=F();return sessionStorage.setItem(V,e),b=e,e}catch(t){return b||(b=F()),b}}function y(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function w(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function E(){var t;try{let e=window.innerWidth,r=window.innerHeight,o=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${o}`}catch(e){return ""}}function v(){var t,e;try{let o=navigator.connection;return o&&(e=(t=o.type)!=null?t:o.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var O=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},o=`${this.config.endpoint}/api/ingest`;try{let u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!u.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",u.status);}catch(u){this.config.debug&&console.warn("[Ultron] Flush error:",u),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,o={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(o)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(u){this.config.debug&&console.warn("[Ultron] flushSync error:",u);}}};var R={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},L=500,X=["image/","audio/","video/","font/","application/octet-stream"];function P(t,e,r){return e?"cors":t>=500?"server_error":t>=400?"client_error":r?"slow":"network_failure"}function ne(t){try{let e=new URL(t);return e.origin===window.location.origin?e.pathname+(e.search||""):t}catch(e){return t}}function q(t){try{let e=Object.fromEntries(new URL(t).searchParams.entries());return Object.keys(e).length>0?e:null}catch(e){return null}}function U(t){try{return new URL(t).pathname}catch(e){return t.split("?")[0]}}async function oe(t){var e;try{let r=(e=t.headers.get("content-type"))!=null?e:"";if(X.some(n=>r.includes(n)))return null;let u=await t.clone().text();return u.slice(0,L)+(u.length>L?"\u2026":"")}catch(r){return null}}function j(t){try{let r=performance.getEntriesByType("resource").filter(o=>o.name===t).pop();return !r||!r.responseEnd||r.responseStart===0?null:{dns:Math.round(r.domainLookupEnd-r.domainLookupStart),tcp:Math.round(r.connectEnd-r.connectStart),tls:r.secureConnectionStart>0?Math.round(r.connectEnd-r.secureConnectionStart):0,ttfb:Math.round(r.responseStart-r.requestStart),transfer:Math.round(r.responseEnd-r.responseStart),total:Math.round(r.responseEnd-r.startTime)}}catch(e){return null}}function I(t,e,r,o,u){var i,c;let n=ne(e),s=`${o}ms`;switch(u){case "cors":return `CORS blocked: ${t} ${n}`;case "server_error":return `Server error ${r} (${(i=R[r])!=null?i:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "client_error":return `Client error ${r} (${(c=R[r])!=null?c:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "slow":return `Slow response: ${t} ${n} \u2014 ${s}`;case "network_failure":return `Network failure: ${t} ${n}`}}function $(t,e){let r=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:e,timestamp:Date.now()}}function K(t){try{return t.startsWith("http")?new URL(t).origin!==window.location.origin:!1}catch(e){return false}}function ie(t,e){return K(t)&&(e.includes("Failed to fetch")||e.includes("NetworkError")||e.includes("Load failed"))}function Q(t,e){try{let r=new URL(e).hostname,o=t.startsWith("http")?new URL(t).hostname:null;if(o&&o===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function G(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,o=window.fetch.bind(window);window.fetch=async function(i,c){var k;let a=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(Q(a,e.endpoint))return o(i,c);let S=((k=c==null?void 0:c.method)!=null?k:i instanceof Request?i.method:"GET").toUpperCase(),_=Date.now();try{let d=await o(i,c),l=Date.now()-_,f=l>r;if(!d.ok||f){let p=d.ok?0:d.status,h=P(p,!1,f);oe(d).then(T=>{var x;t.enqueue($(I(S,a,p,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:p,status_text:(x=R[p])!=null?x:null,duration:l,slow:f,cors:!1,response_body:T,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));});}return d}catch(d){let l=Date.now()-_,f=String(d),p=ie(a,f),h=P(0,p,false);throw t.enqueue($(I(S,a,0,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:0,status_text:null,duration:l,slow:false,cors:p,error:f,response_body:null,timing:null,page:window.location.pathname,referrer:document.referrer||null})),d}};let u=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,c,...a){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(c),u.call(this,i,c,...a)},XMLHttpRequest.prototype.send=function(...i){var _,k;let c=(_=this.__ultron_method)!=null?_:"GET",a=(k=this.__ultron_url)!=null?k:"",S=Date.now();return Q(a,e.endpoint)||this.addEventListener("loadend",()=>{var h,T;let d=Date.now()-S,l=this.status,f=d>r,p=l===0&&K(a);if(l===0||l>=400||f){let x=P(l,p,f),M=null;try{let N=(h=this.getResponseHeader("content-type"))!=null?h:"";!X.some(Y=>N.includes(Y))&&typeof this.responseText=="string"&&(M=this.responseText.slice(0,L)+(this.responseText.length>L?"\u2026":""));}catch(N){}t.enqueue($(I(c,a,l,d,x),{category:x,endpoint:U(a),request_url:a,params:q(a),method:c,status:l,status_text:(T=R[l])!=null?T:null,duration:d,slow:f,cors:p,response_body:M,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));}}),n.apply(this,i)};}var se={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function ae(t,e,r){let o=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function ce(t,e){let r=se[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function W(t,e){var u;let r=(u=e.reportAllVitals)!=null?u:false;function o(n,s){let i=ce(n,s);(r||i!=="good")&&t.enqueue(ae(n,s,i));}if(typeof PerformanceObserver!="undefined"){try{let n=0,s=new PerformanceObserver(i=>{let c=i.getEntries();n=c[c.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("LCP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.hadRecentInput||(n+=a.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(o("CLS",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.duration>n&&(n=a.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("INP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(o("FCP",i.startTime),n.disconnect());});n.observe({type:"paint",buffered:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries()){let c=i;o("TTFB",c.responseStart-c.requestStart),n.disconnect();}});n.observe({type:"navigation",buffered:!0});}catch(n){}}}var ue=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function z(t,e){let r=navigator.userAgent;function o(u){let n=u.target;if(!n||!ue.has(n.tagName))return;let s=n.src||n.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${n.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:{tag:n.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",o,true),()=>window.removeEventListener("error",o,true)}var C=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new O(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=z(this.queue,this.config),G(this.queue,this.config),W(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let o=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,o,u,n,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,o,u,n,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let o=r.reason,u=o instanceof Error?o:new Error(String(o));e.capturing||e.captureError(u);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var g=null;function Pe(t){if(g&&g.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=D(A({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return g=new C(e),g.init(),g}function qe(t,e){if(!g){console.warn("[Ultron] captureError called before initTracker");return}g.captureError(t,e);}function Ue(){g&&(g.destroy(),g=null);}
|
|
2
2
|
exports.UltronTracker=C;exports.captureError=qe;exports.destroyTracker=Ue;exports.initTracker=Pe;
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Z=Object.defineProperty,J=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var B=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var H=(t,e,r)=>e in t?Z(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))te.call(e,r)&&H(t,r,e[r]);if(B)for(var r of B(e))re.call(e,r)&&H(t,r,e[r]);return t},D=(t,e)=>J(t,ee(e));var V="__ultron_sid__";function F(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var b=null;function m(){if(b)return b;try{let t=sessionStorage.getItem(V);if(t)return b=t,t;let e=F();return sessionStorage.setItem(V,e),b=e,e}catch(t){return b||(b=F()),b}}function y(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function w(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function E(){var t;try{let e=window.innerWidth,r=window.innerHeight,o=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${o}`}catch(e){return ""}}function v(){var t,e;try{let o=navigator.connection;return o&&(e=(t=o.type)!=null?t:o.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var O=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},o=`${this.config.endpoint}/api/ingest`;try{let u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!u.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",u.status);}catch(u){this.config.debug&&console.warn("[Ultron] Flush error:",u),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,o={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(o)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(u){this.config.debug&&console.warn("[Ultron] flushSync error:",u);}}};var R={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},L=500,X=["image/","audio/","video/","font/","application/octet-stream"];function P(t,e,r){return e?"cors":t>=500?"server_error":t>=400?"client_error":r?"slow":"network_failure"}function ne(t){try{let e=new URL(t);return e.origin===window.location.origin?e.pathname+(e.search||""):t}catch(e){return t}}function q(t){try{let e=Object.fromEntries(new URL(t).searchParams.entries());return Object.keys(e).length>0?e:null}catch(e){return null}}function U(t){try{return new URL(t).pathname}catch(e){return t.split("?")[0]}}async function oe(t){var e;try{let r=(e=t.headers.get("content-type"))!=null?e:"";if(X.some(n=>r.includes(n)))return null;let u=await t.clone().text();return u.slice(0,L)+(u.length>L?"\u2026":"")}catch(r){return null}}function j(t){try{let r=performance.getEntriesByType("resource").filter(o=>o.name===t).pop();return !r||!r.responseEnd?null:{dns:Math.round(r.domainLookupEnd-r.domainLookupStart),tcp:Math.round(r.connectEnd-r.connectStart),tls:r.secureConnectionStart>0?Math.round(r.connectEnd-r.secureConnectionStart):0,ttfb:Math.round(r.responseStart-r.requestStart),transfer:Math.round(r.responseEnd-r.responseStart),total:Math.round(r.responseEnd-r.startTime)}}catch(e){return null}}function I(t,e,r,o,u){var i,c;let n=ne(e),s=`${o}ms`;switch(u){case "cors":return `CORS blocked: ${t} ${n}`;case "server_error":return `Server error ${r} (${(i=R[r])!=null?i:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "client_error":return `Client error ${r} (${(c=R[r])!=null?c:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "slow":return `Slow response: ${t} ${n} \u2014 ${s}`;case "network_failure":return `Network failure: ${t} ${n}`}}function $(t,e){let r=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:e,timestamp:Date.now()}}function K(t){try{return t.startsWith("http")?new URL(t).origin!==window.location.origin:!1}catch(e){return false}}function ie(t,e){return K(t)&&(e.includes("Failed to fetch")||e.includes("NetworkError")||e.includes("Load failed"))}function Q(t,e){try{let r=new URL(e).hostname,o=t.startsWith("http")?new URL(t).hostname:null;if(o&&o===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function G(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,o=window.fetch.bind(window);window.fetch=async function(i,c){var k;let a=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(Q(a,e.endpoint))return o(i,c);let S=((k=c==null?void 0:c.method)!=null?k:i instanceof Request?i.method:"GET").toUpperCase(),_=Date.now();try{let d=await o(i,c),l=Date.now()-_,f=l>r;if(!d.ok||f){let p=d.ok?0:d.status,h=P(p,!1,f);oe(d).then(T=>{var x;t.enqueue($(I(S,a,p,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:p,status_text:(x=R[p])!=null?x:null,duration:l,slow:f,cors:!1,response_body:T,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));});}return d}catch(d){let l=Date.now()-_,f=String(d),p=ie(a,f),h=P(0,p,false);throw t.enqueue($(I(S,a,0,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:0,status_text:null,duration:l,slow:false,cors:p,error:f,response_body:null,timing:null,page:window.location.pathname,referrer:document.referrer||null})),d}};let u=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,c,...a){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(c),u.call(this,i,c,...a)},XMLHttpRequest.prototype.send=function(...i){var _,k;let c=(_=this.__ultron_method)!=null?_:"GET",a=(k=this.__ultron_url)!=null?k:"",S=Date.now();return Q(a,e.endpoint)||this.addEventListener("loadend",()=>{var h,T;let d=Date.now()-S,l=this.status,f=d>r,p=l===0&&K(a);if(l===0||l>=400||f){let x=P(l,p,f),M=null;try{let N=(h=this.getResponseHeader("content-type"))!=null?h:"";!X.some(Y=>N.includes(Y))&&typeof this.responseText=="string"&&(M=this.responseText.slice(0,L)+(this.responseText.length>L?"\u2026":""));}catch(N){}t.enqueue($(I(c,a,l,d,x),{category:x,endpoint:U(a),request_url:a,params:q(a),method:c,status:l,status_text:(T=R[l])!=null?T:null,duration:d,slow:f,cors:p,response_body:M,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));}}),n.apply(this,i)};}var se={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function ae(t,e,r){let o=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function ce(t,e){let r=se[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function W(t,e){var u;let r=(u=e.reportAllVitals)!=null?u:false;function o(n,s){let i=ce(n,s);(r||i!=="good")&&t.enqueue(ae(n,s,i));}if(typeof PerformanceObserver!="undefined"){try{let n=0,s=new PerformanceObserver(i=>{let c=i.getEntries();n=c[c.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("LCP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.hadRecentInput||(n+=a.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(o("CLS",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.duration>n&&(n=a.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("INP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(o("FCP",i.startTime),n.disconnect());});n.observe({type:"paint",buffered:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries()){let c=i;o("TTFB",c.responseStart-c.requestStart),n.disconnect();}});n.observe({type:"navigation",buffered:!0});}catch(n){}}}var ue=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function z(t,e){let r=navigator.userAgent;function o(u){let n=u.target;if(!n||!ue.has(n.tagName))return;let s=n.src||n.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${n.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:{tag:n.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",o,true),()=>window.removeEventListener("error",o,true)}var C=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new O(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=z(this.queue,this.config),G(this.queue,this.config),W(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let o=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,o,u,n,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,o,u,n,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let o=r.reason,u=o instanceof Error?o:new Error(String(o));e.capturing||e.captureError(u);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var g=null;function Pe(t){if(g&&g.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=D(A({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return g=new C(e),g.init(),g}function qe(t,e){if(!g){console.warn("[Ultron] captureError called before initTracker");return}g.captureError(t,e);}function Ue(){g&&(g.destroy(),g=null);}
|
|
1
|
+
var Z=Object.defineProperty,J=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var B=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var H=(t,e,r)=>e in t?Z(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))te.call(e,r)&&H(t,r,e[r]);if(B)for(var r of B(e))re.call(e,r)&&H(t,r,e[r]);return t},D=(t,e)=>J(t,ee(e));var V="__ultron_sid__";function F(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var b=null;function m(){if(b)return b;try{let t=sessionStorage.getItem(V);if(t)return b=t,t;let e=F();return sessionStorage.setItem(V,e),b=e,e}catch(t){return b||(b=F()),b}}function y(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function w(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function E(){var t;try{let e=window.innerWidth,r=window.innerHeight,o=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${o}`}catch(e){return ""}}function v(){var t,e;try{let o=navigator.connection;return o&&(e=(t=o.type)!=null?t:o.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var O=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},o=`${this.config.endpoint}/api/ingest`;try{let u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!u.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",u.status);}catch(u){this.config.debug&&console.warn("[Ultron] Flush error:",u),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,o={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(o)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(u){this.config.debug&&console.warn("[Ultron] flushSync error:",u);}}};var R={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},L=500,X=["image/","audio/","video/","font/","application/octet-stream"];function P(t,e,r){return e?"cors":t>=500?"server_error":t>=400?"client_error":r?"slow":"network_failure"}function ne(t){try{let e=new URL(t);return e.origin===window.location.origin?e.pathname+(e.search||""):t}catch(e){return t}}function q(t){try{let e=Object.fromEntries(new URL(t).searchParams.entries());return Object.keys(e).length>0?e:null}catch(e){return null}}function U(t){try{return new URL(t).pathname}catch(e){return t.split("?")[0]}}async function oe(t){var e;try{let r=(e=t.headers.get("content-type"))!=null?e:"";if(X.some(n=>r.includes(n)))return null;let u=await t.clone().text();return u.slice(0,L)+(u.length>L?"\u2026":"")}catch(r){return null}}function j(t){try{let r=performance.getEntriesByType("resource").filter(o=>o.name===t).pop();return !r||!r.responseEnd||r.responseStart===0?null:{dns:Math.round(r.domainLookupEnd-r.domainLookupStart),tcp:Math.round(r.connectEnd-r.connectStart),tls:r.secureConnectionStart>0?Math.round(r.connectEnd-r.secureConnectionStart):0,ttfb:Math.round(r.responseStart-r.requestStart),transfer:Math.round(r.responseEnd-r.responseStart),total:Math.round(r.responseEnd-r.startTime)}}catch(e){return null}}function I(t,e,r,o,u){var i,c;let n=ne(e),s=`${o}ms`;switch(u){case "cors":return `CORS blocked: ${t} ${n}`;case "server_error":return `Server error ${r} (${(i=R[r])!=null?i:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "client_error":return `Client error ${r} (${(c=R[r])!=null?c:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "slow":return `Slow response: ${t} ${n} \u2014 ${s}`;case "network_failure":return `Network failure: ${t} ${n}`}}function $(t,e){let r=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:e,timestamp:Date.now()}}function K(t){try{return t.startsWith("http")?new URL(t).origin!==window.location.origin:!1}catch(e){return false}}function ie(t,e){return K(t)&&(e.includes("Failed to fetch")||e.includes("NetworkError")||e.includes("Load failed"))}function Q(t,e){try{let r=new URL(e).hostname,o=t.startsWith("http")?new URL(t).hostname:null;if(o&&o===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function G(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,o=window.fetch.bind(window);window.fetch=async function(i,c){var k;let a=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(Q(a,e.endpoint))return o(i,c);let S=((k=c==null?void 0:c.method)!=null?k:i instanceof Request?i.method:"GET").toUpperCase(),_=Date.now();try{let d=await o(i,c),l=Date.now()-_,f=l>r;if(!d.ok||f){let p=d.ok?0:d.status,h=P(p,!1,f);oe(d).then(T=>{var x;t.enqueue($(I(S,a,p,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:p,status_text:(x=R[p])!=null?x:null,duration:l,slow:f,cors:!1,response_body:T,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));});}return d}catch(d){let l=Date.now()-_,f=String(d),p=ie(a,f),h=P(0,p,false);throw t.enqueue($(I(S,a,0,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:0,status_text:null,duration:l,slow:false,cors:p,error:f,response_body:null,timing:null,page:window.location.pathname,referrer:document.referrer||null})),d}};let u=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,c,...a){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(c),u.call(this,i,c,...a)},XMLHttpRequest.prototype.send=function(...i){var _,k;let c=(_=this.__ultron_method)!=null?_:"GET",a=(k=this.__ultron_url)!=null?k:"",S=Date.now();return Q(a,e.endpoint)||this.addEventListener("loadend",()=>{var h,T;let d=Date.now()-S,l=this.status,f=d>r,p=l===0&&K(a);if(l===0||l>=400||f){let x=P(l,p,f),M=null;try{let N=(h=this.getResponseHeader("content-type"))!=null?h:"";!X.some(Y=>N.includes(Y))&&typeof this.responseText=="string"&&(M=this.responseText.slice(0,L)+(this.responseText.length>L?"\u2026":""));}catch(N){}t.enqueue($(I(c,a,l,d,x),{category:x,endpoint:U(a),request_url:a,params:q(a),method:c,status:l,status_text:(T=R[l])!=null?T:null,duration:d,slow:f,cors:p,response_body:M,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));}}),n.apply(this,i)};}var se={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function ae(t,e,r){let o=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function ce(t,e){let r=se[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function W(t,e){var u;let r=(u=e.reportAllVitals)!=null?u:false;function o(n,s){let i=ce(n,s);(r||i!=="good")&&t.enqueue(ae(n,s,i));}if(typeof PerformanceObserver!="undefined"){try{let n=0,s=new PerformanceObserver(i=>{let c=i.getEntries();n=c[c.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("LCP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.hadRecentInput||(n+=a.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(o("CLS",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.duration>n&&(n=a.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("INP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(o("FCP",i.startTime),n.disconnect());});n.observe({type:"paint",buffered:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries()){let c=i;o("TTFB",c.responseStart-c.requestStart),n.disconnect();}});n.observe({type:"navigation",buffered:!0});}catch(n){}}}var ue=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function z(t,e){let r=navigator.userAgent;function o(u){let n=u.target;if(!n||!ue.has(n.tagName))return;let s=n.src||n.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${n.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:{tag:n.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",o,true),()=>window.removeEventListener("error",o,true)}var C=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new O(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=z(this.queue,this.config),G(this.queue,this.config),W(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let o=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,o,u,n,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,o,u,n,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let o=r.reason,u=o instanceof Error?o:new Error(String(o));e.capturing||e.captureError(u);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var g=null;function Pe(t){if(g&&g.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=D(A({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return g=new C(e),g.init(),g}function qe(t,e){if(!g){console.warn("[Ultron] captureError called before initTracker");return}g.captureError(t,e);}function Ue(){g&&(g.destroy(),g=null);}
|
|
2
2
|
export{C as UltronTracker,qe as captureError,Ue as destroyTracker,Pe as initTracker};
|