@senzops/apm-node 1.1.4 → 1.1.6

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.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=class{constructor(t){this.config=t;this.queue=[];this.timer=null;typeof setInterval<"u"&&(this.timer=setInterval(()=>this.flush(),t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}add(t){this.queue.push(t),this.queue.length>=(this.config.batchSize||100)&&this.flush()}async flush(){if(this.queue.length===0)return;let t=[...this.queue];this.queue=[];try{await fetch(this.config.endpoint||"https://api.senzor.dev/api/ingest/apm",{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey},body:JSON.stringify(t),keepalive:!0}),this.config.debug&&console.log(`[Senzor] Flushed ${t.length} traces`)}catch(n){this.config.debug&&console.error("[Senzor] Ingestion Error:",n)}}};import{AsyncLocalStorage as L}from"async_hooks";var C=new L,m={run:(e,t)=>C.run(e,t),current:()=>C.getStore(),addSpan:e=>{let t=C.getStore();t&&t.spans.push(e)},setError:e=>{let t=C.getStore();t&&(t.error={name:e.name,message:e.message,stack:e.stack})}};import{randomUUID as N}from"crypto";import k from"http";import O from"https";import{URL as b}from"url";var F=(e,t,n)=>{if(!e[t])return;let r=e[t];e[t]=n(r)},I=(e,t=!1)=>{if(!globalThis.fetch)return;let n="";try{n=new b(e).hostname}catch{}let r=globalThis.fetch;globalThis.fetch=async(o,a)=>{let i="";if(typeof o=="string"?i=o:o instanceof b?i=o.toString():o&&o.url&&(i=o.url),n&&i.includes(n))return r(o,a);let u=m.current();if(!u)return r(o,a);let c=(a?.method||"GET").toUpperCase(),h=performance.now()-u.startTime,w=performance.now(),y="unknown";try{y=new b(i).hostname}catch{}t&&console.log(`[Senzor] Tracking Fetch: ${c} ${y}`);try{let l=await r(o,a),d=performance.now()-w;return m.addSpan({name:`${c} ${y}`,type:"http",startTime:h,duration:d,status:l.status,meta:{url:i,method:c,library:"fetch"}}),l}catch(l){let d=performance.now()-w;throw m.addSpan({name:`${c} ${y}`,type:"http",startTime:h,duration:d,status:500,meta:{error:l.message,url:i,library:"fetch"}}),l}}},P=(e,t=!1)=>{let n="";try{n=new b(e).hostname}catch{}let r=o=>function(...a){let i={},u="";if(typeof a[0]=="string"||a[0]instanceof b)u=a[0].toString(),typeof a[1]=="object"&&a[1]!==null&&(i=a[1]);else{i=a[0]||{};let p=i.protocol||(i.port===443?"https:":"http:"),f=i.hostname||i.host||"localhost",T=i.path||"/";u=`${p}//${f}${T}`}if(n&&(u.includes(n)||i.hostname&&i.hostname.includes(n)))return o.apply(this,a);let c=m.current();if(!c)return o.apply(this,a);let h=(i.method||"GET").toUpperCase(),w=performance.now()-c.startTime,y=performance.now(),l="unknown";try{l=new b(u).hostname}catch{l=i.hostname||"unknown"}let d=o.apply(this,a),g=(p,f)=>{let T=performance.now()-y;m.addSpan({name:`${h} ${l}`,type:"http",startTime:w,duration:T,status:f?500:p?.statusCode||0,meta:{url:u,method:h,library:"http",error:f?f.message:void 0}})};return d.on("response",p=>{p.once("end",()=>g(p)),p.once("error",f=>g(p,f))}),d.on("error",p=>g(null,p)),d};F(k,"request",r),F(k,"get",r),F(O,"request",r),F(O,"get",r)};var $=(e=!1)=>{try{let t=A("mongodb"),n=t.Collection,r=t.FindCursor||A("mongodb/lib/cursor/find_cursor").FindCursor,o=t.AggregationCursor||A("mongodb/lib/cursor/aggregation_cursor").AggregationCursor;e&&console.log("[Senzor] Instrumenting MongoDB (Collection + Cursors)...");let a=(c,h,w,y,l,d)=>{let g=performance.now()-y;m.addSpan({name:`MongoDB ${c}`,type:"db",startTime:performance.now()-l-g,duration:g,status:d?500:0,meta:{collection:w,operation:h,error:d?d.message:void 0}}),e&&console.log(`[Senzor] Captured Mongo: ${c} (${g.toFixed(2)}ms)`)};["insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","countDocuments"].forEach(c=>{if(!n.prototype[c])return;let h=n.prototype[c];n.prototype[c]=function(...w){let y=m.current();if(!y)return h.apply(this,w);let l=performance.now(),d=y.startTime,g=this.collectionName;try{let p=h.apply(this,w);return p&&typeof p.then=="function"?p.then(f=>(a(c,c,g,l,d),f),f=>{throw a(c,c,g,l,d,f),f}):p}catch(p){throw a(c,c,g,l,d,p),p}}});let u=(c,h)=>{if(!c||!c.prototype.toArray)return;let w=c.prototype.toArray;c.prototype.toArray=function(...y){let l=m.current();if(!l)return w.apply(this,y);let d=performance.now(),g=l.startTime,p=this.namespace?.collection||"unknown",f=S=>(a(h,h,p,d,g),S),T=S=>{throw a(h,h,p,d,g,S),S};try{let S=w.apply(this,y);return S&&typeof S.then=="function"?S.then(f,T):f(S)}catch(S){T(S)}}};u(r,"find"),u(o,"aggregate")}catch(t){e&&console.warn("[Senzor] MongoDB instrumentation warning:",t.message)}};var H=()=>{try{let e=A("pg"),t=e.Client.prototype.query;e.Client.prototype.query=function(...n){let r=m.current();if(!r)return t.apply(this,n);let o=performance.now()-r.startTime,a=performance.now(),i=typeof n[0]=="string"?n[0]:n[0].text,u=t.apply(this,n);return u&&typeof u.then=="function"?u.then(c=>{let h=performance.now()-a;return m.addSpan({name:"Postgres Query",type:"db",startTime:o,duration:h,meta:{query:i}}),c}):u}}catch{}};var z=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let n=t.endpoint||"https://api.senzor.dev/api/ingest/apm",r=t.debug||!1;if(this.transport=new E({...t,endpoint:n}),!this.isInstrumented){try{P(n,r)}catch{}try{I(n,r)}catch{}try{$(r)}catch{}try{H()}catch{}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}startTrace(t,n){if(!this.transport)return n();let r={id:N(),startTime:performance.now(),data:t,spans:[]};return m.run(r,n)}endTrace(t,n={}){let r=m.current();if(!r||!this.transport)return;let o=performance.now()-r.startTime,a={traceId:r.id,...r.data,...n,status:t,duration:o,spans:r.spans,error:r.error,timestamp:new Date().toISOString()};this.transport.add(a)}captureError(t){t instanceof Error?m.setError(t):typeof t=="string"&&m.setError(new Error(t))}track(t){this.transport?.add({traceId:N(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=m.current();if(!r)return{end:()=>{}};let o=performance.now()-r.startTime,a=performance.now();return{end:(i,u)=>{m.addSpan({name:t,type:n,startTime:o,duration:performance.now()-a,status:u,meta:i})}}}async flush(){this.transport&&await this.transport.flush()}},s=new z;var R=()=>(e,t,n)=>{s.startTrace({method:e.method,path:e.originalUrl||e.url,ip:e.ip||e.socket?.remoteAddress,userAgent:e.headers["user-agent"]},()=>{t.once("finish",()=>{try{let r="UNKNOWN";e.route&&e.route.path?r=(e.baseUrl||"")+e.route.path:t.statusCode===404?r="Not Found":r=e.path||"Wildcard",s.endTrace(t.statusCode,{route:r})}catch{}}),n()})},M=()=>(e,t,n,r)=>{s.captureError(e),r(e)};var x=e=>!e||e==="/"?"/":e.replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g,":uuid").replace(/[0-9a-fA-F]{24}/g,":objectId").replace(/\/(\d+)(?=\/|$)/g,"/:id").split("?")[0],v=(e,t)=>e.route&&e.route.path?(e.baseUrl||"")+e.route.path:e.context&&e.context.matchedRoute?e.context.matchedRoute.path:e.routerPath?e.routerPath:x(t);var U=e=>t=>{let n=t.node.req,r=n.originalUrl||n.url||"/";return s.startTrace({method:n.method||"GET",path:r,ip:n.headers["x-forwarded-for"]||n.socket?.remoteAddress,userAgent:n.headers["user-agent"]},async()=>{try{let o=await e(t),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),o&&o.statusCode&&(a=o.statusCode),s.endTrace(a,{route:v(t,r)}),o}catch(o){s.captureError(o);let a=o.statusCode||o.status||500;throw s.endTrace(a,{route:v(t,r)}),o}})};var D=e=>async(t,n)=>{let r=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",a=t.headers.get?t.headers.get("user-agent"):void 0,i=t.headers.get?t.headers.get("x-forwarded-for"):void 0;return s.startTrace({method:o,path:r.pathname,userAgent:a,ip:i},async()=>{try{let u=await e(t,n),c=u?.status||200;return s.endTrace(c,{route:x(r.pathname)}),u}catch(u){throw s.captureError(u),s.endTrace(500,{route:x(r.pathname)}),u}})},K=e=>async(t,n)=>{let r=t.url?t.url.split("?")[0]:"/";return s.startTrace({method:t.method||"GET",path:r,userAgent:t.headers["user-agent"],ip:t.headers["x-forwarded-for"]||t.socket?.remoteAddress},async()=>{let o=()=>{s.endTrace(n.statusCode||200,{route:x(r)})};n.once("finish",o),n.once("close",o);try{return await e(t,n)}catch(a){throw s.captureError(a),a}})};var G=(e,t,n)=>{t&&t.apiKey&&s.init(t),e.addHook("onRequest",(r,o,a)=>{s.startTrace({method:r.method,path:r.raw.url||r.url,ip:r.ip,userAgent:r.headers["user-agent"]},()=>a())}),e.addHook("onError",(r,o,a,i)=>{s.captureError(a),i()}),e.addHook("onResponse",(r,o,a)=>{let i=r.routeOptions?.url||r.routerPath||"UNKNOWN";s.endTrace(o.statusCode,{route:i}),a()}),n()};var W={init:e=>s.init(e),flush:()=>s.flush(),track:s.track.bind(s),startSpan:s.startSpan.bind(s),captureException:s.captureError.bind(s),requestHandler:R,errorHandler:M,wrapNextRoute:D,wrapNextPages:K,wrapH3:U,fastifyPlugin:G},Ft=W;export{W as Senzor,Ft as default};
1
+ var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=class{constructor(t){this.config=t;this.queue=[];this.timer=null;typeof setInterval<"u"&&(this.timer=setInterval(()=>this.flush(),t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}add(t){this.queue.push(t),this.queue.length>=(this.config.batchSize||100)&&this.flush()}async flush(){if(this.queue.length===0)return;let t=[...this.queue];this.queue=[];try{await fetch(this.config.endpoint||"https://api.senzor.dev/api/ingest/apm",{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey},body:JSON.stringify(t),keepalive:!0}),this.config.debug&&console.log(`[Senzor] Flushed ${t.length} traces`)}catch(n){this.config.debug&&console.error("[Senzor] Ingestion Error:",n)}}};import{AsyncLocalStorage as W}from"async_hooks";var I=new W,l={run:(e,t)=>I.run(e,t),current:()=>I.getStore(),addSpan:e=>{let t=I.getStore();t&&t.spans.push(e)},setError:e=>{let t=I.getStore();t&&(t.error={name:e.name,message:e.message,stack:e.stack})}};import{randomUUID as F}from"crypto";import H from"http";import U from"https";import{URL as x}from"url";import{randomUUID as P}from"crypto";var z=(e,t,n)=>{if(!e[t])return;let r=e[t];e[t]=n(r)},R=(e,t=!1)=>{if(!globalThis.fetch)return;let n="";try{n=new x(e).hostname}catch{}let r=globalThis.fetch;globalThis.fetch=async(o,a)=>{let i="";if(typeof o=="string"?i=o:o instanceof x?i=o.toString():o&&o.url&&(i=o.url),n&&i.includes(n))return r(o,a);let c=l.current();if(!c)return r(o,a);let s=(a?.method||"GET").toUpperCase(),d=performance.now()-c.startTime,S=performance.now(),T=P(),w="unknown";try{w=new x(i).hostname}catch{}let h={...a};h.headers||(h.headers={});let m=(u,f)=>{h.headers instanceof Headers?h.headers.set(u,f):Array.isArray(h.headers)?h.headers.push([u,f]):h.headers[u]=f};m("x-senzor-trace-id",c.id),m("x-senzor-parent-span-id",T);try{let u=await r(o,h),f=performance.now()-S;return l.addSpan({spanId:T,name:`${s} ${w}`,type:"http",startTime:d,duration:f,status:u.status,meta:{url:i,method:s,library:"fetch"}}),u}catch(u){let f=performance.now()-S;throw l.addSpan({spanId:T,name:`${s} ${w}`,type:"http",startTime:d,duration:f,status:500,meta:{error:u.message,url:i,library:"fetch"}}),u}}},$=(e,t=!1)=>{let n="";try{n=new x(e).hostname}catch{}let r=o=>function(...a){let i={},c="",s=0;if(typeof a[0]=="string"||a[0]instanceof x?(c=a[0].toString(),s=1):s=0,(!a[s]||typeof a[s]!="object")&&(a[s]={}),i=a[s],!c){let g=i.protocol||(i.port===443?"https:":"http:"),y=i.hostname||i.host||"localhost",C=i.path||"/";c=`${g}//${y}${C}`}if(n&&(c.includes(n)||i.hostname&&i.hostname.includes(n)))return o.apply(this,a);let d=l.current();if(!d)return o.apply(this,a);let S=(i.method||"GET").toUpperCase(),T=performance.now()-d.startTime,w=performance.now(),h=P(),m="unknown";try{m=new x(c).hostname}catch{m=i.hostname||"unknown"}i.headers||(i.headers={}),i.headers["x-senzor-trace-id"]=d.id,i.headers["x-senzor-parent-span-id"]=h,t&&console.log(`[Senzor] Injecting headers to ${c}`);let u=o.apply(this,a),f=(g,y)=>{let C=performance.now()-w;l.addSpan({spanId:h,name:`${S} ${m}`,type:"http",startTime:T,duration:C,status:y?500:g?.statusCode||0,meta:{url:c,method:S,library:"http"}})};return u.on("response",g=>{g.once("end",()=>f(g)),g.once("close",()=>f(g)),g.once("error",y=>f(g,y))}),u.on("error",g=>f(null,g)),u};z(H,"request",r),z(H,"get",r),z(U,"request",r),z(U,"get",r)};var N=(e=!1)=>{try{let t=A("mongodb"),n=t.Collection,r=t.FindCursor||A("mongodb/lib/cursor/find_cursor").FindCursor,o=t.AggregationCursor||A("mongodb/lib/cursor/aggregation_cursor").AggregationCursor;e&&console.log("[Senzor] Instrumenting MongoDB (Collection + Cursors)...");let a=(s,d,S,T,w,h)=>{let m=performance.now()-T;l.addSpan({name:`MongoDB ${s}`,type:"db",startTime:performance.now()-w-m,duration:m,status:h?500:0,meta:{collection:S,operation:d,error:h?h.message:void 0}}),e&&console.log(`[Senzor] Captured Mongo: ${s} (${m.toFixed(2)}ms)`)};["insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","countDocuments"].forEach(s=>{if(!n.prototype[s])return;let d=n.prototype[s];n.prototype[s]=function(...S){let T=l.current();if(!T)return d.apply(this,S);let w=performance.now(),h=T.startTime,m=this.collectionName;try{let u=d.apply(this,S);return u&&typeof u.then=="function"?u.then(f=>(a(s,s,m,w,h),f),f=>{throw a(s,s,m,w,h,f),f}):u}catch(u){throw a(s,s,m,w,h,u),u}}});let c=(s,d)=>{if(!s||!s.prototype.toArray)return;let S=s.prototype.toArray;s.prototype.toArray=function(...T){let w=l.current();if(!w)return S.apply(this,T);let h=performance.now(),m=w.startTime,u=this.namespace?.collection||"unknown",f=y=>(a(d,d,u,h,m),y),g=y=>{throw a(d,d,u,h,m,y),y};try{let y=S.apply(this,T);return y&&typeof y.then=="function"?y.then(f,g):f(y)}catch(y){g(y)}}};c(r,"find"),c(o,"aggregate")}catch(t){e&&console.warn("[Senzor] MongoDB instrumentation warning:",t.message)}};var M=()=>{try{let e=A("pg"),t=e.Client.prototype.query;e.Client.prototype.query=function(...n){let r=l.current();if(!r)return t.apply(this,n);let o=performance.now()-r.startTime,a=performance.now(),i=typeof n[0]=="string"?n[0]:n[0].text,c=t.apply(this,n);return c&&typeof c.then=="function"?c.then(s=>{let d=performance.now()-a;return l.addSpan({name:"Postgres Query",type:"db",startTime:o,duration:d,meta:{query:i}}),s}):c}}catch{}};var O=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let n=t.endpoint||"https://api.senzor.dev/api/ingest/apm",r=t.debug||!1;if(this.transport=new E({...t,endpoint:n}),!this.isInstrumented){try{$(n,r)}catch{}try{R(n,r)}catch{}try{N(r)}catch{}try{M()}catch{}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}startTrace(t,n){if(!this.transport)return n();let r,o;if(t.headers){let i=c=>{if(t.headers[c])return t.headers[c];if(t.headers[c.toLowerCase()])return t.headers[c.toLowerCase()];if(t.headers[c.toUpperCase()])return t.headers[c.toUpperCase()]};r=i("x-senzor-trace-id"),o=i("x-senzor-parent-span-id")}let a={id:F(),startTime:performance.now(),data:{...t,parentTraceId:r,parentSpanId:o},spans:[]};return l.run(a,n)}endTrace(t,n={}){let r=l.current();if(!r||!this.transport)return;let o=performance.now()-r.startTime,a={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,...r.data,...n,status:t,duration:o,spans:r.spans,timestamp:new Date().toISOString(),error:r.error};this.transport.add(a)}captureError(t){t instanceof Error?l.setError(t):typeof t=="string"&&l.setError(new Error(t))}track(t){this.transport?.add({traceId:F(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=l.current();if(!r)return{end:()=>{}};let o=performance.now()-r.startTime,a=performance.now(),i=F();return{end:(c,s)=>{l.addSpan({spanId:i,name:t,type:n,startTime:o,duration:performance.now()-a,status:s,meta:c})}}}async flush(){this.transport&&await this.transport.flush()}},p=new O;var k=()=>(e,t,n)=>{p.startTrace({method:e.method,path:e.originalUrl||e.url,ip:e.ip||e.socket?.remoteAddress,userAgent:e.headers["user-agent"],headers:e.headers},()=>{t.once("finish",()=>{try{let r="UNKNOWN";e.route&&e.route.path?r=(e.baseUrl||"")+e.route.path:t.statusCode===404?r="Not Found":r=e.path||"Wildcard",p.endTrace(t.statusCode,{route:r})}catch{}}),n()})},D=()=>(e,t,n,r)=>{p.captureError(e),r(e)};var b=e=>!e||e==="/"?"/":e.replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g,":uuid").replace(/[0-9a-fA-F]{24}/g,":objectId").replace(/\/(\d+)(?=\/|$)/g,"/:id").split("?")[0],v=(e,t)=>e.route&&e.route.path?(e.baseUrl||"")+e.route.path:e.context&&e.context.matchedRoute?e.context.matchedRoute.path:e.routerPath?e.routerPath:b(t);var K=e=>t=>{let n=t.node.req,r=n.originalUrl||n.url||"/";return p.startTrace({method:n.method||"GET",path:r,ip:n.headers["x-forwarded-for"]||n.socket?.remoteAddress,userAgent:n.headers["user-agent"],headers:n.headers},async()=>{try{let o=await e(t),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),o&&o.statusCode&&(a=o.statusCode),p.endTrace(a,{route:v(t,r)}),o}catch(o){p.captureError(o);let a=o.statusCode||o.status||500;throw p.endTrace(a,{route:v(t,r)}),o}})};var L=e=>async(t,n)=>{let r=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",a={},i,c;return typeof t.headers.get=="function"?(i=t.headers.get("user-agent"),c=t.headers.get("x-forwarded-for"),t.headers.forEach((s,d)=>{a[d]=s})):(a=t.headers,i=a["user-agent"],c=a["x-forwarded-for"]),p.startTrace({method:o,path:r.pathname,userAgent:i,ip:c,headers:a},async()=>{try{let s=await e(t,n),d=s?.status||200;return p.endTrace(d,{route:b(r.pathname)}),s}catch(s){throw p.captureError(s),p.endTrace(500,{route:b(r.pathname)}),s}})},G=e=>async(t,n)=>{let r=t.url?t.url.split("?")[0]:"/";return p.startTrace({method:t.method||"GET",path:r,userAgent:t.headers["user-agent"],ip:t.headers["x-forwarded-for"]||t.socket?.remoteAddress,headers:t.headers},async()=>{let o=()=>{p.endTrace(n.statusCode||200,{route:b(r)})};n.once("finish",o),n.once("close",o);try{return await e(t,n)}catch(a){throw p.captureError(a),a}})};var j=(e,t,n)=>{t&&t.apiKey&&p.init(t),e.addHook("onRequest",(r,o,a)=>{p.startTrace({method:r.method,path:r.raw.url||r.url,ip:r.ip,userAgent:r.headers["user-agent"],headers:r.headers},()=>a())}),e.addHook("onError",(r,o,a,i)=>{p.captureError(a),i()}),e.addHook("onResponse",(r,o,a)=>{let i=r.routeOptions?.url||r.routerPath||"UNKNOWN";p.endTrace(o.statusCode,{route:i}),a()}),n()};var B={init:e=>p.init(e),flush:()=>p.flush(),track:p.track.bind(p),startSpan:p.startSpan.bind(p),captureException:p.captureError.bind(p),requestHandler:k,errorHandler:D,wrapNextRoute:L,wrapNextPages:G,wrapH3:K,fastifyPlugin:j},Ot=B;export{B as Senzor,Ot as default};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/transport.ts","../src/core/context.ts","../src/core/client.ts","../src/instrumentation/http.ts","../src/instrumentation/mongo.ts","../src/instrumentation/pg.ts","../src/middleware/express.ts","../src/core/normalizer.ts","../src/wrappers/h3.ts","../src/wrappers/next.ts","../src/wrappers/fastify.ts","../src/index.ts"],"sourcesContent":["import { SenzorOptions } from './types';\r\n\r\nexport class Transport {\r\n private queue: any[] = [];\r\n private timer: NodeJS.Timeout | null = null;\r\n\r\n constructor(private config: SenzorOptions) {\r\n if (typeof setInterval !== 'undefined') {\r\n this.timer = setInterval(() => this.flush(), config.flushInterval || 10000);\r\n if (this.timer && typeof this.timer.unref === 'function') {\r\n this.timer.unref(); // Don't block process exit\r\n }\r\n }\r\n }\r\n\r\n public add(trace: any) {\r\n this.queue.push(trace);\r\n if (this.queue.length >= (this.config.batchSize || 100)) {\r\n this.flush();\r\n }\r\n }\r\n\r\n public async flush() {\r\n if (this.queue.length === 0) return;\r\n\r\n const batch = [...this.queue];\r\n this.queue = [];\r\n\r\n try {\r\n // Use global fetch (Node 18+)\r\n await fetch(this.config.endpoint || 'https://api.senzor.dev/api/ingest/apm', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'x-service-api-key': this.config.apiKey,\r\n },\r\n body: JSON.stringify(batch),\r\n keepalive: true,\r\n });\r\n \r\n if (this.config.debug) console.log(`[Senzor] Flushed ${batch.length} traces`);\r\n } catch (err) {\r\n if (this.config.debug) console.error('[Senzor] Ingestion Error:', err);\r\n // Dropping data to prevent memory leaks is preferred in APM\r\n }\r\n }\r\n}","import { AsyncLocalStorage } from 'async_hooks';\r\nimport { ActiveTrace, TraceError } from './types';\r\n\r\nexport const storage = new AsyncLocalStorage<ActiveTrace>();\r\n\r\nexport const Context = {\r\n run: <T>(trace: ActiveTrace, fn: () => T): T => {\r\n return storage.run(trace, fn);\r\n },\r\n\r\n current: (): ActiveTrace | undefined => {\r\n return storage.getStore();\r\n },\r\n\r\n addSpan: (span: any) => {\r\n const store = storage.getStore();\r\n if (store) {\r\n store.spans.push(span);\r\n }\r\n },\r\n\r\n // Attach error to current trace\r\n setError: (error: Error) => {\r\n const store = storage.getStore();\r\n if (store) {\r\n store.error = {\r\n name: error.name,\r\n message: error.message,\r\n stack: error.stack\r\n };\r\n }\r\n }\r\n};","import { Transport } from './transport';\r\nimport { Context } from './context';\r\nimport { SenzorOptions, ActiveTrace } from './types';\r\nimport { randomUUID } from 'crypto';\r\nimport { instrumentHttp, instrumentFetch } from '../instrumentation/http';\r\nimport { instrumentMongo } from '../instrumentation/mongo';\r\nimport { instrumentPg } from '../instrumentation/pg';\r\n\r\nexport class SenzorClient {\r\n private transport: Transport | null = null;\r\n private options: SenzorOptions | null = null;\r\n private isInstrumented = false;\r\n\r\n public init(options: SenzorOptions) {\r\n if (!options.apiKey) {\r\n console.warn('[Senzor] API Key missing. SDK disabled.');\r\n return;\r\n }\r\n this.options = options;\r\n const endpoint = options.endpoint || 'https://api.senzor.dev/api/ingest/apm';\r\n const debug = options.debug || false;\r\n\r\n this.transport = new Transport({ ...options, endpoint });\r\n\r\n if (!this.isInstrumented) {\r\n try { instrumentHttp(endpoint, debug); } catch (e) { }\r\n try { instrumentFetch(endpoint, debug); } catch (e) { }\r\n try { instrumentMongo(debug); } catch (e) { }\r\n try { instrumentPg(); } catch (e) { }\r\n\r\n this.isInstrumented = true;\r\n if (debug) console.log('[Senzor] Auto-instrumentation enabled');\r\n }\r\n }\r\n\r\n public startTrace<T>(data: Partial<ActiveTrace['data']>, next: () => T): T {\r\n if (!this.transport) return next();\r\n const trace: ActiveTrace = {\r\n id: randomUUID(),\r\n startTime: performance.now(),\r\n data: data,\r\n spans: []\r\n };\r\n return Context.run(trace, next);\r\n }\r\n\r\n public endTrace(status: number, extraData: any = {}) {\r\n const trace = Context.current();\r\n if (!trace || !this.transport) return;\r\n\r\n const duration = performance.now() - trace.startTime;\r\n\r\n const payload = {\r\n traceId: trace.id,\r\n ...trace.data,\r\n ...extraData,\r\n status,\r\n duration,\r\n spans: trace.spans,\r\n error: trace.error, // Include Error if captured\r\n timestamp: new Date().toISOString()\r\n };\r\n\r\n this.transport.add(payload);\r\n }\r\n\r\n // --- NEW: Capture Exception ---\r\n public captureError(error: unknown) {\r\n if (error instanceof Error) {\r\n Context.setError(error);\r\n } else if (typeof error === 'string') {\r\n Context.setError(new Error(error));\r\n }\r\n }\r\n\r\n // ... (manual track, startSpan, flush remain same) ...\r\n public track(data: any) { this.transport?.add({ traceId: randomUUID(), ...data, spans: [], timestamp: new Date().toISOString() }); }\r\n\r\n public startSpan(name: string, type: 'db' | 'http' | 'function' | 'custom' = 'custom') {\r\n const trace = Context.current();\r\n if (!trace) return { end: () => { } };\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n return { end: (meta?: any, status?: number) => { Context.addSpan({ name, type, startTime, duration: performance.now() - spanStartAbs, status, meta }); } };\r\n }\r\n\r\n public async flush() { if (this.transport) await this.transport.flush(); }\r\n}\r\n\r\nexport const client = new SenzorClient();","import http from 'http';\r\nimport https from 'https';\r\nimport { URL } from 'url';\r\nimport { Context } from '../core/context';\r\n\r\nconst shimmer = (module: any, methodName: string, wrapper: (original: Function) => Function) => {\r\n if (!module[methodName]) return;\r\n const original = module[methodName];\r\n module[methodName] = wrapper(original);\r\n};\r\n\r\n// --- Native Fetch Instrumentation (Node 18+) ---\r\nexport const instrumentFetch = (ingestUrl: string, debug = false) => {\r\n if (!globalThis.fetch) return;\r\n\r\n let ingestHost = '';\r\n try { ingestHost = new URL(ingestUrl).hostname; } catch (e) { }\r\n\r\n const originalFetch = globalThis.fetch;\r\n\r\n // @ts-ignore\r\n globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {\r\n // 1. Extract URL\r\n let urlStr = '';\r\n if (typeof input === 'string') urlStr = input;\r\n else if (input instanceof URL) urlStr = input.toString();\r\n else if (input && input.url) urlStr = input.url; // Request object\r\n\r\n // 2. Infinite Loop Guard\r\n if (ingestHost && urlStr.includes(ingestHost)) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n // 3. Context Check\r\n const trace = Context.current();\r\n if (!trace) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n // 4. Start Span\r\n const method = (init?.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { }\r\n\r\n if (debug) console.log(`[Senzor] Tracking Fetch: ${method} ${hostname}`);\r\n\r\n try {\r\n const response = await originalFetch(input, init);\r\n\r\n // 5. End Span\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: response.status,\r\n meta: { url: urlStr, method, library: 'fetch' }\r\n });\r\n\r\n return response;\r\n } catch (err: any) {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: 500,\r\n meta: { error: err.message, url: urlStr, library: 'fetch' }\r\n });\r\n throw err;\r\n }\r\n };\r\n};\r\n\r\n// --- Standard HTTP/HTTPS Instrumentation ---\r\nexport const instrumentHttp = (ingestUrl: string, debug = false) => {\r\n let ingestHost = '';\r\n try {\r\n ingestHost = new URL(ingestUrl).hostname;\r\n } catch (e) { }\r\n\r\n const requestWrapper = (original: Function) => {\r\n return function (this: any, ...args: any[]) {\r\n let options: any = {};\r\n let urlStr = '';\r\n\r\n if (typeof args[0] === 'string' || args[0] instanceof URL) {\r\n urlStr = args[0].toString();\r\n if (typeof args[1] === 'object' && args[1] !== null) options = args[1];\r\n } else {\r\n options = args[0] || {};\r\n const protocol = options.protocol || (options.port === 443 ? 'https:' : 'http:');\r\n const host = options.hostname || options.host || 'localhost';\r\n const path = options.path || '/';\r\n urlStr = `${protocol}//${host}${path}`;\r\n }\r\n\r\n if (ingestHost && (urlStr.includes(ingestHost) || (options.hostname && options.hostname.includes(ingestHost)))) {\r\n return original.apply(this, args);\r\n }\r\n\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const method = (options.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { hostname = options.hostname || 'unknown'; }\r\n\r\n const req = original.apply(this, args);\r\n\r\n const captureSpan = (res: any, error?: Error) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: error ? 500 : res?.statusCode || 0,\r\n meta: { url: urlStr, method, library: 'http', error: error ? error.message : undefined }\r\n });\r\n };\r\n\r\n req.on('response', (res: any) => {\r\n res.once('end', () => captureSpan(res));\r\n res.once('error', (err: Error) => captureSpan(res, err));\r\n });\r\n\r\n req.on('error', (err: Error) => captureSpan(null, err));\r\n\r\n return req;\r\n };\r\n };\r\n\r\n shimmer(http, 'request', requestWrapper);\r\n shimmer(http, 'get', requestWrapper);\r\n shimmer(https, 'request', requestWrapper);\r\n shimmer(https, 'get', requestWrapper);\r\n};","import { Context } from '../core/context';\r\n\r\nexport const instrumentMongo = (debug = false) => {\r\n try {\r\n const mongodb = require('mongodb');\r\n const Collection = mongodb.Collection;\r\n\r\n // Attempt to get Cursor classes\r\n // Note: The location of these classes varies by driver version, \r\n // checking common locations\r\n const FindCursor = mongodb.FindCursor || require('mongodb/lib/cursor/find_cursor').FindCursor;\r\n const AggregationCursor = mongodb.AggregationCursor || require('mongodb/lib/cursor/aggregation_cursor').AggregationCursor;\r\n\r\n if (debug) console.log('[Senzor] Instrumenting MongoDB (Collection + Cursors)...');\r\n\r\n // --- Helper to Record Span ---\r\n const recordSpan = (name: string, operation: string, collection: string, startAbs: number, traceStart: number, err?: Error) => {\r\n const duration = performance.now() - startAbs;\r\n Context.addSpan({\r\n name: `MongoDB ${name}`,\r\n type: 'db',\r\n startTime: performance.now() - traceStart - duration, // Adjust start time to when op actually started\r\n duration,\r\n status: err ? 500 : 0,\r\n meta: { collection, operation, error: err ? err.message : undefined }\r\n });\r\n if (debug) console.log(`[Senzor] Captured Mongo: ${name} (${duration.toFixed(2)}ms)`);\r\n };\r\n\r\n // --- 1. Instrument Immediate Operations (Insert/Update/Delete) ---\r\n const immediateMethods = ['insertOne', 'insertMany', 'updateOne', 'updateMany', 'deleteOne', 'deleteMany', 'countDocuments'];\r\n\r\n immediateMethods.forEach((method) => {\r\n if (!Collection.prototype[method]) return;\r\n const original = Collection.prototype[method];\r\n\r\n Collection.prototype[method] = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n const collName = this.collectionName;\r\n\r\n try {\r\n const result = original.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(\r\n (res: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart); return res; },\r\n (err: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart, err); throw err; }\r\n );\r\n }\r\n return result;\r\n } catch (err: any) {\r\n recordSpan(method, method, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n }\r\n };\r\n });\r\n\r\n // --- 2. Instrument Cursor Execution (find -> toArray) ---\r\n const patchCursor = (CursorClass: any, label: string) => {\r\n if (!CursorClass || !CursorClass.prototype.toArray) return;\r\n\r\n const originalToArray = CursorClass.prototype.toArray;\r\n\r\n CursorClass.prototype.toArray = function (...args: any[]) {\r\n const trace = Context.current();\r\n // Cursors are often created in context but executed later. \r\n // We check context at execution time.\r\n if (!trace) return originalToArray.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n // Attempt to get collection name from cursor internal state\r\n const collName = this.namespace?.collection || 'unknown';\r\n\r\n const onSuccess = (res: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart);\r\n return res;\r\n };\r\n const onError = (err: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n };\r\n\r\n try {\r\n const result = originalToArray.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(onSuccess, onError);\r\n }\r\n return onSuccess(result);\r\n } catch (e) {\r\n onError(e);\r\n }\r\n };\r\n };\r\n\r\n patchCursor(FindCursor, 'find');\r\n patchCursor(AggregationCursor, 'aggregate');\r\n\r\n } catch (e: any) {\r\n if (debug) console.warn('[Senzor] MongoDB instrumentation warning:', e.message);\r\n }\r\n};","import { Context } from '../core/context';\r\n\r\n// Simple shim for 'pg' library\r\nexport const instrumentPg = () => {\r\n try {\r\n // Try to require pg (it might not be installed by user)\r\n const pg = require('pg');\r\n const originalQuery = pg.Client.prototype.query;\r\n\r\n pg.Client.prototype.query = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return originalQuery.apply(this, args);\r\n\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n\r\n // Extract SQL (first arg usually string or config object)\r\n const sql = typeof args[0] === 'string' ? args[0] : args[0].text;\r\n\r\n // Wrap callback if present, or handle Promise\r\n const result = originalQuery.apply(this, args);\r\n\r\n if (result && typeof result.then === 'function') {\r\n return result.then((res: any) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: 'Postgres Query',\r\n type: 'db',\r\n startTime,\r\n duration,\r\n meta: { query: sql }\r\n });\r\n return res;\r\n });\r\n }\r\n return result;\r\n };\r\n } catch (e) {\r\n // User doesn't use pg, ignore\r\n }\r\n};","import { client } from '../core/client';\r\n\r\n// 1. Request Handler (Place before routes)\r\nexport const expressMiddleware = () => {\r\n return (req: any, res: any, next: () => void) => {\r\n client.startTrace({\r\n method: req.method,\r\n path: req.originalUrl || req.url,\r\n ip: req.ip || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n }, () => {\r\n\r\n // Auto-detect status code on finish\r\n res.once('finish', () => {\r\n try {\r\n let route = 'UNKNOWN';\r\n // Express populates req.route only if a route matched\r\n if (req.route && req.route.path) {\r\n route = (req.baseUrl || '') + req.route.path;\r\n } else if (res.statusCode === 404) {\r\n route = 'Not Found';\r\n } else {\r\n route = req.path || 'Wildcard';\r\n }\r\n\r\n client.endTrace(res.statusCode, { route });\r\n } catch (e) { /* Fail open */ }\r\n });\r\n\r\n next();\r\n });\r\n };\r\n};\r\n\r\n// 2. Error Handler (Place after routes)\r\n// This is required in Express to capture the actual Error Object (Stack Trace)\r\nexport const expressErrorHandler = () => {\r\n return (err: any, req: any, res: any, next: (err?: any) => void) => {\r\n\r\n // 1. Capture the exception context\r\n client.captureError(err);\r\n\r\n // 2. Pass it to the next error handler (don't swallow it)\r\n next(err);\r\n };\r\n};","/**\r\n * Heuristic URL Normalizer\r\n * Converts raw paths with IDs into generic patterns to prevent high cardinality.\r\n * Example: /users/123/orders/abc-def -> /users/:id/orders/:uuid\r\n */\r\nexport const normalizePath = (path: string): string => {\r\n if (!path || path === '/') return '/';\r\n\r\n return path\r\n // Replace UUIDs (long alphanumeric strings)\r\n .replace(\r\n /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g,\r\n ':uuid'\r\n )\r\n // Replace MongoDB ObjectIds (24 hex chars)\r\n .replace(/[0-9a-fA-F]{24}/g, ':objectId')\r\n // Replace pure numeric IDs (e.g., /123)\r\n .replace(/\\/(\\d+)(?=\\/|$)/g, '/:id')\r\n // Remove query strings\r\n .split('?')[0];\r\n};\r\n\r\n/**\r\n * Tries to extract route from Framework internals, falls back to heuristic\r\n */\r\nexport const getRoute = (req: any, fallbackPath: string): string => {\r\n // Express / Connect\r\n if (req.route && req.route.path) {\r\n return (req.baseUrl || '') + req.route.path;\r\n }\r\n\r\n // H3 / Nitro (Nuxt)\r\n if (req.context && req.context.matchedRoute) {\r\n return req.context.matchedRoute.path;\r\n }\r\n\r\n // Fastify\r\n if (req.routerPath) {\r\n return req.routerPath;\r\n }\r\n\r\n // Fallback: Heuristic Normalization\r\n return normalizePath(fallbackPath);\r\n};","import { client } from '../core/client';\r\nimport { getRoute } from '../core/normalizer';\r\n\r\ntype EventHandler = (event: any) => any;\r\n\r\nexport const wrapH3 = (handler: EventHandler) => {\r\n return (event: any) => {\r\n const req = event.node.req;\r\n const path = req.originalUrl || req.url || '/';\r\n\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n }, async () => {\r\n try {\r\n const response = await handler(event);\r\n let status = 200;\r\n if (event.node.res.statusCode) status = event.node.res.statusCode;\r\n if (response && response.statusCode) status = response.statusCode;\r\n\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n return response;\r\n } catch (err: any) {\r\n // AUTOMATIC ERROR CAPTURE\r\n client.captureError(err);\r\n\r\n const status = err.statusCode || err.status || 500;\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n throw err;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { normalizePath } from '../core/normalizer';\r\n\r\n// --- App Router Wrapper ---\r\nexport const wrapNextRoute = (handler: Function) => {\r\n return async (req: Request | any, context?: any) => {\r\n const url = req.url ? new URL(req.url) : { pathname: '/' };\r\n const method = req.method || 'GET';\r\n const ua = req.headers.get ? req.headers.get('user-agent') : undefined;\r\n const ip = req.headers.get ? req.headers.get('x-forwarded-for') : undefined;\r\n\r\n return client.startTrace({\r\n method,\r\n path: url.pathname,\r\n userAgent: ua,\r\n ip: ip\r\n }, async () => {\r\n try {\r\n const response = await handler(req, context);\r\n const status = response?.status || 200;\r\n client.endTrace(status, { route: normalizePath(url.pathname) });\r\n return response;\r\n } catch (err: any) {\r\n // AUTOMATIC ERROR CAPTURE\r\n client.captureError(err);\r\n client.endTrace(500, { route: normalizePath(url.pathname) });\r\n throw err; // Re-throw so Next.js handles the error page\r\n }\r\n });\r\n };\r\n};\r\n\r\n// --- Pages Router Wrapper ---\r\nexport const wrapNextPages = (handler: Function) => {\r\n return async (req: any, res: any) => {\r\n const path = req.url ? req.url.split('?')[0] : '/';\r\n\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n userAgent: req.headers['user-agent'],\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n }, async () => {\r\n\r\n const done = () => {\r\n client.endTrace(res.statusCode || 200, { route: normalizePath(path) });\r\n };\r\n\r\n res.once('finish', done);\r\n res.once('close', done);\r\n\r\n try {\r\n return await handler(req, res);\r\n } catch (e: any) {\r\n // AUTOMATIC ERROR CAPTURE\r\n client.captureError(e);\r\n // Note: In Pages dir, we rely on 'finish' listener above to close trace, \r\n // but capturing here ensures the error data is attached.\r\n throw e;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { SenzorOptions } from '../core/types';\r\n\r\nexport const senzorPlugin = (fastify: any, options: SenzorOptions, done: Function) => {\r\n\r\n if (options && options.apiKey) {\r\n client.init(options);\r\n }\r\n\r\n // 1. Start Trace\r\n fastify.addHook('onRequest', (request: any, reply: any, next: Function) => {\r\n // FIX: Wrap next in a closure to satisfy TS types\r\n client.startTrace({\r\n method: request.method,\r\n path: request.raw.url || request.url,\r\n ip: request.ip,\r\n userAgent: request.headers['user-agent']\r\n }, () => next());\r\n });\r\n\r\n // 2. Capture Errors\r\n fastify.addHook('onError', (request: any, reply: any, error: any, next: Function) => {\r\n client.captureError(error);\r\n next();\r\n });\r\n\r\n // 3. End Trace\r\n fastify.addHook('onResponse', (request: any, reply: any, next: Function) => {\r\n const route = request.routeOptions?.url || request.routerPath || 'UNKNOWN';\r\n client.endTrace(reply.statusCode, { route });\r\n next();\r\n });\r\n\r\n done();\r\n};","import { client } from './core/client';\r\nimport { expressMiddleware, expressErrorHandler } from './middleware/express';\r\nimport { wrapH3 } from './wrappers/h3';\r\nimport { wrapNextRoute, wrapNextPages } from './wrappers/next';\r\nimport { senzorPlugin } from './wrappers/fastify';\r\nimport { SenzorOptions } from './core/types';\r\n\r\nconst Senzor = {\r\n init: (options: SenzorOptions) => client.init(options),\r\n flush: () => client.flush(),\r\n track: client.track.bind(client),\r\n startSpan: client.startSpan.bind(client),\r\n captureException: client.captureError.bind(client),\r\n\r\n // Express\r\n requestHandler: expressMiddleware,\r\n errorHandler: expressErrorHandler,\r\n\r\n // Next\r\n wrapNextRoute,\r\n wrapNextPages,\r\n\r\n // H3\r\n wrapH3,\r\n\r\n // Fastify\r\n fastifyPlugin: senzorPlugin\r\n};\r\n\r\nexport default Senzor;\r\nexport { Senzor };"],"mappings":"yPAEO,IAAMA,EAAN,KAAgB,CAIrB,YAAoBC,EAAuB,CAAvB,YAAAA,EAHpB,KAAQ,MAAe,CAAC,EACxB,KAAQ,MAA+B,KAGjC,OAAO,YAAgB,MACzB,KAAK,MAAQ,YAAY,IAAM,KAAK,MAAM,EAAGA,EAAO,eAAiB,GAAK,EACtE,KAAK,OAAS,OAAO,KAAK,MAAM,OAAU,YAC5C,KAAK,MAAM,MAAM,EAGvB,CAEO,IAAIC,EAAY,CACrB,KAAK,MAAM,KAAKA,CAAK,EACjB,KAAK,MAAM,SAAW,KAAK,OAAO,WAAa,MACjD,KAAK,MAAM,CAEf,CAEA,MAAa,OAAQ,CACnB,GAAI,KAAK,MAAM,SAAW,EAAG,OAE7B,IAAMC,EAAQ,CAAC,GAAG,KAAK,KAAK,EAC5B,KAAK,MAAQ,CAAC,EAEd,GAAI,CAEF,MAAM,MAAM,KAAK,OAAO,UAAY,wCAAyC,CAC3E,OAAQ,OACR,QAAS,CACP,eAAgB,mBAChB,oBAAq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H,EAAO,WAAW,CAChB,OAAQC,EAAQ,OAChB,KAAMA,EAAQ,IAAI,KAAOA,EAAQ,IACjC,GAAIA,EAAQ,GACZ,UAAWA,EAAQ,QAAQ,YAAY,CACzC,EAAG,IAAME,EAAK,CAAC,CACjB,CAAC,EAGDN,EAAQ,QAAQ,UAAW,CAACI,EAAcC,EAAYE,EAAYD,IAAmB,CACnFH,EAAO,aAAaI,CAAK,EACzBD,EAAK,CACP,CAAC,EAGDN,EAAQ,QAAQ,aAAc,CAACI,EAAcC,EAAYC,IAAmB,CAC1E,IAAME,EAAQJ,EAAQ,cAAc,KAAOA,EAAQ,YAAc,UACjED,EAAO,SAASE,EAAM,WAAY,CAAE,MAAAG,CAAM,CAAC,EAC3CF,EAAK,CACP,CAAC,EAEDJ,EAAK,CACP,EC3BA,IAAMO,EAAS,CACb,KAAOC,GAA2BC,EAAO,KAAKD,CAAO,EACrD,MAAO,IAAMC,EAAO,MAAM,EAC1B,MAAOA,EAAO,MAAM,KAAKA,CAAM,EAC/B,UAAWA,EAAO,UAAU,KAAKA,CAAM,EACvC,iBAAkBA,EAAO,aAAa,KAAKA,CAAM,EAGjD,eAAgBC,EAChB,aAAcC,EAGd,cAAAC,EACA,cAAAC,EAGA,OAAAC,EAGA,cAAeC,CACjB,EAEOC,GAAQT","names":["Transport","config","trace","batch","err","AsyncLocalStorage","storage","Context","trace","fn","span","store","error","randomUUID","http","https","URL","shimmer","module","methodName","wrapper","original","instrumentFetch","ingestUrl","debug","ingestHost","URL","originalFetch","input","init","urlStr","trace","Context","method","startTime","spanStartAbs","hostname","response","duration","err","instrumentHttp","requestWrapper","args","options","protocol","host","path","req","captureSpan","res","error","http","https","instrumentMongo","debug","mongodb","Collection","FindCursor","AggregationCursor","recordSpan","name","operation","collection","startAbs","traceStart","err","duration","Context","method","original","args","trace","spanStartAbs","collName","result","res","patchCursor","CursorClass","label","originalToArray","onSuccess","onError","e","instrumentPg","pg","originalQuery","args","trace","Context","startTime","spanStartAbs","sql","result","res","duration","SenzorClient","options","endpoint","debug","Transport","instrumentHttp","instrumentFetch","instrumentMongo","instrumentPg","data","next","trace","randomUUID","Context","status","extraData","duration","payload","error","name","type","startTime","spanStartAbs","meta","client","expressMiddleware","req","res","next","client","route","expressErrorHandler","err","normalizePath","path","getRoute","req","fallbackPath","wrapH3","handler","event","req","path","client","response","status","getRoute","err","wrapNextRoute","handler","req","context","url","method","ua","ip","client","response","status","normalizePath","err","wrapNextPages","res","path","done","e","senzorPlugin","fastify","options","done","client","request","reply","next","error","route","Senzor","options","client","expressMiddleware","expressErrorHandler","wrapNextRoute","wrapNextPages","wrapH3","senzorPlugin","index_default"]}
1
+ {"version":3,"sources":["../src/core/transport.ts","../src/core/context.ts","../src/core/client.ts","../src/instrumentation/http.ts","../src/instrumentation/mongo.ts","../src/instrumentation/pg.ts","../src/middleware/express.ts","../src/core/normalizer.ts","../src/wrappers/h3.ts","../src/wrappers/next.ts","../src/wrappers/fastify.ts","../src/index.ts"],"sourcesContent":["import { SenzorOptions } from './types';\r\n\r\nexport class Transport {\r\n private queue: any[] = [];\r\n private timer: NodeJS.Timeout | null = null;\r\n\r\n constructor(private config: SenzorOptions) {\r\n if (typeof setInterval !== 'undefined') {\r\n this.timer = setInterval(() => this.flush(), config.flushInterval || 10000);\r\n if (this.timer && typeof this.timer.unref === 'function') {\r\n this.timer.unref(); // Don't block process exit\r\n }\r\n }\r\n }\r\n\r\n public add(trace: any) {\r\n this.queue.push(trace);\r\n if (this.queue.length >= (this.config.batchSize || 100)) {\r\n this.flush();\r\n }\r\n }\r\n\r\n public async flush() {\r\n if (this.queue.length === 0) return;\r\n\r\n const batch = [...this.queue];\r\n this.queue = [];\r\n\r\n try {\r\n // Use global fetch (Node 18+)\r\n await fetch(this.config.endpoint || 'https://api.senzor.dev/api/ingest/apm', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'x-service-api-key': this.config.apiKey,\r\n },\r\n body: JSON.stringify(batch),\r\n keepalive: true,\r\n });\r\n \r\n if (this.config.debug) console.log(`[Senzor] Flushed ${batch.length} traces`);\r\n } catch (err) {\r\n if (this.config.debug) console.error('[Senzor] Ingestion Error:', err);\r\n // Dropping data to prevent memory leaks is preferred in APM\r\n }\r\n }\r\n}","import { AsyncLocalStorage } from 'async_hooks';\r\nimport { ActiveTrace, TraceError } from './types';\r\n\r\nexport const storage = new AsyncLocalStorage<ActiveTrace>();\r\n\r\nexport const Context = {\r\n run: <T>(trace: ActiveTrace, fn: () => T): T => {\r\n return storage.run(trace, fn);\r\n },\r\n\r\n current: (): ActiveTrace | undefined => {\r\n return storage.getStore();\r\n },\r\n\r\n addSpan: (span: any) => {\r\n const store = storage.getStore();\r\n if (store) {\r\n store.spans.push(span);\r\n }\r\n },\r\n\r\n // Attach error to current trace\r\n setError: (error: Error) => {\r\n const store = storage.getStore();\r\n if (store) {\r\n store.error = {\r\n name: error.name,\r\n message: error.message,\r\n stack: error.stack\r\n };\r\n }\r\n }\r\n};","import { Transport } from './transport';\r\nimport { Context } from './context';\r\nimport { SenzorOptions, ActiveTrace } from './types';\r\nimport { randomUUID } from 'crypto';\r\nimport { instrumentHttp, instrumentFetch } from '../instrumentation/http';\r\nimport { instrumentMongo } from '../instrumentation/mongo';\r\nimport { instrumentPg } from '../instrumentation/pg';\r\n\r\nexport class SenzorClient {\r\n private transport: Transport | null = null;\r\n private options: SenzorOptions | null = null;\r\n private isInstrumented = false;\r\n\r\n public init(options: SenzorOptions) {\r\n if (!options.apiKey) {\r\n console.warn('[Senzor] API Key missing. SDK disabled.');\r\n return;\r\n }\r\n this.options = options;\r\n const endpoint = options.endpoint || 'https://api.senzor.dev/api/ingest/apm';\r\n const debug = options.debug || false;\r\n\r\n this.transport = new Transport({ ...options, endpoint });\r\n\r\n if (!this.isInstrumented) {\r\n try { instrumentHttp(endpoint, debug); } catch (e) { }\r\n try { instrumentFetch(endpoint, debug); } catch (e) { }\r\n try { instrumentMongo(debug); } catch (e) { }\r\n try { instrumentPg(); } catch (e) { }\r\n\r\n this.isInstrumented = true;\r\n if (debug) console.log('[Senzor] Auto-instrumentation enabled');\r\n }\r\n }\r\n\r\n public startTrace<T>(data: Partial<ActiveTrace['data']> & { headers?: any }, next: () => T): T {\r\n if (!this.transport) return next();\r\n\r\n // Trace Propagation Extraction\r\n let parentTraceId = undefined;\r\n let parentSpanId = undefined;\r\n\r\n if (data.headers) {\r\n // Robust header checking (Node headers are usually lowercase, but handle mixed)\r\n const getHeader = (key: string) => {\r\n // Direct access\r\n if (data.headers[key]) return data.headers[key];\r\n if (data.headers[key.toLowerCase()]) return data.headers[key.toLowerCase()];\r\n if (data.headers[key.toUpperCase()]) return data.headers[key.toUpperCase()];\r\n return undefined;\r\n };\r\n\r\n parentTraceId = getHeader('x-senzor-trace-id');\r\n parentSpanId = getHeader('x-senzor-parent-span-id');\r\n }\r\n\r\n const trace: ActiveTrace = {\r\n id: randomUUID(),\r\n startTime: performance.now(),\r\n data: {\r\n ...data,\r\n parentTraceId,\r\n parentSpanId\r\n },\r\n spans: []\r\n };\r\n\r\n return Context.run(trace, next);\r\n }\r\n\r\n public endTrace(status: number, extraData: any = {}) {\r\n const trace = Context.current();\r\n if (!trace || !this.transport) return;\r\n const duration = performance.now() - trace.startTime;\r\n\r\n const payload = {\r\n traceId: trace.id,\r\n parentTraceId: trace.data.parentTraceId,\r\n parentSpanId: trace.data.parentSpanId,\r\n ...trace.data,\r\n ...extraData,\r\n status, duration, spans: trace.spans, timestamp: new Date().toISOString(),\r\n error: trace.error\r\n };\r\n this.transport.add(payload);\r\n }\r\n\r\n // --- NEW: Capture Exception ---\r\n public captureError(error: unknown) {\r\n if (error instanceof Error) {\r\n Context.setError(error);\r\n } else if (typeof error === 'string') {\r\n Context.setError(new Error(error));\r\n }\r\n }\r\n\r\n public track(data: any) { this.transport?.add({ traceId: randomUUID(), ...data, spans: [], timestamp: new Date().toISOString() }); }\r\n\r\n public startSpan(name: string, type: 'db' | 'http' | 'function' | 'custom' = 'custom') {\r\n const trace = Context.current();\r\n if (!trace) return { end: () => { } };\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n const spanId = randomUUID();\r\n return { end: (meta?: any, status?: number) => { Context.addSpan({ spanId, name, type, startTime, duration: performance.now() - spanStartAbs, status, meta }); } };\r\n }\r\n\r\n public async flush() { if (this.transport) await this.transport.flush(); }\r\n}\r\n\r\nexport const client = new SenzorClient();","import http from 'http';\r\nimport https from 'https';\r\nimport { URL } from 'url';\r\nimport { Context } from '../core/context';\r\nimport { randomUUID } from 'crypto';\r\n\r\nconst shimmer = (module: any, methodName: string, wrapper: (original: Function) => Function) => {\r\n if (!module[methodName]) return;\r\n const original = module[methodName];\r\n module[methodName] = wrapper(original);\r\n};\r\n\r\n// --- FETCH INSTRUMENTATION ---\r\nexport const instrumentFetch = (ingestUrl: string, debug = false) => {\r\n if (!globalThis.fetch) return;\r\n\r\n let ingestHost = '';\r\n try { ingestHost = new URL(ingestUrl).hostname; } catch (e) { }\r\n\r\n const originalFetch = globalThis.fetch;\r\n\r\n // @ts-ignore\r\n globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {\r\n let urlStr = '';\r\n if (typeof input === 'string') urlStr = input;\r\n else if (input instanceof URL) urlStr = input.toString();\r\n else if (input && (input as any).url) urlStr = (input as any).url;\r\n\r\n if (ingestHost && urlStr.includes(ingestHost)) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n const trace = Context.current();\r\n if (!trace) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n const method = (init?.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n const spanId = randomUUID();\r\n\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { }\r\n\r\n // Inject Headers\r\n const newInit = { ...init } as RequestInit;\r\n if (!newInit.headers) newInit.headers = {};\r\n\r\n // Helper to set header on various types\r\n const setHeader = (key: string, value: string) => {\r\n if (newInit.headers instanceof Headers) {\r\n newInit.headers.set(key, value);\r\n } else if (Array.isArray(newInit.headers)) {\r\n newInit.headers.push([key, value]);\r\n } else {\r\n (newInit.headers as any)[key] = value;\r\n }\r\n };\r\n\r\n setHeader('x-senzor-trace-id', trace.id);\r\n setHeader('x-senzor-parent-span-id', spanId);\r\n\r\n try {\r\n const response = await originalFetch(input, newInit);\r\n\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n spanId,\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: response.status,\r\n meta: { url: urlStr, method, library: 'fetch' }\r\n });\r\n\r\n return response;\r\n } catch (err: any) {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n spanId,\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: 500,\r\n meta: { error: err.message, url: urlStr, library: 'fetch' }\r\n });\r\n throw err;\r\n }\r\n };\r\n};\r\n\r\n// --- HTTP/HTTPS INSTRUMENTATION ---\r\nexport const instrumentHttp = (ingestUrl: string, debug = false) => {\r\n let ingestHost = '';\r\n try { ingestHost = new URL(ingestUrl).hostname; } catch (e) { }\r\n\r\n const requestWrapper = (original: Function) => {\r\n return function (this: any, ...args: any[]) {\r\n let options: any = {};\r\n let urlStr = '';\r\n let optionsIndex = 0;\r\n\r\n // Parsing Logic: http.request(url, options, cb) OR http.request(options, cb)\r\n if (typeof args[0] === 'string' || args[0] instanceof URL) {\r\n urlStr = args[0].toString();\r\n optionsIndex = 1;\r\n } else {\r\n optionsIndex = 0;\r\n }\r\n\r\n // Ensure options object exists at correct index\r\n if (!args[optionsIndex] || typeof args[optionsIndex] !== 'object') {\r\n args[optionsIndex] = {};\r\n }\r\n options = args[optionsIndex];\r\n\r\n // Construct URL if missing\r\n if (!urlStr) {\r\n const protocol = options.protocol || (options.port === 443 ? 'https:' : 'http:');\r\n const host = options.hostname || options.host || 'localhost';\r\n const path = options.path || '/';\r\n urlStr = `${protocol}//${host}${path}`;\r\n }\r\n\r\n // Guard\r\n if (ingestHost && (urlStr.includes(ingestHost) || (options.hostname && options.hostname.includes(ingestHost)))) {\r\n return original.apply(this, args);\r\n }\r\n\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const method = (options.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n const spanId = randomUUID();\r\n\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { hostname = options.hostname || 'unknown'; }\r\n\r\n // Inject Headers (Mutate the options object reference directly)\r\n if (!options.headers) options.headers = {};\r\n options.headers['x-senzor-trace-id'] = trace.id;\r\n options.headers['x-senzor-parent-span-id'] = spanId;\r\n\r\n // Debug\r\n if (debug) console.log(`[Senzor] Injecting headers to ${urlStr}`);\r\n\r\n // Call Original\r\n const req = original.apply(this, args);\r\n\r\n const captureSpan = (res: any, error?: Error) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n spanId,\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: error ? 500 : res?.statusCode || 0,\r\n meta: { url: urlStr, method, library: 'http' }\r\n });\r\n };\r\n\r\n req.on('response', (res: any) => {\r\n res.once('end', () => captureSpan(res));\r\n res.once('close', () => captureSpan(res));\r\n res.once('error', (err: Error) => captureSpan(res, err));\r\n });\r\n\r\n req.on('error', (err: Error) => captureSpan(null, err));\r\n\r\n return req;\r\n };\r\n };\r\n\r\n shimmer(http, 'request', requestWrapper);\r\n shimmer(http, 'get', requestWrapper);\r\n shimmer(https, 'request', requestWrapper);\r\n shimmer(https, 'get', requestWrapper);\r\n};","import { Context } from '../core/context';\r\n\r\nexport const instrumentMongo = (debug = false) => {\r\n try {\r\n const mongodb = require('mongodb');\r\n const Collection = mongodb.Collection;\r\n\r\n // Attempt to get Cursor classes\r\n // Note: The location of these classes varies by driver version, \r\n // checking common locations\r\n const FindCursor = mongodb.FindCursor || require('mongodb/lib/cursor/find_cursor').FindCursor;\r\n const AggregationCursor = mongodb.AggregationCursor || require('mongodb/lib/cursor/aggregation_cursor').AggregationCursor;\r\n\r\n if (debug) console.log('[Senzor] Instrumenting MongoDB (Collection + Cursors)...');\r\n\r\n // --- Helper to Record Span ---\r\n const recordSpan = (name: string, operation: string, collection: string, startAbs: number, traceStart: number, err?: Error) => {\r\n const duration = performance.now() - startAbs;\r\n Context.addSpan({\r\n name: `MongoDB ${name}`,\r\n type: 'db',\r\n startTime: performance.now() - traceStart - duration, // Adjust start time to when op actually started\r\n duration,\r\n status: err ? 500 : 0,\r\n meta: { collection, operation, error: err ? err.message : undefined }\r\n });\r\n if (debug) console.log(`[Senzor] Captured Mongo: ${name} (${duration.toFixed(2)}ms)`);\r\n };\r\n\r\n // --- 1. Instrument Immediate Operations (Insert/Update/Delete) ---\r\n const immediateMethods = ['insertOne', 'insertMany', 'updateOne', 'updateMany', 'deleteOne', 'deleteMany', 'countDocuments'];\r\n\r\n immediateMethods.forEach((method) => {\r\n if (!Collection.prototype[method]) return;\r\n const original = Collection.prototype[method];\r\n\r\n Collection.prototype[method] = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n const collName = this.collectionName;\r\n\r\n try {\r\n const result = original.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(\r\n (res: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart); return res; },\r\n (err: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart, err); throw err; }\r\n );\r\n }\r\n return result;\r\n } catch (err: any) {\r\n recordSpan(method, method, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n }\r\n };\r\n });\r\n\r\n // --- 2. Instrument Cursor Execution (find -> toArray) ---\r\n const patchCursor = (CursorClass: any, label: string) => {\r\n if (!CursorClass || !CursorClass.prototype.toArray) return;\r\n\r\n const originalToArray = CursorClass.prototype.toArray;\r\n\r\n CursorClass.prototype.toArray = function (...args: any[]) {\r\n const trace = Context.current();\r\n // Cursors are often created in context but executed later. \r\n // We check context at execution time.\r\n if (!trace) return originalToArray.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n // Attempt to get collection name from cursor internal state\r\n const collName = this.namespace?.collection || 'unknown';\r\n\r\n const onSuccess = (res: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart);\r\n return res;\r\n };\r\n const onError = (err: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n };\r\n\r\n try {\r\n const result = originalToArray.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(onSuccess, onError);\r\n }\r\n return onSuccess(result);\r\n } catch (e) {\r\n onError(e);\r\n }\r\n };\r\n };\r\n\r\n patchCursor(FindCursor, 'find');\r\n patchCursor(AggregationCursor, 'aggregate');\r\n\r\n } catch (e: any) {\r\n if (debug) console.warn('[Senzor] MongoDB instrumentation warning:', e.message);\r\n }\r\n};","import { Context } from '../core/context';\r\n\r\n// Simple shim for 'pg' library\r\nexport const instrumentPg = () => {\r\n try {\r\n // Try to require pg (it might not be installed by user)\r\n const pg = require('pg');\r\n const originalQuery = pg.Client.prototype.query;\r\n\r\n pg.Client.prototype.query = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return originalQuery.apply(this, args);\r\n\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n\r\n // Extract SQL (first arg usually string or config object)\r\n const sql = typeof args[0] === 'string' ? args[0] : args[0].text;\r\n\r\n // Wrap callback if present, or handle Promise\r\n const result = originalQuery.apply(this, args);\r\n\r\n if (result && typeof result.then === 'function') {\r\n return result.then((res: any) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: 'Postgres Query',\r\n type: 'db',\r\n startTime,\r\n duration,\r\n meta: { query: sql }\r\n });\r\n return res;\r\n });\r\n }\r\n return result;\r\n };\r\n } catch (e) {\r\n // User doesn't use pg, ignore\r\n }\r\n};","import { client } from '../core/client';\r\n\r\n// 1. Request Handler (Place before routes)\r\nexport const expressMiddleware = () => {\r\n return (req: any, res: any, next: () => void) => {\r\n client.startTrace({\r\n method: req.method,\r\n path: req.originalUrl || req.url,\r\n ip: req.ip || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n headers: req.headers\r\n }, () => {\r\n\r\n // Auto-detect status code on finish\r\n res.once('finish', () => {\r\n try {\r\n let route = 'UNKNOWN';\r\n // Express populates req.route only if a route matched\r\n if (req.route && req.route.path) {\r\n route = (req.baseUrl || '') + req.route.path;\r\n } else if (res.statusCode === 404) {\r\n route = 'Not Found';\r\n } else {\r\n route = req.path || 'Wildcard';\r\n }\r\n\r\n client.endTrace(res.statusCode, { route });\r\n } catch (e) { /* Fail open */ }\r\n });\r\n\r\n next();\r\n });\r\n };\r\n};\r\n\r\n// 2. Error Handler (Place after routes)\r\n// This is required in Express to capture the actual Error Object (Stack Trace)\r\nexport const expressErrorHandler = () => {\r\n return (err: any, req: any, res: any, next: (err?: any) => void) => {\r\n\r\n // 1. Capture the exception context\r\n client.captureError(err);\r\n\r\n // 2. Pass it to the next error handler (don't swallow it)\r\n next(err);\r\n };\r\n};","/**\r\n * Heuristic URL Normalizer\r\n * Converts raw paths with IDs into generic patterns to prevent high cardinality.\r\n * Example: /users/123/orders/abc-def -> /users/:id/orders/:uuid\r\n */\r\nexport const normalizePath = (path: string): string => {\r\n if (!path || path === '/') return '/';\r\n\r\n return path\r\n // Replace UUIDs (long alphanumeric strings)\r\n .replace(\r\n /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g,\r\n ':uuid'\r\n )\r\n // Replace MongoDB ObjectIds (24 hex chars)\r\n .replace(/[0-9a-fA-F]{24}/g, ':objectId')\r\n // Replace pure numeric IDs (e.g., /123)\r\n .replace(/\\/(\\d+)(?=\\/|$)/g, '/:id')\r\n // Remove query strings\r\n .split('?')[0];\r\n};\r\n\r\n/**\r\n * Tries to extract route from Framework internals, falls back to heuristic\r\n */\r\nexport const getRoute = (req: any, fallbackPath: string): string => {\r\n // Express / Connect\r\n if (req.route && req.route.path) {\r\n return (req.baseUrl || '') + req.route.path;\r\n }\r\n\r\n // H3 / Nitro (Nuxt)\r\n if (req.context && req.context.matchedRoute) {\r\n return req.context.matchedRoute.path;\r\n }\r\n\r\n // Fastify\r\n if (req.routerPath) {\r\n return req.routerPath;\r\n }\r\n\r\n // Fallback: Heuristic Normalization\r\n return normalizePath(fallbackPath);\r\n};","import { client } from '../core/client';\r\nimport { getRoute } from '../core/normalizer';\r\n\r\ntype EventHandler = (event: any) => any;\r\n\r\nexport const wrapH3 = (handler: EventHandler) => {\r\n return (event: any) => {\r\n const req = event.node.req;\r\n const path = req.originalUrl || req.url || '/';\r\n\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n headers: req.headers // Pass headers\r\n }, async () => {\r\n try {\r\n const response = await handler(event);\r\n let status = 200;\r\n if (event.node.res.statusCode) status = event.node.res.statusCode;\r\n if (response && response.statusCode) status = response.statusCode;\r\n\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n return response;\r\n } catch (err: any) {\r\n client.captureError(err);\r\n const status = err.statusCode || err.status || 500;\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n throw err;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { normalizePath } from '../core/normalizer';\r\n\r\n// --- App Router Wrapper ---\r\nexport const wrapNextRoute = (handler: Function) => {\r\n return async (req: Request | any, context?: any) => {\r\n\r\n // Extract info from Web Standard Request\r\n const url = req.url ? new URL(req.url) : { pathname: '/' };\r\n const method = req.method || 'GET';\r\n\r\n // Header Extraction\r\n let headers: Record<string, string> = {};\r\n let ua: string | undefined;\r\n let ip: string | undefined;\r\n\r\n if (typeof req.headers.get === 'function') {\r\n // It's a Web Request Object\r\n ua = req.headers.get('user-agent');\r\n ip = req.headers.get('x-forwarded-for');\r\n\r\n // Convert to plain object for trace context extraction\r\n req.headers.forEach((value: string, key: string) => {\r\n headers[key] = value;\r\n });\r\n } else {\r\n // It's a Node Request Object (rare in App router but possible)\r\n headers = req.headers;\r\n ua = headers['user-agent'];\r\n ip = headers['x-forwarded-for'] as string;\r\n }\r\n\r\n return client.startTrace({\r\n method,\r\n path: url.pathname,\r\n userAgent: ua,\r\n ip: ip,\r\n headers: headers // Pass extracted headers\r\n }, async () => {\r\n try {\r\n const response = await handler(req, context);\r\n const status = response?.status || 200;\r\n\r\n client.endTrace(status, { route: normalizePath(url.pathname) });\r\n return response;\r\n } catch (err: any) {\r\n client.captureError(err);\r\n client.endTrace(500, { route: normalizePath(url.pathname) });\r\n throw err;\r\n }\r\n });\r\n };\r\n};\r\n\r\n// --- Pages Router Wrapper ---\r\nexport const wrapNextPages = (handler: Function) => {\r\n return async (req: any, res: any) => {\r\n const path = req.url ? req.url.split('?')[0] : '/';\r\n\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n userAgent: req.headers['user-agent'],\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n headers: req.headers // Standard Node headers work fine\r\n }, async () => {\r\n\r\n const done = () => {\r\n client.endTrace(res.statusCode || 200, { route: normalizePath(path) });\r\n };\r\n\r\n res.once('finish', done);\r\n res.once('close', done);\r\n\r\n try {\r\n return await handler(req, res);\r\n } catch (e: any) {\r\n client.captureError(e);\r\n throw e;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { SenzorOptions } from '../core/types';\r\n\r\nexport const senzorPlugin = (fastify: any, options: SenzorOptions, done: Function) => {\r\n if (options && options.apiKey) {\r\n client.init(options);\r\n }\r\n\r\n fastify.addHook('onRequest', (request: any, reply: any, next: Function) => {\r\n client.startTrace({\r\n method: request.method,\r\n path: request.raw.url || request.url,\r\n ip: request.ip,\r\n userAgent: request.headers['user-agent'],\r\n headers: request.headers // Pass headers\r\n }, () => next());\r\n });\r\n\r\n fastify.addHook('onError', (request: any, reply: any, error: any, next: Function) => {\r\n client.captureError(error);\r\n next();\r\n });\r\n\r\n fastify.addHook('onResponse', (request: any, reply: any, next: Function) => {\r\n const route = request.routeOptions?.url || request.routerPath || 'UNKNOWN';\r\n client.endTrace(reply.statusCode, { route });\r\n next();\r\n });\r\n\r\n done();\r\n};","import { client } from './core/client';\r\nimport { expressMiddleware, expressErrorHandler } from './middleware/express';\r\nimport { wrapH3 } from './wrappers/h3';\r\nimport { wrapNextRoute, wrapNextPages } from './wrappers/next';\r\nimport { senzorPlugin } from './wrappers/fastify';\r\nimport { SenzorOptions } from './core/types';\r\n\r\nconst Senzor = {\r\n init: (options: SenzorOptions) => client.init(options),\r\n flush: () => client.flush(),\r\n track: client.track.bind(client),\r\n startSpan: client.startSpan.bind(client),\r\n captureException: client.captureError.bind(client),\r\n\r\n // Express\r\n requestHandler: expressMiddleware,\r\n errorHandler: expressErrorHandler,\r\n\r\n // Next\r\n wrapNextRoute,\r\n wrapNextPages,\r\n\r\n // H3\r\n wrapH3,\r\n\r\n // Fastify\r\n fastifyPlugin: senzorPlugin\r\n};\r\n\r\nexport default Senzor;\r\nexport { Senzor };"],"mappings":"yPAEO,IAAMA,EAAN,KAAgB,CAIrB,YAAoBC,EAAuB,CAAvB,YAAAA,EAHpB,KAAQ,MAAe,CAAC,EACxB,KAAQ,MAA+B,KAGjC,OAAO,YAAgB,MACzB,KAAK,MAAQ,YAAY,IAAM,KAAK,MAAM,EAAGA,EAAO,eAAiB,GAAK,EACtE,KAAK,OAAS,OAAO,KAAK,MAAM,OAAU,YAC5C,KAAK,MAAM,MAAM,EAGvB,CAEO,IAAIC,EAAY,CACrB,KAAK,MAAM,KAAKA,CAAK,EACjB,KAAK,MAAM,SAAW,KAAK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KA,CAAM,EAGjD,eAAgBC,EAChB,aAAcC,EAGd,cAAAC,EACA,cAAAC,EAGA,OAAAC,EAGA,cAAeC,CACjB,EAEOC,GAAQT","names":["Transport","config","trace","batch","err","AsyncLocalStorage","storage","Context","trace","fn","span","store","error","randomUUID","http","https","URL","randomUUID","shimmer","module","methodName","wrapper","original","instrumentFetch","ingestUrl","debug","ingestHost","URL","originalFetch","input","init","urlStr","trace","Context","method","startTime","spanStartAbs","spanId","hostname","newInit","setHeader","key","value","response","duration","err","instrumentHttp","requestWrapper","args","options","optionsIndex","protocol","host","path","req","captureSpan","res","error","http","https","instrumentMongo","debug","mongodb","Collection","FindCursor","AggregationCursor","recordSpan","name","operation","collection","startAbs","traceStart","err","duration","Context","method","original","args","trace","spanStartAbs","collName","result","res","patchCursor","CursorClass","label","originalToArray","onSuccess","onError","e","instrumentPg","pg","originalQuery","args","trace","Context","startTime","spanStartAbs","sql","result","res","duration","SenzorClient","options","endpoint","debug","Transport","instrumentHttp","instrumentFetch","instrumentMongo","instrumentPg","data","next","parentTraceId","parentSpanId","getHeader","key","trace","randomUUID","Context","status","extraData","duration","payload","error","name","type","startTime","spanStartAbs","spanId","meta","client","expressMiddleware","req","res","next","client","route","expressErrorHandler","err","normalizePath","path","getRoute","req","fallbackPath","wrapH3","handler","event","req","path","client","response","status","getRoute","err","wrapNextRoute","handler","req","context","url","method","headers","ua","ip","value","key","client","response","status","normalizePath","err","wrapNextPages","res","path","done","e","senzorPlugin","fastify","options","done","client","request","reply","next","error","route","Senzor","options","client","expressMiddleware","expressErrorHandler","wrapNextRoute","wrapNextPages","wrapH3","senzorPlugin","index_default"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senzops/apm-node",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "description": "Universal APM SDK for Senzor",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -33,34 +33,55 @@ export class SenzorClient {
33
33
  }
34
34
  }
35
35
 
36
- public startTrace<T>(data: Partial<ActiveTrace['data']>, next: () => T): T {
36
+ public startTrace<T>(data: Partial<ActiveTrace['data']> & { headers?: any }, next: () => T): T {
37
37
  if (!this.transport) return next();
38
+
39
+ // Trace Propagation Extraction
40
+ let parentTraceId = undefined;
41
+ let parentSpanId = undefined;
42
+
43
+ if (data.headers) {
44
+ // Robust header checking (Node headers are usually lowercase, but handle mixed)
45
+ const getHeader = (key: string) => {
46
+ // Direct access
47
+ if (data.headers[key]) return data.headers[key];
48
+ if (data.headers[key.toLowerCase()]) return data.headers[key.toLowerCase()];
49
+ if (data.headers[key.toUpperCase()]) return data.headers[key.toUpperCase()];
50
+ return undefined;
51
+ };
52
+
53
+ parentTraceId = getHeader('x-senzor-trace-id');
54
+ parentSpanId = getHeader('x-senzor-parent-span-id');
55
+ }
56
+
38
57
  const trace: ActiveTrace = {
39
58
  id: randomUUID(),
40
59
  startTime: performance.now(),
41
- data: data,
60
+ data: {
61
+ ...data,
62
+ parentTraceId,
63
+ parentSpanId
64
+ },
42
65
  spans: []
43
66
  };
67
+
44
68
  return Context.run(trace, next);
45
69
  }
46
70
 
47
71
  public endTrace(status: number, extraData: any = {}) {
48
72
  const trace = Context.current();
49
73
  if (!trace || !this.transport) return;
50
-
51
74
  const duration = performance.now() - trace.startTime;
52
75
 
53
76
  const payload = {
54
77
  traceId: trace.id,
78
+ parentTraceId: trace.data.parentTraceId,
79
+ parentSpanId: trace.data.parentSpanId,
55
80
  ...trace.data,
56
81
  ...extraData,
57
- status,
58
- duration,
59
- spans: trace.spans,
60
- error: trace.error, // Include Error if captured
61
- timestamp: new Date().toISOString()
82
+ status, duration, spans: trace.spans, timestamp: new Date().toISOString(),
83
+ error: trace.error
62
84
  };
63
-
64
85
  this.transport.add(payload);
65
86
  }
66
87
 
@@ -73,7 +94,6 @@ export class SenzorClient {
73
94
  }
74
95
  }
75
96
 
76
- // ... (manual track, startSpan, flush remain same) ...
77
97
  public track(data: any) { this.transport?.add({ traceId: randomUUID(), ...data, spans: [], timestamp: new Date().toISOString() }); }
78
98
 
79
99
  public startSpan(name: string, type: 'db' | 'http' | 'function' | 'custom' = 'custom') {
@@ -81,7 +101,8 @@ export class SenzorClient {
81
101
  if (!trace) return { end: () => { } };
82
102
  const startTime = performance.now() - trace.startTime;
83
103
  const spanStartAbs = performance.now();
84
- return { end: (meta?: any, status?: number) => { Context.addSpan({ name, type, startTime, duration: performance.now() - spanStartAbs, status, meta }); } };
104
+ const spanId = randomUUID();
105
+ return { end: (meta?: any, status?: number) => { Context.addSpan({ spanId, name, type, startTime, duration: performance.now() - spanStartAbs, status, meta }); } };
85
106
  }
86
107
 
87
108
  public async flush() { if (this.transport) await this.transport.flush(); }
package/src/core/types.ts CHANGED
@@ -7,6 +7,7 @@ export interface SenzorOptions {
7
7
  }
8
8
 
9
9
  export interface Span {
10
+ spanId: string; // NEW: Unique ID for this span
10
11
  name: string;
11
12
  type: 'db' | 'http' | 'function' | 'custom';
12
13
  startTime: number;
@@ -23,6 +24,11 @@ export interface TraceError {
23
24
 
24
25
  export interface Trace {
25
26
  traceId: string;
27
+
28
+ // Distributed Tracing Fields
29
+ parentTraceId?: string; // NEW
30
+ parentSpanId?: string; // NEW
31
+
26
32
  method: string;
27
33
  route: string;
28
34
  path: string;
@@ -2,6 +2,7 @@ import http from 'http';
2
2
  import https from 'https';
3
3
  import { URL } from 'url';
4
4
  import { Context } from '../core/context';
5
+ import { randomUUID } from 'crypto';
5
6
 
6
7
  const shimmer = (module: any, methodName: string, wrapper: (original: Function) => Function) => {
7
8
  if (!module[methodName]) return;
@@ -9,7 +10,7 @@ const shimmer = (module: any, methodName: string, wrapper: (original: Function)
9
10
  module[methodName] = wrapper(original);
10
11
  };
11
12
 
12
- // --- Native Fetch Instrumentation (Node 18+) ---
13
+ // --- FETCH INSTRUMENTATION ---
13
14
  export const instrumentFetch = (ingestUrl: string, debug = false) => {
14
15
  if (!globalThis.fetch) return;
15
16
 
@@ -20,38 +21,52 @@ export const instrumentFetch = (ingestUrl: string, debug = false) => {
20
21
 
21
22
  // @ts-ignore
22
23
  globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
23
- // 1. Extract URL
24
24
  let urlStr = '';
25
25
  if (typeof input === 'string') urlStr = input;
26
26
  else if (input instanceof URL) urlStr = input.toString();
27
- else if (input && input.url) urlStr = input.url; // Request object
27
+ else if (input && (input as any).url) urlStr = (input as any).url;
28
28
 
29
- // 2. Infinite Loop Guard
30
29
  if (ingestHost && urlStr.includes(ingestHost)) {
31
30
  return originalFetch(input, init);
32
31
  }
33
32
 
34
- // 3. Context Check
35
33
  const trace = Context.current();
36
34
  if (!trace) {
37
35
  return originalFetch(input, init);
38
36
  }
39
37
 
40
- // 4. Start Span
41
38
  const method = (init?.method || 'GET').toUpperCase();
42
39
  const startTime = performance.now() - trace.startTime;
43
40
  const spanStartAbs = performance.now();
41
+ const spanId = randomUUID();
42
+
44
43
  let hostname = 'unknown';
45
44
  try { hostname = new URL(urlStr).hostname; } catch (e) { }
46
45
 
47
- if (debug) console.log(`[Senzor] Tracking Fetch: ${method} ${hostname}`);
46
+ // Inject Headers
47
+ const newInit = { ...init } as RequestInit;
48
+ if (!newInit.headers) newInit.headers = {};
49
+
50
+ // Helper to set header on various types
51
+ const setHeader = (key: string, value: string) => {
52
+ if (newInit.headers instanceof Headers) {
53
+ newInit.headers.set(key, value);
54
+ } else if (Array.isArray(newInit.headers)) {
55
+ newInit.headers.push([key, value]);
56
+ } else {
57
+ (newInit.headers as any)[key] = value;
58
+ }
59
+ };
60
+
61
+ setHeader('x-senzor-trace-id', trace.id);
62
+ setHeader('x-senzor-parent-span-id', spanId);
48
63
 
49
64
  try {
50
- const response = await originalFetch(input, init);
65
+ const response = await originalFetch(input, newInit);
51
66
 
52
- // 5. End Span
53
67
  const duration = performance.now() - spanStartAbs;
54
68
  Context.addSpan({
69
+ spanId,
55
70
  name: `${method} ${hostname}`,
56
71
  type: 'http',
57
72
  startTime,
@@ -64,6 +79,7 @@ export const instrumentFetch = (ingestUrl: string, debug = false) => {
64
79
  } catch (err: any) {
65
80
  const duration = performance.now() - spanStartAbs;
66
81
  Context.addSpan({
82
+ spanId,
67
83
  name: `${method} ${hostname}`,
68
84
  type: 'http',
69
85
  startTime,
@@ -76,29 +92,40 @@ export const instrumentFetch = (ingestUrl: string, debug = false) => {
76
92
  };
77
93
  };
78
94
 
79
- // --- Standard HTTP/HTTPS Instrumentation ---
95
+ // --- HTTP/HTTPS INSTRUMENTATION ---
80
96
  export const instrumentHttp = (ingestUrl: string, debug = false) => {
81
97
  let ingestHost = '';
82
- try {
83
- ingestHost = new URL(ingestUrl).hostname;
84
- } catch (e) { }
98
+ try { ingestHost = new URL(ingestUrl).hostname; } catch (e) { }
85
99
 
86
100
  const requestWrapper = (original: Function) => {
87
101
  return function (this: any, ...args: any[]) {
88
102
  let options: any = {};
89
103
  let urlStr = '';
104
+ let optionsIndex = 0;
90
105
 
106
+ // Parsing Logic: http.request(url, options, cb) OR http.request(options, cb)
91
107
  if (typeof args[0] === 'string' || args[0] instanceof URL) {
92
108
  urlStr = args[0].toString();
93
- if (typeof args[1] === 'object' && args[1] !== null) options = args[1];
109
+ optionsIndex = 1;
94
110
  } else {
95
- options = args[0] || {};
111
+ optionsIndex = 0;
112
+ }
113
+
114
+ // Ensure options object exists at correct index
115
+ if (!args[optionsIndex] || typeof args[optionsIndex] !== 'object') {
116
+ args[optionsIndex] = {};
117
+ }
118
+ options = args[optionsIndex];
119
+
120
+ // Construct URL if missing
121
+ if (!urlStr) {
96
122
  const protocol = options.protocol || (options.port === 443 ? 'https:' : 'http:');
97
123
  const host = options.hostname || options.host || 'localhost';
98
124
  const path = options.path || '/';
99
125
  urlStr = `${protocol}//${host}${path}`;
100
126
  }
101
127
 
128
+ // Guard
102
129
  if (ingestHost && (urlStr.includes(ingestHost) || (options.hostname && options.hostname.includes(ingestHost)))) {
103
130
  return original.apply(this, args);
104
131
  }
@@ -109,25 +136,38 @@ export const instrumentHttp = (ingestUrl: string, debug = false) => {
109
136
  const method = (options.method || 'GET').toUpperCase();
110
137
  const startTime = performance.now() - trace.startTime;
111
138
  const spanStartAbs = performance.now();
139
+ const spanId = randomUUID();
140
+
112
141
  let hostname = 'unknown';
113
142
  try { hostname = new URL(urlStr).hostname; } catch (e) { hostname = options.hostname || 'unknown'; }
114
143
 
144
+ // Inject Headers (Mutate the options object reference directly)
145
+ if (!options.headers) options.headers = {};
146
+ options.headers['x-senzor-trace-id'] = trace.id;
147
+ options.headers['x-senzor-parent-span-id'] = spanId;
148
+
149
+ // Debug
150
+ if (debug) console.log(`[Senzor] Injecting headers to ${urlStr}`);
151
+
152
+ // Call Original
115
153
  const req = original.apply(this, args);
116
154
 
117
155
  const captureSpan = (res: any, error?: Error) => {
118
156
  const duration = performance.now() - spanStartAbs;
119
157
  Context.addSpan({
158
+ spanId,
120
159
  name: `${method} ${hostname}`,
121
160
  type: 'http',
122
161
  startTime,
123
162
  duration,
124
163
  status: error ? 500 : res?.statusCode || 0,
125
- meta: { url: urlStr, method, library: 'http', error: error ? error.message : undefined }
164
+ meta: { url: urlStr, method, library: 'http' }
126
165
  });
127
166
  };
128
167
 
129
168
  req.on('response', (res: any) => {
130
169
  res.once('end', () => captureSpan(res));
170
+ res.once('close', () => captureSpan(res));
131
171
  res.once('error', (err: Error) => captureSpan(res, err));
132
172
  });
133
173
 
@@ -8,6 +8,7 @@ export const expressMiddleware = () => {
8
8
  path: req.originalUrl || req.url,
9
9
  ip: req.ip || req.socket?.remoteAddress,
10
10
  userAgent: req.headers['user-agent'],
11
+ headers: req.headers
11
12
  }, () => {
12
13
 
13
14
  // Auto-detect status code on finish
@@ -2,29 +2,25 @@ import { client } from '../core/client';
2
2
  import { SenzorOptions } from '../core/types';
3
3
 
4
4
  export const senzorPlugin = (fastify: any, options: SenzorOptions, done: Function) => {
5
-
6
5
  if (options && options.apiKey) {
7
6
  client.init(options);
8
7
  }
9
8
 
10
- // 1. Start Trace
11
9
  fastify.addHook('onRequest', (request: any, reply: any, next: Function) => {
12
- // FIX: Wrap next in a closure to satisfy TS types
13
10
  client.startTrace({
14
11
  method: request.method,
15
12
  path: request.raw.url || request.url,
16
13
  ip: request.ip,
17
- userAgent: request.headers['user-agent']
14
+ userAgent: request.headers['user-agent'],
15
+ headers: request.headers // Pass headers
18
16
  }, () => next());
19
17
  });
20
18
 
21
- // 2. Capture Errors
22
19
  fastify.addHook('onError', (request: any, reply: any, error: any, next: Function) => {
23
20
  client.captureError(error);
24
21
  next();
25
22
  });
26
23
 
27
- // 3. End Trace
28
24
  fastify.addHook('onResponse', (request: any, reply: any, next: Function) => {
29
25
  const route = request.routeOptions?.url || request.routerPath || 'UNKNOWN';
30
26
  client.endTrace(reply.statusCode, { route });
@@ -13,6 +13,7 @@ export const wrapH3 = (handler: EventHandler) => {
13
13
  path: path,
14
14
  ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,
15
15
  userAgent: req.headers['user-agent'],
16
+ headers: req.headers // Pass headers
16
17
  }, async () => {
17
18
  try {
18
19
  const response = await handler(event);
@@ -23,9 +24,7 @@ export const wrapH3 = (handler: EventHandler) => {
23
24
  client.endTrace(status, { route: getRoute(event, path) });
24
25
  return response;
25
26
  } catch (err: any) {
26
- // AUTOMATIC ERROR CAPTURE
27
27
  client.captureError(err);
28
-
29
28
  const status = err.statusCode || err.status || 500;
30
29
  client.endTrace(status, { route: getRoute(event, path) });
31
30
  throw err;