@senzops/apm-node 1.2.4 → 1.2.5
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.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/register.js +1 -1
- package/dist/register.js.map +1 -1
- package/dist/register.mjs +1 -1
- package/dist/register.mjs.map +1 -1
- package/package.json +1 -1
- package/src/instrumentation/express.ts +53 -20
- package/src/middleware/express.ts +2 -2
- package/src/wrappers/fastify.ts +13 -13
- package/src/wrappers/h3.ts +41 -40
- package/src/wrappers/next.ts +70 -68
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Et=Object.create;var j=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var At=(e,t)=>{for(var r in t)j(e,r,{get:t[r],enumerable:!0})},Se=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Tt(t))!Ct.call(e,o)&&o!==r&&j(e,o,{get:()=>t[o],enumerable:!(n=xt(t,o))||n.enumerable});return e};var Z=(e,t,r)=>(r=e!=null?Et(zt(e)):{},Se(t||!e||!e.__esModule?j(r,"default",{value:e,enumerable:!0}):r,e)),It=e=>Se(j({},"__esModule",{value:!0}),e);var Lr={};At(Lr,{Senzor:()=>bt,default:()=>Fr});module.exports=It(Lr);var A="x-senzor-sdk-internal";var Q=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.taskQueue=[];this.taskErrorQueue=[];this.taskLogQueue=[];this.timer=null;this.isFlushing=!1;this.flushAgain=!1;this.droppedItems=0;let r=t.endpoint||"https://api.senzor.dev";this.apmEndpoint=r.includes("/api/ingest")?r:`${r}/api/ingest/apm`,this.taskEndpoint=r.includes("/api/ingest")?r.replace("/apm","/task"):`${r}/api/ingest/task`,typeof setInterval<"u"&&(this.timer=setInterval(()=>{this.flush()},t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()),this.installShutdownFlush()}addTrace(t){this.enqueue(this.traceQueue,t),this.checkFlush()}addTask(t){this.enqueue(this.taskQueue,t),this.checkFlush()}addError(t,r="apm"){this.enqueue(r==="task"?this.taskErrorQueue:this.apmErrorQueue,t),this.checkFlush()}addLog(t,r="apm"){this.enqueue(r==="task"?this.taskLogQueue:this.apmLogQueue,t),this.checkFlush()}enqueue(t,r){t.push(r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.shift(),this.droppedItems++}prependWithLimit(t,r){if(!r.length)return;t.unshift(...r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.pop(),this.droppedItems++}checkFlush(){let t=this.traceQueue.length+this.apmErrorQueue.length+this.apmLogQueue.length,r=this.taskQueue.length+this.taskErrorQueue.length+this.taskLogQueue.length;(t>=(this.config.batchSize||100)||r>=(this.config.batchSize||100))&&this.flush()}takeApmPayload(){let t={traces:this.traceQueue,errors:this.apmErrorQueue,logs:this.apmLogQueue};return this.traceQueue=[],this.apmErrorQueue=[],this.apmLogQueue=[],t}takeTaskPayload(){let t={runs:this.taskQueue,errors:this.taskErrorQueue,logs:this.taskLogQueue};return this.taskQueue=[],this.taskErrorQueue=[],this.taskLogQueue=[],t}restoreApmPayload(t){this.prependWithLimit(this.apmLogQueue,t.logs),this.prependWithLimit(this.apmErrorQueue,t.errors),this.prependWithLimit(this.traceQueue,t.traces)}restoreTaskPayload(t){this.prependWithLimit(this.taskLogQueue,t.logs),this.prependWithLimit(this.taskErrorQueue,t.errors),this.prependWithLimit(this.taskQueue,t.runs)}hasApmPayload(t){return t.traces.length>0||t.errors.length>0||t.logs.length>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),this.config.flushTimeoutMs??5e3);typeof o.unref=="function"&&o.unref();try{let s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[A]:"true"},body:JSON.stringify(r),keepalive:!0,signal:n.signal});if(!s.ok)throw new Error(`Senzor ingest failed with status ${s.status}`)}finally{clearTimeout(o)}}async flush(){if(this.isFlushing){this.flushAgain=!0;return}this.isFlushing=!0;try{do{this.flushAgain=!1;let t=this.takeApmPayload(),r=this.takeTaskPayload(),n=[];if(this.hasApmPayload(t)&&n.push(this.postJson(this.apmEndpoint,t).catch(a=>{throw this.restoreApmPayload(t),a})),this.hasTaskPayload(r)&&n.push(this.postJson(this.taskEndpoint,r).catch(a=>{throw this.restoreTaskPayload(r),a})),!n.length)continue;let s=(await Promise.allSettled(n)).filter(a=>a.status==="rejected");this.config.debug&&console.log(`[Senzor] Flushed: APM(${t.traces.length} traces, ${t.logs.length} logs), Task(${r.runs.length} runs, ${r.logs.length} logs), failures=${s.length}, dropped=${this.droppedItems}`)}while(this.flushAgain)}catch(t){this.config.debug&&console.error("[Senzor] Transport Flush Error:",t)}finally{this.isFlushing=!1}}installShutdownFlush(){let t=Symbol.for("senzor.transport.shutdownFlushInstalled"),r=process;if(r[t])return;Object.defineProperty(r,t,{value:!0,enumerable:!1});let n=()=>{this.flush()};process.once("beforeExit",n)}};var ke=require("async_hooks"),v=new ke.AsyncLocalStorage,k={run:(e,t)=>v.run(e,t),withActiveSpan:(e,t)=>{let r=v.getStore();return r?v.run({...r,activeSpanId:e,data:r.data,spans:r.spans},t):t()},current:()=>v.getStore(),addSpan:e=>{let t=v.getStore();t&&k.addSpanToTrace(t,e)},addSpanToTrace:(e,t)=>{if(e.state.ended)return;let r=e.maxSpans??500;if(e.spans.length>=r){e.state.droppedSpans=(e.state.droppedSpans??0)+1;return}e.spans.push(t)}};var ht=require("crypto");var oe=Z(require("http")),se=Z(require("https")),C=require("url");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],N=(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 Ot=64,ee=2048,Rt=4,Pt=20,_t=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Ft=e=>({maxAttributes:e?.maxAttributes??Ot,maxAttributeLength:e?.maxAttributeLength??ee}),O=(e,t=ee)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Lt=e=>_t.test(e),Mt=(e,t)=>{if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(typeof e=="string")return O(e,t)},Y=(e,t,r,n)=>{if(Lt(e))return"[REDACTED]";let o=Mt(t,r.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:O(t.name,r.maxAttributeLength),message:O(t.message,r.maxAttributeLength),stack:t.stack?O(t.stack,r.maxAttributeLength):void 0};if(n>=Rt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Pt).map(s=>Y(e,s,r,n+1));if(typeof t=="object"){let s={},a=0;for(let[i,p]of Object.entries(t)){if(a>=r.maxAttributes){s.__truncated=!0;break}s[i]=Y(i,p,r,n+1),a++}return s}return O(String(t),r.maxAttributeLength)},R=(e={},t)=>{let r=Ft(t),n={maxAttributes:r.maxAttributes,maxAttributeLength:r.maxAttributeLength},o={},s=0;for(let[a,i]of Object.entries(e)){if(s>=n.maxAttributes){o.__truncated=!0;break}o[a]=Y(a,i,n,0),s++}return o},we=(e,t)=>{if(!e||typeof e!="object")return{};let r={};if(typeof e.forEach=="function")e.forEach((n,o)=>{r[o.toLowerCase()]=n});else for(let[n,o]of Object.entries(e))r[n.toLowerCase()]=Array.isArray(o)?o.join(", "):o;return R(r,t)},P=(e,t)=>{if(typeof e!="string")return;let r=e.replace(/\s+/g," ").trim();if(!r)return;let n=r.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return O(t?.captureDbStatement===!1?n.split(" ").slice(0,6).join(" "):n,t?.maxAttributeLength??ee)},W=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase();var te=require("net"),$t=e=>e.startsWith("::ffff:")?e.slice(7):e,Ht=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let r=e.slice(0,t);return(0,te.isIP)(r)===4?r:e},vt=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},I=e=>{if(!e)return null;let t=e.trim();return t?(t=vt(t),t=Ht(t),t=$t(t),(0,te.isIP)(t)!==0?t:null):null},be=e=>!!(e==="127.0.0.1"||e.startsWith("10.")||e.startsWith("192.168.")||e.startsWith("169.254.")||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||e==="::1"||e==="::"||e.toLowerCase().startsWith("fe80:")||e.toLowerCase().startsWith("fc")||e.toLowerCase().startsWith("fd")),Nt=e=>{let t=e.split(",");for(let r of t){let n=r.match(/for=["[]?([^\]",;>\s]+)/i);if(n){let o=I(n[1]);if(o&&!be(o))return o}}return null},Ut=e=>{let t=e.split(",").map(r=>r.trim());for(let r of t){let n=I(r);if(n&&!be(n))return n}for(let r of t){let n=I(r);if(n)return n}return null},T=e=>{let t=e.headers;{let r=I(t["cf-connecting-ip"]);if(r)return r}{let r=I(t["true-client-ip"]);if(r)return r}{let r=I(t["x-real-ip"]);if(r)return r}{let r=t.forwarded;if(r){let n=Nt(r);if(n)return n}}{let r=t["x-forwarded-for"];if(r){let n=Ut(r);if(n)return n}}{let r=e.socket?.remoteAddress,n=I(r);if(n)return n}return null};var qt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Ee=e=>{if(!e)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let r=t.trim().toLowerCase().match(qt);if(!r)return null;let n=r[1],o=r[2],s=r[3];if(n==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:n,parentSpanId:o,sampled:a}},_=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`;var xe=Symbol.for("senzor.patch.keys"),Te=Symbol.for("senzor.patch.original"),g=(e,t,r,n)=>{if(!e)return!1;let o=e[t];if(typeof o!="function")return!1;let s=o[xe];if(s?.has(r))return!1;let a=o[Te]||o,i=n(o),p=new Set(s||[]);p.add(r);try{Object.defineProperty(i,xe,{value:p,enumerable:!1}),Object.defineProperty(i,Te,{value:a,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}};var re=require("crypto"),ne=()=>(0,re.randomUUID)().replace(/-/g,""),U=()=>(0,re.randomUUID)().replace(/-/g,"").slice(0,16);var b=(e,t,r={},n)=>{let o=k.current();if(!o)return null;let s=U(),a=o.activeSpanId,i=performance.now()-o.startTime,p=performance.now(),c=!1;return{spanId:s,parentSpanId:a,trace:o,end:(u,d={})=>{if(c)return;c=!0;let f=R({...r,...d,parentSpanId:a},n);k.addSpanToTrace(o,{spanId:s,parentSpanId:a,name:e,type:t,startTime:i,duration:performance.now()-p,status:u,meta:f})}}},E=(e,t)=>e?k.withActiveSpan(e.spanId,t):t();var Dt=e=>!!e?.debug,ze=e=>typeof e=="object"&&e!==null&&!(e instanceof C.URL)&&!(e instanceof Function)&&!Array.isArray(e),jt=(e,t)=>{if(e){if(typeof Headers<"u"&&e instanceof Headers)return e.get(t);if(Array.isArray(e))return e.find(([n])=>String(n).toLowerCase()===t.toLowerCase())?.[1];if(typeof e=="object"){let r=t.toLowerCase();for(let[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o}}},Ie=e=>String(jt(e,A)||"").toLowerCase()==="true",Oe=(e,t,r)=>{if(Ie(r))return!0;if(!e)return!1;try{let n=new C.URL(e),o=new C.URL(t);return n.hostname===o.hostname&&n.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},ae=e=>{if(!e)return{};if(typeof Headers<"u"&&e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?e.reduce((t,[r,n])=>(t[r]=n,t),{}):typeof e=="object"?{...e}:{}},F=(e,t,r)=>{let n=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[n||t]=r},Qt=(e,t)=>{let r=[...e],n=0,o={},s=null;if(typeof r[0]=="string"||r[0]instanceof C.URL){try{s=new C.URL(r[0].toString())}catch{s=null}ze(r[1])?(n=1,o={...r[1],headers:ae(r[1].headers)},r[1]=o):(n=1,o={headers:{}},r.splice(1,0,o))}else ze(r[0])?(n=0,o={...r[0],headers:ae(r[0].headers)},r[0]=o):(n=0,o={headers:{}},r[0]=o);o.headers||(o.headers={}),r[n]=o;let a=o.protocol||s?.protocol||(o.port===443?"https:":t),i=o.hostname||o.host||s?.hostname||"localhost",p=o.path||`${s?.pathname||"/"}${s?.search||""}`,c=s?s.toString():`${a}//${i}${p}`,u=String(o.method||"GET").toUpperCase();return{args:r,options:o,url:c,method:u,hostname:String(i).replace(/:\d+$/,""),path:p}},Wt=(e,t,r)=>{if(t?.statusCode===404)return"Not Found";try{return N(e,r)}catch{return x(r)}},Ce=(e,t,r,n)=>{g(e,"emit",`senzor.${t}.server`,o=>function(a,...i){if(a!=="request")return o.call(this,a,...i);let p=i[0],c=i[1];if(!p||!c||k.current()?.contextType==="apm")return o.call(this,a,...i);let u=p.originalUrl||p.url||"/",d=String(u).split("?")[0]||"/",f=p.headers||{};return Ie(f)?o.call(this,a,...i):r.startTrace({method:p.method||"GET",path:u,route:x(d),ip:T(p),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:p.httpVersion,headers:n?.captureHeaders?we(f,n):void 0}},()=>{let l=k.current(),m=!1,h=w=>{m||!l||(m=!0,setImmediate(()=>{l.state.ended||k.run(l,()=>{r.endTrace(c.statusCode||0,{route:Wt(p,c,d),statusMessage:c.statusMessage,meta:{...l.data.meta,endReason:w}})})}))};c.once("finish",()=>h("finish")),c.once("close",()=>h("close")),c.once("error",w=>{r.captureError(w,{instrumentation:`${t}.server`}),h("error")});try{return o.call(this,a,...i)}catch(w){throw r.captureError(w,{instrumentation:`${t}.server`}),h("error"),w}})})},Ae=(e,t,r,n)=>{let o=t==="https:"?"senzor.https":"senzor.http",s=a=>function(...p){let c=Qt(p,t);if(Oe(c.url,r,c.options.headers))return a.apply(this,p);let u=k.current();if(!u)return a.apply(this,p);let d=b(`${c.method} ${c.hostname}`,"http",{url:c.url,method:c.method,library:t==="https:"?"https":"http","http.request.method":c.method,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);d&&(F(c.options.headers,"traceparent",_(u.id,d.spanId)),F(c.options.headers,"x-senzor-trace-id",u.id),F(c.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=a.apply(this,c.args);if(!d||!l||typeof l.once!="function")return l;let m=!1,h=(w,D={})=>{m||(m=!0,d.end(w,D))};return l.once("response",w=>{let D=w?.statusCode||0,ye=()=>h(D,{"http.response.status_code":D});w.once("end",ye),w.once("close",ye),w.once("error",ge=>h(500,{error:ge.message,"error.type":ge.name}))}),l.once("timeout",()=>h(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",w=>h(500,{error:w.message,"error.type":w.name})),l};return Dt(n)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),E(d,f)};g(e,"request",`${o}.request`,s),g(e,"get",`${o}.get`,s)},Re=(e,t)=>{globalThis.fetch&&g(globalThis,"fetch","senzor.fetch",r=>async function(o,s){let a=typeof o=="string"?o:o instanceof C.URL?o.toString():o?.url||"",i=s?.headers||o?.headers;if(Oe(a,e,i))return r.call(this,o,s);let p=k.current();if(!p)return r.call(this,o,s);let c="unknown",u="/";try{let h=new C.URL(a);c=h.hostname,u=`${h.pathname}${h.search}`}catch{}let d=String(s?.method||o?.method||"GET").toUpperCase(),f=b(`${d} ${c}`,"http",{url:a,method:d,library:"fetch","http.request.method":d,"url.full":a,"url.path":u,"server.address":c},t);if(!f)return r.call(this,o,s);let l={...s||{}},m=typeof Headers<"u"?new Headers(i||void 0):ae(i);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",_(p.id,f.spanId)),m.set("x-senzor-trace-id",p.id),m.set("x-senzor-parent-span-id",f.spanId)):(F(m,"traceparent",_(p.id,f.spanId)),F(m,"x-senzor-trace-id",p.id),F(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,E(f,async()=>{try{let h=await r.call(this,o,l);return f.end(h.status,{"http.response.status_code":h.status}),h}catch(h){throw f.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}})})},Pe=(e,t,r)=>{Ce(oe.default.Server?.prototype,"http",e,r),Ce(se.default.Server?.prototype,"https",e,r),Ae(oe.default,"http:",t,r),Ae(se.default,"https:",t,r)};var q=Z(require("module")),_e=Symbol.for("senzor.require.patched"),K=Symbol.for("senzor.require.hooks"),G=q.default.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/");function Kt(){let e=q.default;return e[K]||Object.defineProperty(e,K,{value:new Map,enumerable:!1}),e[K]}function Gt(e,t){let r=q.default[K];if(!r)return t;let n=r.get(e);if(!n?.length)return t;let o=t;for(let s of n)try{let a=s(o);a!==void 0&&(o=a)}catch(a){console.error(`[Senzor] instrumentation failed for ${e}`,a)}return o}function Bt(){let e=q.default;if(e[_e])return;let t=e._load;e._load=function(n,o,s){let a=t.apply(this,arguments);return Gt(n,a)},Object.defineProperty(e,_e,{value:!0,enumerable:!1})}function Vt(e,t){try{let r=G.resolve(e),n=G.cache?.[r];if(n?.exports){let o=t(n.exports);o!==void 0&&(n.exports=o)}}catch{}}function Jt(e,t){try{let r=G(e);r&&t(r)}catch{}}function Xt(e,t){let r=0,n=5,o=setInterval(()=>{r++;try{let s=G(e);s&&(t(s),clearInterval(o))}catch{}r>=n&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var S=(e,t)=>{let r=Kt();r.has(e)||r.set(e,[]),r.get(e).push(t),Bt(),Vt(e,t),Jt(e,t),Xt(e,t)};var Zt=new Set([void 0,null,"route","router"]),Yt=(e,t)=>!(t?.frameworkSpans===!1||e==="middleware"&&t?.captureMiddlewareSpans===!1||e==="router"&&t?.captureRouterSpans===!1||e==="lifecycle_hook"&&t?.captureLifecycleHookSpans===!1||t?.ignoreFrameworkSpanTypes?.includes(e)),L=(e,t=0)=>{let r=e.response;return r?.statusCode||r?.status||r?.raw?.statusCode||r?.status_code||t},er=e=>!!(e&&typeof e.then=="function"),tr=(e,t)=>e.parentSpanId?k.withActiveSpan(e.parentSpanId,t):t(),rr=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}},z=(e,t,r,n,o,s={})=>{if(!Yt(n.type,o)||!k.current())return e.apply(t,r);let a=b(n.name,"function",{framework:n.framework,"senzor.framework":n.framework,"senzor.framework.type":n.type,"http.route":n.route,route:n.route,method:n.method,layerPath:n.layerPath,handlerName:n.handlerName,...n.attributes},o);if(!a)return e.apply(t,r);let i=!1,p=[],c=(f=L(n),l={})=>{if(!i){i=!0;for(let m of p)try{m()}catch{}a.end(f,l)}},u=n.response;if(s.responseEndsSpan!==!1&&u?.once){let f=()=>c(L(n),{completion:"response.finish"}),l=()=>c(L(n),{completion:"response.close"});u.once("finish",f),u.once("close",l),p.push(()=>{try{u.removeListener?.("finish",f)}catch{}try{u.removeListener?.("close",l)}catch{}})}let d=s.callbackIndex??r.findIndex(f=>typeof f=="function");if(s.callbackCompletesSpan!==!1&&d>=0&&typeof r[d]=="function"){let f=r[d];r[d]=function(...m){let h=m[0],w=!Zt.has(h);return c(w?500:L(n),{completion:"callback",error:w?String(h?.message||h):void 0,"error.type":w?h?.name||typeof h:void 0}),tr(a,()=>f.apply(this,m))}}return E(a,()=>{try{let f=e.apply(t,r);return er(f)?f.then(l=>(c(L(n),{completion:"promise.resolve"}),l),l=>{throw c(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&s.responseEndsSpan===!1&&c(L(n),{completion:"sync.return"}),f)}catch(f){throw c(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})};var M=(e,t,r,n={})=>{if(typeof e!="function")return e;let o=(a,i)=>z(e,a,i,t(a,i),r,n),s;switch(e.length){case 4:s=function(i,p,c,u){return o(this,[i,p,c,u])};break;case 3:s=function(i,p,c){return o(this,[i,p,c])};break;case 2:s=function(i,p){return o(this,[i,p])};break;case 1:s=function(i){return o(this,[i])};break;default:s=function(){return o(this,Array.from(arguments))};break}return rr(e,s),s};var Fe=Symbol.for("senzor.express.layer.patched"),nr=new Set(["checkout","copy","delete","get","head","lock","merge","mkactivity","mkcol","move","m-search","notify","options","patch","post","purge","put","report","search","subscribe","trace","unlock","unsubscribe"]),ce=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ce).filter(Boolean).join(",");if(typeof e=="number")return String(e)},ie=e=>{for(let t of e){if(typeof t=="function")return;let r=ce(t);if(r)return r}},Le=(e,t,r)=>{let n=ce(t?.route?.path);if(n)return`${e?.baseUrl||""}${n}`||n;if(e?.route?.path)return`${e.baseUrl||""}${e.route.path}`;if(r)return`${e?.baseUrl||""}${r}`||r;let o=e?.originalUrl||e?.url||e?.path;return o?x(String(o).split("?")[0]):void 0},or=(e,t,r)=>r||(t.length===4?"error_handler":e?.route?"request_handler":e?.name==="router"||e?.handle?.stack||e?.handle?.name==="router"?"router":"middleware"),Me=(e,t)=>{if(e?.route?.methods){let r=Object.keys(e.route.methods).find(n=>e.route.methods[n]);if(r)return r.toUpperCase()}return t?.method},$e=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}},B=(e,t,r,n)=>{!e||e[Fe]||typeof e.handle!="function"||(Object.defineProperty(e,Fe,{value:!0,enumerable:!1}),g(e,"handle","senzor.express.layer.handle",o=>{let s=or(e,o,n),a=o.name||e.name||s;if(o.length===4){let p=function(u,d,f,l){let m=Le(d,e,t);return z(o,this,[u,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||a}`,route:m,method:Me(e,d),layerPath:t,handlerName:a,request:d,response:f,attributes:{"express.type":"error_handler","express.layer.name":e.name,error:u?.message,"error.type":u?.name||typeof u}},r,{callbackIndex:3,callbackCompletesSpan:!0,responseEndsSpan:!0})};return $e(o,p),p}let i=function(c,u,d){let f=Le(c,e,t),l=Me(e,c),m=f||t||a,h=s==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${s} ${m}`;return z(o,this,[c,u,d],{framework:"express",type:s,name:h,route:f,method:l,layerPath:t,handlerName:a,request:c,response:u,attributes:{"express.type":s,"express.layer.name":e.name,"http.route":f}},r,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return $e(o,i),i}))},sr=(e,t,r)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let n of nr)typeof e[n]=="function"&&g(e,n,`senzor.express.route.${n}`,o=>function(...a){let i=o.apply(this,a),p=this?.stack||[];for(let c of p)B(c,t,r,"request_handler");return i})}},He=e=>{if(e){if(e._router)return e._router;try{return e.router}catch{return}}},ve=(e,t)=>{if(!e)return;let r=typeof e?.Router?.prototype?.route=="function"?e.Router.prototype:e.Router;g(r,"route","senzor.express.router.route",n=>function(...s){let a=n.apply(this,s),i=ie(s),p=this?.stack?.[this.stack.length-1];return B(p,i,t,"router"),sr(a,i,t),a}),g(r,"use","senzor.express.router.use",n=>function(...s){let a=n.apply(this,s),i=this?.stack?.[this.stack.length-1];return B(i,ie(s),t),a}),g(e.application,"use","senzor.express.application.use",n=>function(...s){let a=He(this),i=n.apply(this,s),p=He(this)||a,c=p?.stack?.[p.stack.length-1];return B(c,ie(s),t),i})},Ne=e=>{S("express",t=>{ve(t,e),t?.default&&ve(t.default,e)})};var Ue=Symbol.for("senzor.fastify.factory.patched"),qe=Symbol.for("senzor.fastify.instance.patched"),ar=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),ir=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],ue=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,De=(e,t,r,n)=>typeof t!="function"?t:M(t,(o,s)=>{let a=s[0],i=s[1],p=ue(a,n);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${p||a?.url||""}`.trim(),route:p,method:a?.method,handlerName:t.name||e,request:a,response:i?.raw||i,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":p,url:a?.url}}},r,{callbackCompletesSpan:!0,responseEndsSpan:!1}),cr=(e,t,r)=>typeof e!="function"?e:M(e,(n,o)=>{let s=o[0],a=o[1],i=ue(s,r);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${s?.method||""} ${i||s?.url||""}`.trim(),route:i,method:s?.method,handlerName:e.name||"handler",request:s,response:a?.raw||a,attributes:{"fastify.type":"route_handler","http.route":i,url:s?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),pr=(e,t)=>Array.isArray(e)?e.map(t):t(e),je=(e,t)=>(!e||e[qe]||(Object.defineProperty(e,qe,{value:!0,enumerable:!1}),g(e,"addHook","senzor.fastify.addHook",r=>function(o,s){return ar.has(o)?r.call(this,o,De(o,s,t)):r.apply(this,arguments)}),g(e,"route","senzor.fastify.route",r=>function(o){if(!o||typeof o!="object")return r.apply(this,arguments);let s={...o},a=s.url||s.path||s.routePath;s.handler&&(s.handler=cr(s.handler,t,a));for(let i of ir)s[i]&&(s[i]=pr(s[i],p=>De(i,p,t,a)));return r.call(this,s)}),g(e,"setErrorHandler","senzor.fastify.setErrorHandler",r=>function(o){return r.call(this,M(o,(s,a)=>{let i=a[1],p=a[2],c=ue(i);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${c||i?.url||""}`.trim(),route:c,method:i?.method,handlerName:o?.name||"errorHandler",request:i,response:p?.raw||p,attributes:{"fastify.type":"error_handler",error:a[0]?.message,"error.type":a[0]?.name||typeof a[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),ur=(e,t)=>{for(let r of Reflect.ownKeys(e))if(!["length","name","prototype"].includes(String(r)))try{Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}catch{}},pe=(e,t)=>{if(typeof e!="function"||e[Ue])return e;let r=function(...s){let a=e.apply(this,s);return je(a,t)};ur(e,r),Object.defineProperty(r,Ue,{value:!0,enumerable:!1});let n=r;return n.fastify===e&&(n.fastify=n),n.default===e&&(n.default=n),n},Qe=e=>{S("fastify",t=>typeof t=="function"?pe(t,e):(t?.fastify&&(t.fastify=pe(t.fastify,e)),t?.default&&(t.default=pe(t.default,e)),t))},We=(e,t)=>je(e,t);var dr=["all","del","delete","get","head","options","patch","post","put"],Be=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(Be).filter(Boolean).join(",")},Ke=e=>{for(let t of e){if(typeof t=="function")return;let r=Be(t);if(r)return r}},de=(e,t,r,n="middleware",o)=>typeof e!="function"?e:M(e,(s,a)=>{let i=a[0],p=i?._matchedRoute||i?.matched?.[0]?.path||r||x(i?.path||i?.request?.path||"/"),c=o||i?.method||i?.request?.method,u=e.name||n;return{framework:"koa",type:n,name:n==="route_handler"?`koa.request_handler ${c||""} ${p}`.trim():`koa.${n} ${p||u}`,route:p,method:c,layerPath:r,handlerName:u,request:i?.req||i?.request,response:i?.res||i?.response,attributes:{"koa.type":n,"http.route":p,path:i?.path||i?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),fr=(e,t)=>{let r=e?.prototype||e?.default?.prototype;r&&g(r,"use","senzor.koa.application.use",n=>function(s){return n.call(this,de(s,t,void 0,"middleware"))})},Ge=(e,t)=>{let n=(e?.Router||e?.default||e)?.prototype;if(n){g(n,"use","senzor.koa.router.use",o=>function(...a){let i=Ke(a),p=a.map(c=>typeof c=="function"?de(c,t,i,"router"):c);return o.apply(this,p)});for(let o of dr)g(n,o,`senzor.koa.router.${o}`,s=>function(...i){let p=Ke(i),c=i.map(u=>typeof u=="function"?de(u,t,p,"route_handler",o.toUpperCase()):u);return s.apply(this,c)})}},Ve=e=>{S("koa",t=>{fr(t,e)}),S("@koa/router",t=>{Ge(t,e)}),S("koa-router",t=>{Ge(t,e)})};var lr=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",Je=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,hr=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",mr=(e,t,r)=>{g(e,t,`senzor.mongodb.collection.${t}`,n=>function(...s){let a=lr(this),i=b(`MongoDB ${t}`,"db",{collection:a,operation:t,"db.system.name":"mongodb","db.collection.name":a,"db.namespace":Je(this)?`${Je(this)}.${a}`:a,"db.operation.name":t,library:"mongodb"},r);return i?E(i,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(c=>(i.end(0,{matchedCount:c?.matchedCount,modifiedCount:c?.modifiedCount,deletedCount:c?.deletedCount,insertedCount:c?.insertedCount}),c),c=>{throw i.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(i.end(0),p)}catch(p){throw i.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}}):n.apply(this,s)})},Xe=(e,t,r,n)=>{g(e,t,`senzor.mongodb.cursor.${r}.${t}`,o=>function(...a){let i=hr(this),p=b(`MongoDB ${r}`,"db",{collection:i,operation:r,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":r,library:"mongodb"},n);return p?E(p,()=>{try{let c=o.apply(this,a);return c&&typeof c.then=="function"?c.then(u=>(p.end(0,{resultCount:Array.isArray(u)?u.length:void 0}),u),u=>{throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(p.end(0),c)}catch(c){throw p.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):o.apply(this,a)})},yr=(e,t)=>{let n=(e?.Collection||e?.default?.Collection)?.prototype;["insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOne","findOneAndUpdate","findOneAndDelete","findOneAndReplace","countDocuments","estimatedDocumentCount","distinct","bulkWrite","createIndex","dropIndex"].forEach(a=>mr(n,a,t));let o=e?.FindCursor||e?.default?.FindCursor,s=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(a=>Xe(o?.prototype,a,"find",t)),["toArray","next","forEach"].forEach(a=>Xe(s?.prototype,a,"aggregate",t))},Ze=e=>{S("mongodb",t=>yr(t,e))};var gr=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},V=(e,t,r)=>{g(e,"query",`senzor.pg.${t}.query`,n=>function(...s){let a=gr(s),i=W(a)||"QUERY",p=b(`Postgres ${i}`,"db",{query:P(a,r),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":P(a,r),library:"pg"},r);if(!p)return n.apply(this,s);let c=s.findIndex(u=>typeof u=="function");if(c>=0){let u=s[c];s[c]=function(f,l){return p.end(f?500:0,{error:f?.message,"error.type":f?.name,rowCount:l?.rowCount,"db.response.row_count":l?.rowCount}),u.apply(this,arguments)}}return E(p,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(d=>(p.end(0,{rowCount:d?.rowCount,"db.response.row_count":d?.rowCount}),d),d=>{throw p.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(c<0&&u&&typeof u.once=="function"?(u.once("end",()=>p.end(0)),u.once("error",d=>p.end(500,{error:d.message,"error.type":d.name}))):c<0&&p.end(0),u)}catch(u){throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}})})},Sr=(e,t)=>{e&&(V(e.Client?.prototype,"client",t),V(e.Pool?.prototype,"pool",t),e.default&&(V(e.default.Client?.prototype,"default.client",t),V(e.default.Pool?.prototype,"default.pool",t)))},Ye=e=>{S("pg",t=>Sr(t,e))};var kr=e=>e?Array.isArray(e)?e.some(([t,r])=>String(t).toLowerCase()===A&&String(r).toLowerCase()==="true"):Object.entries(e).some(([t,r])=>t.toLowerCase()===A&&String(r).toLowerCase()==="true"):!1,fe=(e,t,r)=>{if(Array.isArray(e))return e.push([t,r]),e;let n={...e||{}},o=Object.keys(n).find(s=>s.toLowerCase()===t.toLowerCase());return n[o||t]=r,n},wr=e=>{try{let t=new URL(String(e));return{url:t.toString(),hostname:t.hostname,path:`${t.pathname}${t.search}`}}catch{return{url:String(e||""),hostname:"unknown",path:"/"}}},J=(e,t,r,n)=>{g(e,t,r,o=>function(a,i,p){if(kr(i?.headers))return o.apply(this,arguments);let c=wr(a?.origin?a.origin:a),u=String(i?.method||"GET").toUpperCase(),d=b(`${u} ${c.hostname}`,"http",{url:c.url,method:u,route:x(c.path),library:"undici","http.request.method":u,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);if(!d)return o.apply(this,arguments);let f={...i||{}};f.headers=fe(f.headers,"traceparent",_(d.trace.id,d.spanId)),f.headers=fe(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=fe(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof p=="function"?function(h,w){return d.end(h?500:w?.statusCode||0,{error:h?.message,"error.type":h?.name,"http.response.status_code":w?.statusCode}),p.apply(this,arguments)}:p;return E(d,()=>{try{let m=o.call(this,a,f,l);return m&&typeof m.then=="function"?m.then(h=>(d.end(h?.statusCode||h?.status||0,{"http.response.status_code":h?.statusCode||h?.status}),h),h=>{throw d.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}):(typeof l!="function"&&d.end(0),m)}catch(m){throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},br=(e,t)=>{J(e,"request","senzor.undici.request",t),J(e,"stream","senzor.undici.stream",t),J(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((r,n)=>{J(r,"request",`senzor.undici.dispatcher.${n}.request`,t)})},et=e=>{S("undici",t=>br(t,e))};var Er=e=>typeof e=="string"?e.toUpperCase():Array.isArray(e)?String(e[0]||"COMMAND").toUpperCase():e?.name?String(e.name).toUpperCase():Array.isArray(e?.args)?String(e.args[0]||"COMMAND").toUpperCase():"COMMAND",$=(e,t,r)=>{g(e,"sendCommand",`senzor.redis.${t}.sendCommand`,n=>function(s,...a){let i=Er(s),p=b(`Redis ${i}`,"db",{command:i,operation:i,"db.system.name":"redis","db.operation.name":i,library:t},r);return p?E(p,()=>{try{let c=n.call(this,s,...a);return c&&typeof c.then=="function"?c.then(u=>(p.end(0),u),u=>{throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(p.end(0),c)}catch(c){throw p.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,arguments)})},xr=(e,t,r)=>($(e,t,r),$(Object.getPrototypeOf(e),t,r),e),Tr=(e,t)=>{["createClient","createCluster"].forEach(r=>{g(e,r,`senzor.redis.${r}`,n=>function(...s){let a=n.apply(this,s);return xr(a,"redis",t)})})},zr=(e,t)=>{$(e?.prototype,"ioredis",t),$(e?.Redis?.prototype,"ioredis",t),$(e?.Cluster?.prototype,"ioredis-cluster",t),$(e?.default?.prototype,"ioredis",t)},tt=e=>{S("redis",t=>Tr(t,e)),S("ioredis",t=>zr(t,e))};var Cr=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},H=(e,t,r,n)=>{g(e,t,`senzor.${r}.${t}`,o=>function(...a){let i=Cr(a),p=W(i)||t.toUpperCase(),c=b(`MySQL ${p}`,"db",{query:P(i,n),operation:p,"db.system.name":"mysql","db.operation.name":p,"db.query.text":P(i,n),library:r},n);if(!c)return o.apply(this,a);let u=a.findIndex(d=>typeof d=="function");if(u>=0){let d=a[u];a[u]=function(l,m){return c.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(m)?m.length:void 0}),d.apply(this,arguments)}}return E(c,()=>{try{let d=o.apply(this,a);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return c.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw c.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(u<0&&d&&typeof d.once=="function"?(d.once("end",()=>c.end(0)),d.once("error",f=>c.end(500,{error:f.message,"error.type":f.name}))):u<0&&c.end(0),d)}catch(d){throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},Ar=(e,t,r)=>{[e?.Connection?.prototype,e?.Pool?.prototype,e?.PoolConnection?.prototype,e?.PromiseConnection?.prototype,e?.PromisePool?.prototype,e?.default?.Connection?.prototype,e?.default?.Pool?.prototype].forEach(n=>{H(n,"query",t,r),H(n,"execute",t,r)})},Ir=(e,t,r)=>{["createConnection","createPool"].forEach(n=>{g(e,n,`senzor.${t}.${n}`,o=>function(...a){let i=o.apply(this,a);return H(i,"query",t,r),H(i,"execute",t,r),H(Object.getPrototypeOf(i),"query",t,r),H(Object.getPrototypeOf(i),"execute",t,r),i})})},rt=(e,t,r)=>{Ar(e,t,r),Ir(e,t,r)},nt=e=>{S("mysql",t=>rt(t,"mysql",e)),S("mysql2",t=>rt(t,"mysql2",e))};var st=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",at=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",X=(e,t,r)=>{g(e,"exec",`senzor.mongoose.${t}.exec`,n=>function(...s){let a=String(this?.op||this?._op||t).toUpperCase(),i=at(this),p=b(`Mongoose ${a}`,"db",{collection:i,model:st(this),operation:a,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":a,library:"mongoose"},r);return p?E(p,()=>{try{let c=n.apply(this,s);return c&&typeof c.then=="function"?c.then(u=>(p.end(0,{resultCount:Array.isArray(u)?u.length:void 0}),u),u=>{throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(p.end(0),c)}catch(c){throw p.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,s)})},ot=(e,t)=>{g(e,"save","senzor.mongoose.model.save",r=>function(...o){let s=at(this),a=b("Mongoose SAVE","db",{collection:s,model:st(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":s,"db.operation.name":"SAVE",library:"mongoose"},t);return a?E(a,()=>{try{let i=r.apply(this,o);return i&&typeof i.then=="function"?i.then(p=>(a.end(0),p),p=>{throw a.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(a.end(0),i)}catch(i){throw a.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):r.apply(this,o)})},Or=(e,t)=>{X(e?.Query?.prototype,"query",t),X(e?.Aggregate?.prototype,"aggregate",t),ot(e?.Model?.prototype,t),e?.default&&(X(e.default?.Query?.prototype,"query",t),X(e.default?.Aggregate?.prototype,"aggregate",t),ot(e.default?.Model?.prototype,t))},it=e=>{S("mongoose",t=>Or(t,e))};var ct=Symbol.for("senzor.bullmq.patched");function pt(e,t,r){if(!e?.Worker?.prototype)return;let n=e.Worker.prototype,o=n.processJob;typeof o!="function"||o[ct]||(n.processJob=async function(s){let a=s.timestamp?Date.now()-s.timestamp:0,i=(s.attemptsMade||0)+1,p=s.opts?.attempts??1,c=i>=p,u=s.name==="__default__"?s.queueName:`${s.queueName}:${s.name}`;return t.startTask(u,"queue",{queueDelay:a,attempts:i,isDeadLetter:!1,metadata:{jobId:s.id,queueName:s.queueName,maxAttempts:p}},async()=>{try{let d=await o.call(this,s);return t.endTask("success"),d}catch(d){try{let f=k.current();f&&f.contextType==="task"&&c&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:s.queueName,jobId:s.id,isDeadLetter:c}),t.endTask("failed"),d}})},Object.defineProperty(n.processJob,ct,{value:!0}),r&&console.log("[Senzor] BullMQ instrumented"))}var ut=(e,t)=>{S("bullmq",r=>{pt(r,e,t),r?.default&&pt(r.default,e,t)})};var dt=Symbol.for("senzor.cron.patched");function Rr(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function ft(e,t,r){let n=e.schedule;if(typeof n!="function"||n[dt])return;let o=n,s=function(a,i,p){if(typeof i!="function")return o.call(this,a,i,p);try{let c=Rr(p),u=c?.name??`cron: ${a}`,d=t.wrapTask(u,"cron",{expression:a,metadata:c},i);return o.call(this,a,d,p)}catch(c){return r&&console.error("[Senzor] cron wrap failed",c),o.call(this,a,i,p)}};Object.defineProperty(s,dt,{value:!0,enumerable:!1});try{e.schedule=s}catch{r&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}r&&console.log("[Senzor] node-cron instrumented")}var lt=(e,t)=>{S("node-cron",r=>{r&&(ft(r,e,t),r.default&&ft(r.default,e,t))})};var le={name:"@senzops/apm-node",version:"1.2.4",description:"Universal APM SDK for Senzor",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",require:"./dist/index.js",import:"./dist/index.mjs"},"./register":{types:"./dist/register.d.ts",require:"./dist/register.js",import:"./dist/register.mjs"}},scripts:{build:"tsup",prepublishOnly:"npm run build"},devDependencies:{"@types/node":"^20.19.41",tsup:"^8.0.0",typescript:"^5.0.0"},engines:{node:">=18.0.0"},keywords:["apm","monitoring","senzor","node","javascript","api","observability"],author:"Senzops",license:"MIT"};var he={name:le.name,version:le.version};var _r=e=>{let t=new Set;return JSON.stringify(e,(r,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return"[Circular]";t.add(n)}return n})},me=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}preload(t={}){let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.options={apiKey:"",...this.options,...t},this.installNativeInstrumentations(r,n)}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.transport=new Q({...t,endpoint:r}),this.installNativeInstrumentations(r,n)}isInstrumentationEnabled(t){let r=this.options?.instrumentations;return r===!1?!1:Array.isArray(r)?r.includes(t):!0}installNativeInstrumentations(t,r){if(!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{this.isInstrumentationEnabled("http")&&Pe(this,t,this.options||void 0)}catch{}try{this.isInstrumentationEnabled("express")&&Ne(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("fastify")&&Qe(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("koa")&&Ve(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("fetch")&&Re(t,this.options||void 0)}catch{}try{this.isInstrumentationEnabled("undici")&&et(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mongo")&&Ze(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mongoose")&&it(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("pg")&&Ye(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mysql")&&nt(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("redis")&&tt(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("bullmq")&&ut(this,r)}catch{}try{this.isInstrumentationEnabled("cron")&<(this,r)}catch{}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}setupLogInterception(){if(this.options?.autoLogs===!1)return;let t=["log","info","warn","error","debug"],r={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},n=!1;t.forEach(o=>{console[o]=(...s)=>{if(r[o].apply(console,s),!(n||!this.transport)){n=!0;try{let a="",i={};s.forEach(d=>{if(typeof d=="string")a+=(a?" ":"")+d;else if(d instanceof Error)a+=(a?" ":"")+d.message,i.errorStack=d.stack,i.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(_r(d));i={...i,...R(f,this.options||void 0)}}catch{i.unparseableObject=!0}else a+=(a?" ":"")+String(d)}),!a&&Object.keys(i).length>0&&(a="Object Log");let p=k.current(),c=p?.contextType==="task"?"task":"apm",u={message:a||"Empty log",level:o==="log"?"info":o,attributes:i,timestamp:new Date().toISOString()};p&&(c==="task"?u.runId=p.id:u.traceId=p.id),this.transport.addLog(u,c)}catch{}finally{n=!1}}}})}setupGlobalErrorHandlers(){if(process.__senzorGlobalHandlersInstalled)return;process.__senzorGlobalHandlersInstalled=!0;let t=()=>{try{return{pid:process.pid,ppid:process.ppid,platform:process.platform,uptimeSec:Math.floor(process.uptime()),env:process.env.NODE_ENV||"unknown"}}catch{return{}}},r=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},n=(o,s={})=>{try{let a;if(o instanceof Error)a=o;else if(typeof o=="string")a=new Error(o);else try{a=new Error(JSON.stringify(o))}catch{a=new Error("Non-serializable rejection reason")}let i={...s,runtime:{name:"node",version:process.version},process:t(),memory:r(),sdk:{name:he.name,version:he.version}};this.captureError(a,i)}catch(a){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",a)}catch{}}};process.on("uncaughtExceptionMonitor",o=>n(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>n(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>n(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>n(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,s,a)=>n(a||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:o,severity:"warning"})),process.on("rejectionHandled",o=>{if(this.options?.debug)try{console.warn("[Senzor] rejectionHandled event detected")}catch{}}),process.on("SIGTERM",()=>n(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>n(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,r){if(!this.transport)return r();let n=k.current();if(n?.contextType==="apm")return Object.assign(n.data,t),r();let o,s;if(t.headers){let c=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},u=c("traceparent"),d=Ee(u);if(d)o=d.traceId,s=d.parentSpanId;else{let f=c("x-senzor-trace-id"),l=c("x-senzor-parent-span-id");o=Array.isArray(f)?f[0]:f,s=Array.isArray(l)?l[0]:l}}let a=o||ne(),i=U(),p={id:a,contextType:"apm",startTime:performance.now(),rootSpanId:i,activeSpanId:i,data:{...t,parentTraceId:o,parentSpanId:s,rootSpanId:i},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return k.run(p,r)}endTrace(t,r={}){let n=k.current();if(!n||n.contextType!=="apm"||!this.transport||n.state.ended)return;n.state.ended=!0;let o=performance.now()-n.startTime,s={traceId:n.id,parentTraceId:n.data.parentTraceId,parentSpanId:n.data.parentSpanId,rootSpanId:n.rootSpanId,...n.data,...r,status:t,duration:o,spans:n.spans,droppedSpans:n.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(s)}startTask(t,r,n,o){if(!this.transport)return o();let s=k.current(),a=s?.contextType==="apm"?s.id:void 0,i=process.memoryUsage?process.memoryUsage().heapUsed:0,p=process.cpuUsage?process.cpuUsage():void 0,c={id:(0,ht.randomUUID)(),contextType:"task",startTime:performance.now(),rootSpanId:U(),startMemory:i,startCpu:p,data:{taskName:t,taskType:r,triggerTraceId:a,...n},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return c.activeSpanId=c.rootSpanId,k.run(c,o)}endTask(t,r={}){let n=k.current();if(!n||n.contextType!=="task"||!this.transport||n.state.ended)return;n.state.ended=!0;let o;if(process.memoryUsage&&n.startMemory!==void 0&&process.cpuUsage&&n.startCpu){let a=process.memoryUsage().heapUsed,i=process.cpuUsage(n.startCpu);o={memoryDeltaBytes:a-n.startMemory,cpuUserUs:i.user,cpuSystemUs:i.system}}let s={runId:n.id,taskName:n.data.taskName,taskType:n.data.taskType,triggerTraceId:n.data.triggerTraceId,queueDelay:n.data.queueDelay,attempts:n.data.attempts,isDeadLetter:n.data.isDeadLetter,metadata:{...n.data.metadata,...r,droppedSpans:n.state.droppedSpans},resourceMetrics:o,status:t,duration:performance.now()-n.startTime,spans:n.spans,timestamp:new Date().toISOString()};this.transport.addTask(s)}wrapTask(t,r,n={},o){return(async(...s)=>this.startTask(t,r,n,async()=>{try{let a=await o(...s);return this.endTask("success"),a}catch(a){throw this.captureError(a,{taskName:t}),this.endTask("failed"),a}}))}captureError(t,r={}){if(!this.transport)return;let n;t instanceof Error?n=t:n=new Error(String(t));let o=k.current(),s={errorClass:n.name||"Error",message:n.message,stackTrace:n.stack,context:R(r,this.options||void 0),timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...s,runId:o.id},"task"):this.transport.addError({...s,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:ne(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,r="custom"){let n=b(t,r,{},this.options||void 0);return n?{end:(o,s)=>n.end(s,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},y=new me;var mt=()=>(e,t,r)=>{y.startTrace({method:e.method,path:e.originalUrl||e.url,ip:T(e),userAgent:e.headers["user-agent"],headers:e.headers},()=>{t.once("finish",()=>{try{let n="UNKNOWN";e.route&&e.route.path?n=(e.baseUrl||"")+e.route.path:t.statusCode===404?n="Not Found":n=e.path||"Wildcard",y.endTrace(t.statusCode,{route:n})}catch{}}),r()})},yt=()=>(e,t,r,n)=>{y.captureError(e),n(e)};var gt=e=>t=>{let r=t.node.req,n=r.originalUrl||r.url||"/";return y.startTrace({method:r.method||"GET",path:n,ip:T(r),userAgent:r.headers["user-agent"],headers:r.headers},async()=>{try{let o=N(t,n),s=await z(e,void 0,[t],{framework:"h3",type:"event_handler",name:`h3.event_handler ${r.method||"GET"} ${o}`,route:o,method:r.method||"GET",request:r,response:t.node.res,attributes:{"h3.type":"event_handler","http.route":o}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),s&&s.statusCode&&(a=s.statusCode),y.endTrace(a,{route:o}),s}catch(o){y.captureError(o);let s=o.statusCode||o.status||500;throw y.endTrace(s,{route:N(t,n)}),o}})};var St=e=>async(t,r)=>{let n=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",s={},a,i;return typeof t.headers.get=="function"?(a=t.headers.get("user-agent"),i=t.headers.get("x-forwarded-for"),t.headers.forEach((p,c)=>{s[c]=p})):(s=t.headers,a=s["user-agent"],i=s["x-forwarded-for"]),y.startTrace({method:o,path:n.pathname,userAgent:a,ip:i||T(t),headers:s},async()=>{try{let p=x(n.pathname),c=await z(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.app_route_handler ${o} ${p}`,route:p,method:o,request:t,attributes:{"next.router":"app","http.route":p,"url.path":n.pathname}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),u=c?.status||200;return y.endTrace(u,{route:p}),c}catch(p){throw y.captureError(p),y.endTrace(500,{route:x(n.pathname)}),p}})},kt=e=>async(t,r)=>{let n=t.url?t.url.split("?")[0]:"/";return y.startTrace({method:t.method||"GET",path:n,userAgent:t.headers["user-agent"],ip:T(t),headers:t.headers},async()=>{let o=()=>{y.endTrace(r.statusCode||200,{route:x(n)})};r.once("finish",o),r.once("close",o);try{let s=x(n);return await z(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.pages_api_handler ${t.method||"GET"} ${s}`,route:s,method:t.method||"GET",request:t,response:r,attributes:{"next.router":"pages","http.route":s}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!0})}catch(s){throw y.captureError(s),s}})};var wt=(e,t,r)=>{t&&t.apiKey&&y.init(t),We(e,t),e.addHook("onRequest",(n,o,s)=>{y.startTrace({method:n.method,path:n.raw.url||n.url,ip:T(n),userAgent:n.headers["user-agent"],headers:n.headers},()=>s())}),e.addHook("onError",(n,o,s,a)=>{y.captureError(s),a()}),e.addHook("onResponse",(n,o,s)=>{let a=n.routeOptions?.url||n.routerPath||"UNKNOWN";y.endTrace(o.statusCode,{route:a}),s()}),r()};var bt={preload:(e={})=>y.preload(e),init:e=>y.init(e),flush:()=>y.flush(),track:y.track.bind(y),startSpan:y.startSpan.bind(y),captureException:y.captureError.bind(y),wrapTask:y.wrapTask.bind(y),startTask:y.startTask.bind(y),requestHandler:mt,errorHandler:yt,wrapNextRoute:St,wrapNextPages:kt,wrapH3:gt,fastifyPlugin:wt},Fr=bt;0&&(module.exports={Senzor});
|
|
1
|
+
"use strict";var Et=Object.create;var j=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var At=(e,t)=>{for(var r in t)j(e,r,{get:t[r],enumerable:!0})},Se=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zt(t))!Ct.call(e,o)&&o!==r&&j(e,o,{get:()=>t[o],enumerable:!(n=xt(t,o))||n.enumerable});return e};var Z=(e,t,r)=>(r=e!=null?Et(Tt(e)):{},Se(t||!e||!e.__esModule?j(r,"default",{value:e,enumerable:!0}):r,e)),It=e=>Se(j({},"__esModule",{value:!0}),e);var Lr={};At(Lr,{Senzor:()=>bt,default:()=>Fr});module.exports=It(Lr);var A="x-senzor-sdk-internal";var Q=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.taskQueue=[];this.taskErrorQueue=[];this.taskLogQueue=[];this.timer=null;this.isFlushing=!1;this.flushAgain=!1;this.droppedItems=0;let r=t.endpoint||"https://api.senzor.dev";this.apmEndpoint=r.includes("/api/ingest")?r:`${r}/api/ingest/apm`,this.taskEndpoint=r.includes("/api/ingest")?r.replace("/apm","/task"):`${r}/api/ingest/task`,typeof setInterval<"u"&&(this.timer=setInterval(()=>{this.flush()},t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()),this.installShutdownFlush()}addTrace(t){this.enqueue(this.traceQueue,t),this.checkFlush()}addTask(t){this.enqueue(this.taskQueue,t),this.checkFlush()}addError(t,r="apm"){this.enqueue(r==="task"?this.taskErrorQueue:this.apmErrorQueue,t),this.checkFlush()}addLog(t,r="apm"){this.enqueue(r==="task"?this.taskLogQueue:this.apmLogQueue,t),this.checkFlush()}enqueue(t,r){t.push(r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.shift(),this.droppedItems++}prependWithLimit(t,r){if(!r.length)return;t.unshift(...r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.pop(),this.droppedItems++}checkFlush(){let t=this.traceQueue.length+this.apmErrorQueue.length+this.apmLogQueue.length,r=this.taskQueue.length+this.taskErrorQueue.length+this.taskLogQueue.length;(t>=(this.config.batchSize||100)||r>=(this.config.batchSize||100))&&this.flush()}takeApmPayload(){let t={traces:this.traceQueue,errors:this.apmErrorQueue,logs:this.apmLogQueue};return this.traceQueue=[],this.apmErrorQueue=[],this.apmLogQueue=[],t}takeTaskPayload(){let t={runs:this.taskQueue,errors:this.taskErrorQueue,logs:this.taskLogQueue};return this.taskQueue=[],this.taskErrorQueue=[],this.taskLogQueue=[],t}restoreApmPayload(t){this.prependWithLimit(this.apmLogQueue,t.logs),this.prependWithLimit(this.apmErrorQueue,t.errors),this.prependWithLimit(this.traceQueue,t.traces)}restoreTaskPayload(t){this.prependWithLimit(this.taskLogQueue,t.logs),this.prependWithLimit(this.taskErrorQueue,t.errors),this.prependWithLimit(this.taskQueue,t.runs)}hasApmPayload(t){return t.traces.length>0||t.errors.length>0||t.logs.length>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),this.config.flushTimeoutMs??5e3);typeof o.unref=="function"&&o.unref();try{let s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[A]:"true"},body:JSON.stringify(r),keepalive:!0,signal:n.signal});if(!s.ok)throw new Error(`Senzor ingest failed with status ${s.status}`)}finally{clearTimeout(o)}}async flush(){if(this.isFlushing){this.flushAgain=!0;return}this.isFlushing=!0;try{do{this.flushAgain=!1;let t=this.takeApmPayload(),r=this.takeTaskPayload(),n=[];if(this.hasApmPayload(t)&&n.push(this.postJson(this.apmEndpoint,t).catch(a=>{throw this.restoreApmPayload(t),a})),this.hasTaskPayload(r)&&n.push(this.postJson(this.taskEndpoint,r).catch(a=>{throw this.restoreTaskPayload(r),a})),!n.length)continue;let s=(await Promise.allSettled(n)).filter(a=>a.status==="rejected");this.config.debug&&console.log(`[Senzor] Flushed: APM(${t.traces.length} traces, ${t.logs.length} logs), Task(${r.runs.length} runs, ${r.logs.length} logs), failures=${s.length}, dropped=${this.droppedItems}`)}while(this.flushAgain)}catch(t){this.config.debug&&console.error("[Senzor] Transport Flush Error:",t)}finally{this.isFlushing=!1}}installShutdownFlush(){let t=Symbol.for("senzor.transport.shutdownFlushInstalled"),r=process;if(r[t])return;Object.defineProperty(r,t,{value:!0,enumerable:!1});let n=()=>{this.flush()};process.once("beforeExit",n)}};var ke=require("async_hooks"),v=new ke.AsyncLocalStorage,k={run:(e,t)=>v.run(e,t),withActiveSpan:(e,t)=>{let r=v.getStore();return r?v.run({...r,activeSpanId:e,data:r.data,spans:r.spans},t):t()},current:()=>v.getStore(),addSpan:e=>{let t=v.getStore();t&&k.addSpanToTrace(t,e)},addSpanToTrace:(e,t)=>{if(e.state.ended)return;let r=e.maxSpans??500;if(e.spans.length>=r){e.state.droppedSpans=(e.state.droppedSpans??0)+1;return}e.spans.push(t)}};var ht=require("crypto");var oe=Z(require("http")),se=Z(require("https")),C=require("url");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],N=(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 Ot=64,ee=2048,Rt=4,Pt=20,_t=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Ft=e=>({maxAttributes:e?.maxAttributes??Ot,maxAttributeLength:e?.maxAttributeLength??ee}),O=(e,t=ee)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Lt=e=>_t.test(e),Mt=(e,t)=>{if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(typeof e=="string")return O(e,t)},Y=(e,t,r,n)=>{if(Lt(e))return"[REDACTED]";let o=Mt(t,r.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:O(t.name,r.maxAttributeLength),message:O(t.message,r.maxAttributeLength),stack:t.stack?O(t.stack,r.maxAttributeLength):void 0};if(n>=Rt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Pt).map(s=>Y(e,s,r,n+1));if(typeof t=="object"){let s={},a=0;for(let[i,p]of Object.entries(t)){if(a>=r.maxAttributes){s.__truncated=!0;break}s[i]=Y(i,p,r,n+1),a++}return s}return O(String(t),r.maxAttributeLength)},R=(e={},t)=>{let r=Ft(t),n={maxAttributes:r.maxAttributes,maxAttributeLength:r.maxAttributeLength},o={},s=0;for(let[a,i]of Object.entries(e)){if(s>=n.maxAttributes){o.__truncated=!0;break}o[a]=Y(a,i,n,0),s++}return o},we=(e,t)=>{if(!e||typeof e!="object")return{};let r={};if(typeof e.forEach=="function")e.forEach((n,o)=>{r[o.toLowerCase()]=n});else for(let[n,o]of Object.entries(e))r[n.toLowerCase()]=Array.isArray(o)?o.join(", "):o;return R(r,t)},P=(e,t)=>{if(typeof e!="string")return;let r=e.replace(/\s+/g," ").trim();if(!r)return;let n=r.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return O(t?.captureDbStatement===!1?n.split(" ").slice(0,6).join(" "):n,t?.maxAttributeLength??ee)},W=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase();var te=require("net"),Ht=e=>e.startsWith("::ffff:")?e.slice(7):e,$t=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let r=e.slice(0,t);return(0,te.isIP)(r)===4?r:e},vt=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},I=e=>{if(!e)return null;let t=e.trim();return t?(t=vt(t),t=$t(t),t=Ht(t),(0,te.isIP)(t)!==0?t:null):null},be=e=>!!(e==="127.0.0.1"||e.startsWith("10.")||e.startsWith("192.168.")||e.startsWith("169.254.")||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||e==="::1"||e==="::"||e.toLowerCase().startsWith("fe80:")||e.toLowerCase().startsWith("fc")||e.toLowerCase().startsWith("fd")),Nt=e=>{let t=e.split(",");for(let r of t){let n=r.match(/for=["[]?([^\]",;>\s]+)/i);if(n){let o=I(n[1]);if(o&&!be(o))return o}}return null},Ut=e=>{let t=e.split(",").map(r=>r.trim());for(let r of t){let n=I(r);if(n&&!be(n))return n}for(let r of t){let n=I(r);if(n)return n}return null},z=e=>{let t=e.headers;{let r=I(t["cf-connecting-ip"]);if(r)return r}{let r=I(t["true-client-ip"]);if(r)return r}{let r=I(t["x-real-ip"]);if(r)return r}{let r=t.forwarded;if(r){let n=Nt(r);if(n)return n}}{let r=t["x-forwarded-for"];if(r){let n=Ut(r);if(n)return n}}{let r=e.socket?.remoteAddress,n=I(r);if(n)return n}return null};var qt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Ee=e=>{if(!e)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let r=t.trim().toLowerCase().match(qt);if(!r)return null;let n=r[1],o=r[2],s=r[3];if(n==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:n,parentSpanId:o,sampled:a}},_=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`;var xe=Symbol.for("senzor.patch.keys"),ze=Symbol.for("senzor.patch.original"),g=(e,t,r,n)=>{if(!e)return!1;let o=e[t];if(typeof o!="function")return!1;let s=o[xe];if(s?.has(r))return!1;let a=o[ze]||o,i=n(o),p=new Set(s||[]);p.add(r);try{Object.defineProperty(i,xe,{value:p,enumerable:!1}),Object.defineProperty(i,ze,{value:a,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}};var re=require("crypto"),ne=()=>(0,re.randomUUID)().replace(/-/g,""),U=()=>(0,re.randomUUID)().replace(/-/g,"").slice(0,16);var b=(e,t,r={},n)=>{let o=k.current();if(!o)return null;let s=U(),a=o.activeSpanId,i=performance.now()-o.startTime,p=performance.now(),c=!1;return{spanId:s,parentSpanId:a,trace:o,end:(u,d={})=>{if(c)return;c=!0;let f=R({...r,...d,parentSpanId:a},n);k.addSpanToTrace(o,{spanId:s,parentSpanId:a,name:e,type:t,startTime:i,duration:performance.now()-p,status:u,meta:f})}}},E=(e,t)=>e?k.withActiveSpan(e.spanId,t):t();var Dt=e=>!!e?.debug,Te=e=>typeof e=="object"&&e!==null&&!(e instanceof C.URL)&&!(e instanceof Function)&&!Array.isArray(e),jt=(e,t)=>{if(e){if(typeof Headers<"u"&&e instanceof Headers)return e.get(t);if(Array.isArray(e))return e.find(([n])=>String(n).toLowerCase()===t.toLowerCase())?.[1];if(typeof e=="object"){let r=t.toLowerCase();for(let[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o}}},Ie=e=>String(jt(e,A)||"").toLowerCase()==="true",Oe=(e,t,r)=>{if(Ie(r))return!0;if(!e)return!1;try{let n=new C.URL(e),o=new C.URL(t);return n.hostname===o.hostname&&n.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},ae=e=>{if(!e)return{};if(typeof Headers<"u"&&e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?e.reduce((t,[r,n])=>(t[r]=n,t),{}):typeof e=="object"?{...e}:{}},F=(e,t,r)=>{let n=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[n||t]=r},Qt=(e,t)=>{let r=[...e],n=0,o={},s=null;if(typeof r[0]=="string"||r[0]instanceof C.URL){try{s=new C.URL(r[0].toString())}catch{s=null}Te(r[1])?(n=1,o={...r[1],headers:ae(r[1].headers)},r[1]=o):(n=1,o={headers:{}},r.splice(1,0,o))}else Te(r[0])?(n=0,o={...r[0],headers:ae(r[0].headers)},r[0]=o):(n=0,o={headers:{}},r[0]=o);o.headers||(o.headers={}),r[n]=o;let a=o.protocol||s?.protocol||(o.port===443?"https:":t),i=o.hostname||o.host||s?.hostname||"localhost",p=o.path||`${s?.pathname||"/"}${s?.search||""}`,c=s?s.toString():`${a}//${i}${p}`,u=String(o.method||"GET").toUpperCase();return{args:r,options:o,url:c,method:u,hostname:String(i).replace(/:\d+$/,""),path:p}},Wt=(e,t,r)=>{if(t?.statusCode===404)return"Not Found";try{return N(e,r)}catch{return x(r)}},Ce=(e,t,r,n)=>{g(e,"emit",`senzor.${t}.server`,o=>function(a,...i){if(a!=="request")return o.call(this,a,...i);let p=i[0],c=i[1];if(!p||!c||k.current()?.contextType==="apm")return o.call(this,a,...i);let u=p.originalUrl||p.url||"/",d=String(u).split("?")[0]||"/",f=p.headers||{};return Ie(f)?o.call(this,a,...i):r.startTrace({method:p.method||"GET",path:u,route:x(d),ip:z(p),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:p.httpVersion,headers:n?.captureHeaders?we(f,n):void 0}},()=>{let l=k.current(),m=!1,h=w=>{m||!l||(m=!0,setImmediate(()=>{l.state.ended||k.run(l,()=>{r.endTrace(c.statusCode||0,{route:Wt(p,c,d),statusMessage:c.statusMessage,meta:{...l.data.meta,endReason:w}})})}))};c.once("finish",()=>h("finish")),c.once("close",()=>h("close")),c.once("error",w=>{r.captureError(w,{instrumentation:`${t}.server`}),h("error")});try{return o.call(this,a,...i)}catch(w){throw r.captureError(w,{instrumentation:`${t}.server`}),h("error"),w}})})},Ae=(e,t,r,n)=>{let o=t==="https:"?"senzor.https":"senzor.http",s=a=>function(...p){let c=Qt(p,t);if(Oe(c.url,r,c.options.headers))return a.apply(this,p);let u=k.current();if(!u)return a.apply(this,p);let d=b(`${c.method} ${c.hostname}`,"http",{url:c.url,method:c.method,library:t==="https:"?"https":"http","http.request.method":c.method,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);d&&(F(c.options.headers,"traceparent",_(u.id,d.spanId)),F(c.options.headers,"x-senzor-trace-id",u.id),F(c.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=a.apply(this,c.args);if(!d||!l||typeof l.once!="function")return l;let m=!1,h=(w,D={})=>{m||(m=!0,d.end(w,D))};return l.once("response",w=>{let D=w?.statusCode||0,ye=()=>h(D,{"http.response.status_code":D});w.once("end",ye),w.once("close",ye),w.once("error",ge=>h(500,{error:ge.message,"error.type":ge.name}))}),l.once("timeout",()=>h(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",w=>h(500,{error:w.message,"error.type":w.name})),l};return Dt(n)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),E(d,f)};g(e,"request",`${o}.request`,s),g(e,"get",`${o}.get`,s)},Re=(e,t)=>{globalThis.fetch&&g(globalThis,"fetch","senzor.fetch",r=>async function(o,s){let a=typeof o=="string"?o:o instanceof C.URL?o.toString():o?.url||"",i=s?.headers||o?.headers;if(Oe(a,e,i))return r.call(this,o,s);let p=k.current();if(!p)return r.call(this,o,s);let c="unknown",u="/";try{let h=new C.URL(a);c=h.hostname,u=`${h.pathname}${h.search}`}catch{}let d=String(s?.method||o?.method||"GET").toUpperCase(),f=b(`${d} ${c}`,"http",{url:a,method:d,library:"fetch","http.request.method":d,"url.full":a,"url.path":u,"server.address":c},t);if(!f)return r.call(this,o,s);let l={...s||{}},m=typeof Headers<"u"?new Headers(i||void 0):ae(i);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",_(p.id,f.spanId)),m.set("x-senzor-trace-id",p.id),m.set("x-senzor-parent-span-id",f.spanId)):(F(m,"traceparent",_(p.id,f.spanId)),F(m,"x-senzor-trace-id",p.id),F(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,E(f,async()=>{try{let h=await r.call(this,o,l);return f.end(h.status,{"http.response.status_code":h.status}),h}catch(h){throw f.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}})})},Pe=(e,t,r)=>{Ce(oe.default.Server?.prototype,"http",e,r),Ce(se.default.Server?.prototype,"https",e,r),Ae(oe.default,"http:",t,r),Ae(se.default,"https:",t,r)};var q=Z(require("module")),_e=Symbol.for("senzor.require.patched"),K=Symbol.for("senzor.require.hooks"),G=q.default.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/");function Kt(){let e=q.default;return e[K]||Object.defineProperty(e,K,{value:new Map,enumerable:!1}),e[K]}function Gt(e,t){let r=q.default[K];if(!r)return t;let n=r.get(e);if(!n?.length)return t;let o=t;for(let s of n)try{let a=s(o);a!==void 0&&(o=a)}catch(a){console.error(`[Senzor] instrumentation failed for ${e}`,a)}return o}function Bt(){let e=q.default;if(e[_e])return;let t=e._load;e._load=function(n,o,s){let a=t.apply(this,arguments);return Gt(n,a)},Object.defineProperty(e,_e,{value:!0,enumerable:!1})}function Vt(e,t){try{let r=G.resolve(e),n=G.cache?.[r];if(n?.exports){let o=t(n.exports);o!==void 0&&(n.exports=o)}}catch{}}function Jt(e,t){try{let r=G(e);r&&t(r)}catch{}}function Xt(e,t){let r=0,n=5,o=setInterval(()=>{r++;try{let s=G(e);s&&(t(s),clearInterval(o))}catch{}r>=n&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var S=(e,t)=>{let r=Kt();r.has(e)||r.set(e,[]),r.get(e).push(t),Bt(),Vt(e,t),Jt(e,t),Xt(e,t)};var Zt=new Set([void 0,null,"route","router"]),Yt=(e,t)=>!(t?.frameworkSpans===!1||e==="middleware"&&t?.captureMiddlewareSpans===!1||e==="router"&&t?.captureRouterSpans===!1||e==="lifecycle_hook"&&t?.captureLifecycleHookSpans===!1||t?.ignoreFrameworkSpanTypes?.includes(e)),L=(e,t=0)=>{let r=e.response;return r?.statusCode||r?.status||r?.raw?.statusCode||r?.status_code||t},er=e=>!!(e&&typeof e.then=="function"),tr=(e,t)=>e.parentSpanId?k.withActiveSpan(e.parentSpanId,t):t(),rr=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}},T=(e,t,r,n,o,s={})=>{if(!Yt(n.type,o)||!k.current())return e.apply(t,r);let a=b(n.name,"function",{framework:n.framework,"senzor.framework":n.framework,"senzor.framework.type":n.type,"http.route":n.route,route:n.route,method:n.method,layerPath:n.layerPath,handlerName:n.handlerName,...n.attributes},o);if(!a)return e.apply(t,r);let i=!1,p=[],c=(f=L(n),l={})=>{if(!i){i=!0;for(let m of p)try{m()}catch{}a.end(f,l)}},u=n.response;if(s.responseEndsSpan!==!1&&u?.once){let f=()=>c(L(n),{completion:"response.finish"}),l=()=>c(L(n),{completion:"response.close"});u.once("finish",f),u.once("close",l),p.push(()=>{try{u.removeListener?.("finish",f)}catch{}try{u.removeListener?.("close",l)}catch{}})}let d=s.callbackIndex??r.findIndex(f=>typeof f=="function");if(s.callbackCompletesSpan!==!1&&d>=0&&typeof r[d]=="function"){let f=r[d];r[d]=function(...m){let h=m[0],w=!Zt.has(h);return c(w?500:L(n),{completion:"callback",error:w?String(h?.message||h):void 0,"error.type":w?h?.name||typeof h:void 0}),tr(a,()=>f.apply(this,m))}}return E(a,()=>{try{let f=e.apply(t,r);return er(f)?f.then(l=>(c(L(n),{completion:"promise.resolve"}),l),l=>{throw c(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&s.responseEndsSpan===!1&&c(L(n),{completion:"sync.return"}),f)}catch(f){throw c(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})};var M=(e,t,r,n={})=>{if(typeof e!="function")return e;let o=(a,i)=>T(e,a,i,t(a,i),r,n),s;switch(e.length){case 4:s=function(i,p,c,u){return o(this,[i,p,c,u])};break;case 3:s=function(i,p,c){return o(this,[i,p,c])};break;case 2:s=function(i,p){return o(this,[i,p])};break;case 1:s=function(i){return o(this,[i])};break;default:s=function(){return o(this,Array.from(arguments))};break}return rr(e,s),s};var Fe=Symbol.for("senzor.express.layer.patched"),nr=new Set(["checkout","copy","delete","get","head","lock","merge","mkactivity","mkcol","move","m-search","notify","options","patch","post","purge","put","report","search","subscribe","trace","unlock","unsubscribe"]),ce=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ce).filter(Boolean).join(",");if(typeof e=="number")return String(e)},ie=e=>{for(let t of e){if(typeof t=="function")return;let r=ce(t);if(r)return r}},Le=(e,t,r)=>{if(t?.route?.path){let o=ce(t.route.path);return`${e?.baseUrl||""}${o}`||o}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(r){let o=e?.baseUrl||"";return o===r||o.endsWith(r)?o:`${o}${r}`||r}let n=e?.originalUrl||e?.url||e?.path;return n?x(String(n).split("?")[0]):void 0},or=(e,t,r)=>r||(t.length===4?"error_handler":e?.route?"request_handler":e?.name==="router"||e?.handle?.name==="router"||typeof e?.handle?.stack<"u"||typeof e?.handle?.route=="function"?"router":"middleware"),Me=(e,t)=>{if(e?.route?.methods){let r=Object.keys(e.route.methods).find(n=>e.route.methods[n]);if(r)return r.toUpperCase()}return t?.method},He=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}if(e.stack&&!t.stack)try{t.stack=e.stack}catch{}},B=(e,t,r,n)=>{!e||e[Fe]||typeof e.handle!="function"||(Object.defineProperty(e,Fe,{value:!0,enumerable:!1}),g(e,"handle","senzor.express.layer.handle",o=>{let s=or(e,o,n),a=o.name||e.name||(s==="request_handler"?"handler":s);if(o.length===4){let p=function(u,d,f,l){let m=Le(d,e,t);return T(o,this,[u,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||a}`,route:m,method:Me(e,d),layerPath:t,handlerName:a,request:d,response:f,attributes:{"express.type":"error_handler","express.layer.name":e.name,error:u?.message,"error.type":u?.name||typeof u}},r,{callbackIndex:3,callbackCompletesSpan:!0,responseEndsSpan:!0})};return He(o,p),p}let i=function(c,u,d){let f=Le(c,e,t),l=Me(e,c),m=f||t||a,h=s==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${s} ${m}`;return T(o,this,[c,u,d],{framework:"express",type:s,name:h,route:f,method:l,layerPath:t,handlerName:a,request:c,response:u,attributes:{"express.type":s,"express.layer.name":e.name,"http.route":f}},r,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return He(o,i),i}))},sr=(e,t,r)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let n of nr)typeof e[n]=="function"&&g(e,n,`senzor.express.route.${n}`,o=>function(...a){let i=o.apply(this,a),p=this?.stack||[];for(let c of p)B(c,t,r,"request_handler");return i})}},$e=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},ve=(e,t)=>{if(!e)return;let r=typeof e?.Router?.prototype?.use=="function"?e.Router.prototype:e.Router;g(r,"route","senzor.express.router.route",n=>function(...s){let a=n.apply(this,s),i=ie(s),p=this?.stack||[],c=p[p.length-1];return B(c,i,t,"router"),sr(a,i,t),a}),g(r,"use","senzor.express.router.use",n=>function(...s){let a=this?.stack?.length||0,i=n.apply(this,s),p=this?.stack||[];for(let c=a;c<p.length;c++)B(p[c],ie(s),t);return i}),g(e.application,"use","senzor.express.application.use",n=>function(...s){let i=$e(this)?.stack?.length||0,p=n.apply(this,s),u=$e(this)?.stack||[];for(let d=i;d<u.length;d++)B(u[d],ie(s),t);return p})},Ne=e=>{S("express",t=>{ve(t,e),t?.default&&ve(t.default,e)})};var Ue=Symbol.for("senzor.fastify.factory.patched"),qe=Symbol.for("senzor.fastify.instance.patched"),ar=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),ir=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],ue=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,De=(e,t,r,n)=>typeof t!="function"?t:M(t,(o,s)=>{let a=s[0],i=s[1],p=ue(a,n);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${p||a?.url||""}`.trim(),route:p,method:a?.method,handlerName:t.name||e,request:a,response:i?.raw||i,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":p,url:a?.url}}},r,{callbackCompletesSpan:!0,responseEndsSpan:!1}),cr=(e,t,r)=>typeof e!="function"?e:M(e,(n,o)=>{let s=o[0],a=o[1],i=ue(s,r);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${s?.method||""} ${i||s?.url||""}`.trim(),route:i,method:s?.method,handlerName:e.name||"handler",request:s,response:a?.raw||a,attributes:{"fastify.type":"route_handler","http.route":i,url:s?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),pr=(e,t)=>Array.isArray(e)?e.map(t):t(e),je=(e,t)=>(!e||e[qe]||(Object.defineProperty(e,qe,{value:!0,enumerable:!1}),g(e,"addHook","senzor.fastify.addHook",r=>function(o,s){return ar.has(o)?r.call(this,o,De(o,s,t)):r.apply(this,arguments)}),g(e,"route","senzor.fastify.route",r=>function(o){if(!o||typeof o!="object")return r.apply(this,arguments);let s={...o},a=s.url||s.path||s.routePath;s.handler&&(s.handler=cr(s.handler,t,a));for(let i of ir)s[i]&&(s[i]=pr(s[i],p=>De(i,p,t,a)));return r.call(this,s)}),g(e,"setErrorHandler","senzor.fastify.setErrorHandler",r=>function(o){return r.call(this,M(o,(s,a)=>{let i=a[1],p=a[2],c=ue(i);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${c||i?.url||""}`.trim(),route:c,method:i?.method,handlerName:o?.name||"errorHandler",request:i,response:p?.raw||p,attributes:{"fastify.type":"error_handler",error:a[0]?.message,"error.type":a[0]?.name||typeof a[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),ur=(e,t)=>{for(let r of Reflect.ownKeys(e))if(!["length","name","prototype"].includes(String(r)))try{Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}catch{}},pe=(e,t)=>{if(typeof e!="function"||e[Ue])return e;let r=function(...s){let a=e.apply(this,s);return je(a,t)};ur(e,r),Object.defineProperty(r,Ue,{value:!0,enumerable:!1});let n=r;return n.fastify===e&&(n.fastify=n),n.default===e&&(n.default=n),n},Qe=e=>{S("fastify",t=>typeof t=="function"?pe(t,e):(t?.fastify&&(t.fastify=pe(t.fastify,e)),t?.default&&(t.default=pe(t.default,e)),t))},We=(e,t)=>je(e,t);var dr=["all","del","delete","get","head","options","patch","post","put"],Be=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(Be).filter(Boolean).join(",")},Ke=e=>{for(let t of e){if(typeof t=="function")return;let r=Be(t);if(r)return r}},de=(e,t,r,n="middleware",o)=>typeof e!="function"?e:M(e,(s,a)=>{let i=a[0],p=i?._matchedRoute||i?.matched?.[0]?.path||r||x(i?.path||i?.request?.path||"/"),c=o||i?.method||i?.request?.method,u=e.name||n;return{framework:"koa",type:n,name:n==="route_handler"?`koa.request_handler ${c||""} ${p}`.trim():`koa.${n} ${p||u}`,route:p,method:c,layerPath:r,handlerName:u,request:i?.req||i?.request,response:i?.res||i?.response,attributes:{"koa.type":n,"http.route":p,path:i?.path||i?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),fr=(e,t)=>{let r=e?.prototype||e?.default?.prototype;r&&g(r,"use","senzor.koa.application.use",n=>function(s){return n.call(this,de(s,t,void 0,"middleware"))})},Ge=(e,t)=>{let n=(e?.Router||e?.default||e)?.prototype;if(n){g(n,"use","senzor.koa.router.use",o=>function(...a){let i=Ke(a),p=a.map(c=>typeof c=="function"?de(c,t,i,"router"):c);return o.apply(this,p)});for(let o of dr)g(n,o,`senzor.koa.router.${o}`,s=>function(...i){let p=Ke(i),c=i.map(u=>typeof u=="function"?de(u,t,p,"route_handler",o.toUpperCase()):u);return s.apply(this,c)})}},Ve=e=>{S("koa",t=>{fr(t,e)}),S("@koa/router",t=>{Ge(t,e)}),S("koa-router",t=>{Ge(t,e)})};var lr=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",Je=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,hr=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",mr=(e,t,r)=>{g(e,t,`senzor.mongodb.collection.${t}`,n=>function(...s){let a=lr(this),i=b(`MongoDB ${t}`,"db",{collection:a,operation:t,"db.system.name":"mongodb","db.collection.name":a,"db.namespace":Je(this)?`${Je(this)}.${a}`:a,"db.operation.name":t,library:"mongodb"},r);return i?E(i,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(c=>(i.end(0,{matchedCount:c?.matchedCount,modifiedCount:c?.modifiedCount,deletedCount:c?.deletedCount,insertedCount:c?.insertedCount}),c),c=>{throw i.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(i.end(0),p)}catch(p){throw i.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}}):n.apply(this,s)})},Xe=(e,t,r,n)=>{g(e,t,`senzor.mongodb.cursor.${r}.${t}`,o=>function(...a){let i=hr(this),p=b(`MongoDB ${r}`,"db",{collection:i,operation:r,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":r,library:"mongodb"},n);return p?E(p,()=>{try{let c=o.apply(this,a);return c&&typeof c.then=="function"?c.then(u=>(p.end(0,{resultCount:Array.isArray(u)?u.length:void 0}),u),u=>{throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(p.end(0),c)}catch(c){throw p.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):o.apply(this,a)})},yr=(e,t)=>{let n=(e?.Collection||e?.default?.Collection)?.prototype;["insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOne","findOneAndUpdate","findOneAndDelete","findOneAndReplace","countDocuments","estimatedDocumentCount","distinct","bulkWrite","createIndex","dropIndex"].forEach(a=>mr(n,a,t));let o=e?.FindCursor||e?.default?.FindCursor,s=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(a=>Xe(o?.prototype,a,"find",t)),["toArray","next","forEach"].forEach(a=>Xe(s?.prototype,a,"aggregate",t))},Ze=e=>{S("mongodb",t=>yr(t,e))};var gr=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},V=(e,t,r)=>{g(e,"query",`senzor.pg.${t}.query`,n=>function(...s){let a=gr(s),i=W(a)||"QUERY",p=b(`Postgres ${i}`,"db",{query:P(a,r),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":P(a,r),library:"pg"},r);if(!p)return n.apply(this,s);let c=s.findIndex(u=>typeof u=="function");if(c>=0){let u=s[c];s[c]=function(f,l){return p.end(f?500:0,{error:f?.message,"error.type":f?.name,rowCount:l?.rowCount,"db.response.row_count":l?.rowCount}),u.apply(this,arguments)}}return E(p,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(d=>(p.end(0,{rowCount:d?.rowCount,"db.response.row_count":d?.rowCount}),d),d=>{throw p.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(c<0&&u&&typeof u.once=="function"?(u.once("end",()=>p.end(0)),u.once("error",d=>p.end(500,{error:d.message,"error.type":d.name}))):c<0&&p.end(0),u)}catch(u){throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}})})},Sr=(e,t)=>{e&&(V(e.Client?.prototype,"client",t),V(e.Pool?.prototype,"pool",t),e.default&&(V(e.default.Client?.prototype,"default.client",t),V(e.default.Pool?.prototype,"default.pool",t)))},Ye=e=>{S("pg",t=>Sr(t,e))};var kr=e=>e?Array.isArray(e)?e.some(([t,r])=>String(t).toLowerCase()===A&&String(r).toLowerCase()==="true"):Object.entries(e).some(([t,r])=>t.toLowerCase()===A&&String(r).toLowerCase()==="true"):!1,fe=(e,t,r)=>{if(Array.isArray(e))return e.push([t,r]),e;let n={...e||{}},o=Object.keys(n).find(s=>s.toLowerCase()===t.toLowerCase());return n[o||t]=r,n},wr=e=>{try{let t=new URL(String(e));return{url:t.toString(),hostname:t.hostname,path:`${t.pathname}${t.search}`}}catch{return{url:String(e||""),hostname:"unknown",path:"/"}}},J=(e,t,r,n)=>{g(e,t,r,o=>function(a,i,p){if(kr(i?.headers))return o.apply(this,arguments);let c=wr(a?.origin?a.origin:a),u=String(i?.method||"GET").toUpperCase(),d=b(`${u} ${c.hostname}`,"http",{url:c.url,method:u,route:x(c.path),library:"undici","http.request.method":u,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);if(!d)return o.apply(this,arguments);let f={...i||{}};f.headers=fe(f.headers,"traceparent",_(d.trace.id,d.spanId)),f.headers=fe(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=fe(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof p=="function"?function(h,w){return d.end(h?500:w?.statusCode||0,{error:h?.message,"error.type":h?.name,"http.response.status_code":w?.statusCode}),p.apply(this,arguments)}:p;return E(d,()=>{try{let m=o.call(this,a,f,l);return m&&typeof m.then=="function"?m.then(h=>(d.end(h?.statusCode||h?.status||0,{"http.response.status_code":h?.statusCode||h?.status}),h),h=>{throw d.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}):(typeof l!="function"&&d.end(0),m)}catch(m){throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},br=(e,t)=>{J(e,"request","senzor.undici.request",t),J(e,"stream","senzor.undici.stream",t),J(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((r,n)=>{J(r,"request",`senzor.undici.dispatcher.${n}.request`,t)})},et=e=>{S("undici",t=>br(t,e))};var Er=e=>typeof e=="string"?e.toUpperCase():Array.isArray(e)?String(e[0]||"COMMAND").toUpperCase():e?.name?String(e.name).toUpperCase():Array.isArray(e?.args)?String(e.args[0]||"COMMAND").toUpperCase():"COMMAND",H=(e,t,r)=>{g(e,"sendCommand",`senzor.redis.${t}.sendCommand`,n=>function(s,...a){let i=Er(s),p=b(`Redis ${i}`,"db",{command:i,operation:i,"db.system.name":"redis","db.operation.name":i,library:t},r);return p?E(p,()=>{try{let c=n.call(this,s,...a);return c&&typeof c.then=="function"?c.then(u=>(p.end(0),u),u=>{throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(p.end(0),c)}catch(c){throw p.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,arguments)})},xr=(e,t,r)=>(H(e,t,r),H(Object.getPrototypeOf(e),t,r),e),zr=(e,t)=>{["createClient","createCluster"].forEach(r=>{g(e,r,`senzor.redis.${r}`,n=>function(...s){let a=n.apply(this,s);return xr(a,"redis",t)})})},Tr=(e,t)=>{H(e?.prototype,"ioredis",t),H(e?.Redis?.prototype,"ioredis",t),H(e?.Cluster?.prototype,"ioredis-cluster",t),H(e?.default?.prototype,"ioredis",t)},tt=e=>{S("redis",t=>zr(t,e)),S("ioredis",t=>Tr(t,e))};var Cr=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},$=(e,t,r,n)=>{g(e,t,`senzor.${r}.${t}`,o=>function(...a){let i=Cr(a),p=W(i)||t.toUpperCase(),c=b(`MySQL ${p}`,"db",{query:P(i,n),operation:p,"db.system.name":"mysql","db.operation.name":p,"db.query.text":P(i,n),library:r},n);if(!c)return o.apply(this,a);let u=a.findIndex(d=>typeof d=="function");if(u>=0){let d=a[u];a[u]=function(l,m){return c.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(m)?m.length:void 0}),d.apply(this,arguments)}}return E(c,()=>{try{let d=o.apply(this,a);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return c.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw c.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(u<0&&d&&typeof d.once=="function"?(d.once("end",()=>c.end(0)),d.once("error",f=>c.end(500,{error:f.message,"error.type":f.name}))):u<0&&c.end(0),d)}catch(d){throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},Ar=(e,t,r)=>{[e?.Connection?.prototype,e?.Pool?.prototype,e?.PoolConnection?.prototype,e?.PromiseConnection?.prototype,e?.PromisePool?.prototype,e?.default?.Connection?.prototype,e?.default?.Pool?.prototype].forEach(n=>{$(n,"query",t,r),$(n,"execute",t,r)})},Ir=(e,t,r)=>{["createConnection","createPool"].forEach(n=>{g(e,n,`senzor.${t}.${n}`,o=>function(...a){let i=o.apply(this,a);return $(i,"query",t,r),$(i,"execute",t,r),$(Object.getPrototypeOf(i),"query",t,r),$(Object.getPrototypeOf(i),"execute",t,r),i})})},rt=(e,t,r)=>{Ar(e,t,r),Ir(e,t,r)},nt=e=>{S("mysql",t=>rt(t,"mysql",e)),S("mysql2",t=>rt(t,"mysql2",e))};var st=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",at=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",X=(e,t,r)=>{g(e,"exec",`senzor.mongoose.${t}.exec`,n=>function(...s){let a=String(this?.op||this?._op||t).toUpperCase(),i=at(this),p=b(`Mongoose ${a}`,"db",{collection:i,model:st(this),operation:a,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":a,library:"mongoose"},r);return p?E(p,()=>{try{let c=n.apply(this,s);return c&&typeof c.then=="function"?c.then(u=>(p.end(0,{resultCount:Array.isArray(u)?u.length:void 0}),u),u=>{throw p.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(p.end(0),c)}catch(c){throw p.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,s)})},ot=(e,t)=>{g(e,"save","senzor.mongoose.model.save",r=>function(...o){let s=at(this),a=b("Mongoose SAVE","db",{collection:s,model:st(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":s,"db.operation.name":"SAVE",library:"mongoose"},t);return a?E(a,()=>{try{let i=r.apply(this,o);return i&&typeof i.then=="function"?i.then(p=>(a.end(0),p),p=>{throw a.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(a.end(0),i)}catch(i){throw a.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):r.apply(this,o)})},Or=(e,t)=>{X(e?.Query?.prototype,"query",t),X(e?.Aggregate?.prototype,"aggregate",t),ot(e?.Model?.prototype,t),e?.default&&(X(e.default?.Query?.prototype,"query",t),X(e.default?.Aggregate?.prototype,"aggregate",t),ot(e.default?.Model?.prototype,t))},it=e=>{S("mongoose",t=>Or(t,e))};var ct=Symbol.for("senzor.bullmq.patched");function pt(e,t,r){if(!e?.Worker?.prototype)return;let n=e.Worker.prototype,o=n.processJob;typeof o!="function"||o[ct]||(n.processJob=async function(s){let a=s.timestamp?Date.now()-s.timestamp:0,i=(s.attemptsMade||0)+1,p=s.opts?.attempts??1,c=i>=p,u=s.name==="__default__"?s.queueName:`${s.queueName}:${s.name}`;return t.startTask(u,"queue",{queueDelay:a,attempts:i,isDeadLetter:!1,metadata:{jobId:s.id,queueName:s.queueName,maxAttempts:p}},async()=>{try{let d=await o.call(this,s);return t.endTask("success"),d}catch(d){try{let f=k.current();f&&f.contextType==="task"&&c&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:s.queueName,jobId:s.id,isDeadLetter:c}),t.endTask("failed"),d}})},Object.defineProperty(n.processJob,ct,{value:!0}),r&&console.log("[Senzor] BullMQ instrumented"))}var ut=(e,t)=>{S("bullmq",r=>{pt(r,e,t),r?.default&&pt(r.default,e,t)})};var dt=Symbol.for("senzor.cron.patched");function Rr(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function ft(e,t,r){let n=e.schedule;if(typeof n!="function"||n[dt])return;let o=n,s=function(a,i,p){if(typeof i!="function")return o.call(this,a,i,p);try{let c=Rr(p),u=c?.name??`cron: ${a}`,d=t.wrapTask(u,"cron",{expression:a,metadata:c},i);return o.call(this,a,d,p)}catch(c){return r&&console.error("[Senzor] cron wrap failed",c),o.call(this,a,i,p)}};Object.defineProperty(s,dt,{value:!0,enumerable:!1});try{e.schedule=s}catch{r&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}r&&console.log("[Senzor] node-cron instrumented")}var lt=(e,t)=>{S("node-cron",r=>{r&&(ft(r,e,t),r.default&&ft(r.default,e,t))})};var le={name:"@senzops/apm-node",version:"1.2.5",description:"Universal APM SDK for Senzor",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",require:"./dist/index.js",import:"./dist/index.mjs"},"./register":{types:"./dist/register.d.ts",require:"./dist/register.js",import:"./dist/register.mjs"}},scripts:{build:"tsup",prepublishOnly:"npm run build"},devDependencies:{"@types/node":"^20.19.41",tsup:"^8.0.0",typescript:"^5.0.0"},engines:{node:">=18.0.0"},keywords:["apm","monitoring","senzor","node","javascript","api","observability"],author:"Senzops",license:"MIT"};var he={name:le.name,version:le.version};var _r=e=>{let t=new Set;return JSON.stringify(e,(r,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return"[Circular]";t.add(n)}return n})},me=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}preload(t={}){let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.options={apiKey:"",...this.options,...t},this.installNativeInstrumentations(r,n)}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.transport=new Q({...t,endpoint:r}),this.installNativeInstrumentations(r,n)}isInstrumentationEnabled(t){let r=this.options?.instrumentations;return r===!1?!1:Array.isArray(r)?r.includes(t):!0}installNativeInstrumentations(t,r){if(!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{this.isInstrumentationEnabled("http")&&Pe(this,t,this.options||void 0)}catch{}try{this.isInstrumentationEnabled("express")&&Ne(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("fastify")&&Qe(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("koa")&&Ve(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("fetch")&&Re(t,this.options||void 0)}catch{}try{this.isInstrumentationEnabled("undici")&&et(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mongo")&&Ze(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mongoose")&&it(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("pg")&&Ye(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mysql")&&nt(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("redis")&&tt(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("bullmq")&&ut(this,r)}catch{}try{this.isInstrumentationEnabled("cron")&<(this,r)}catch{}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}setupLogInterception(){if(this.options?.autoLogs===!1)return;let t=["log","info","warn","error","debug"],r={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},n=!1;t.forEach(o=>{console[o]=(...s)=>{if(r[o].apply(console,s),!(n||!this.transport)){n=!0;try{let a="",i={};s.forEach(d=>{if(typeof d=="string")a+=(a?" ":"")+d;else if(d instanceof Error)a+=(a?" ":"")+d.message,i.errorStack=d.stack,i.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(_r(d));i={...i,...R(f,this.options||void 0)}}catch{i.unparseableObject=!0}else a+=(a?" ":"")+String(d)}),!a&&Object.keys(i).length>0&&(a="Object Log");let p=k.current(),c=p?.contextType==="task"?"task":"apm",u={message:a||"Empty log",level:o==="log"?"info":o,attributes:i,timestamp:new Date().toISOString()};p&&(c==="task"?u.runId=p.id:u.traceId=p.id),this.transport.addLog(u,c)}catch{}finally{n=!1}}}})}setupGlobalErrorHandlers(){if(process.__senzorGlobalHandlersInstalled)return;process.__senzorGlobalHandlersInstalled=!0;let t=()=>{try{return{pid:process.pid,ppid:process.ppid,platform:process.platform,uptimeSec:Math.floor(process.uptime()),env:process.env.NODE_ENV||"unknown"}}catch{return{}}},r=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},n=(o,s={})=>{try{let a;if(o instanceof Error)a=o;else if(typeof o=="string")a=new Error(o);else try{a=new Error(JSON.stringify(o))}catch{a=new Error("Non-serializable rejection reason")}let i={...s,runtime:{name:"node",version:process.version},process:t(),memory:r(),sdk:{name:he.name,version:he.version}};this.captureError(a,i)}catch(a){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",a)}catch{}}};process.on("uncaughtExceptionMonitor",o=>n(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>n(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>n(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>n(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,s,a)=>n(a||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:o,severity:"warning"})),process.on("rejectionHandled",o=>{if(this.options?.debug)try{console.warn("[Senzor] rejectionHandled event detected")}catch{}}),process.on("SIGTERM",()=>n(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>n(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,r){if(!this.transport)return r();let n=k.current();if(n?.contextType==="apm")return Object.assign(n.data,t),r();let o,s;if(t.headers){let c=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},u=c("traceparent"),d=Ee(u);if(d)o=d.traceId,s=d.parentSpanId;else{let f=c("x-senzor-trace-id"),l=c("x-senzor-parent-span-id");o=Array.isArray(f)?f[0]:f,s=Array.isArray(l)?l[0]:l}}let a=o||ne(),i=U(),p={id:a,contextType:"apm",startTime:performance.now(),rootSpanId:i,activeSpanId:i,data:{...t,parentTraceId:o,parentSpanId:s,rootSpanId:i},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return k.run(p,r)}endTrace(t,r={}){let n=k.current();if(!n||n.contextType!=="apm"||!this.transport||n.state.ended)return;n.state.ended=!0;let o=performance.now()-n.startTime,s={traceId:n.id,parentTraceId:n.data.parentTraceId,parentSpanId:n.data.parentSpanId,rootSpanId:n.rootSpanId,...n.data,...r,status:t,duration:o,spans:n.spans,droppedSpans:n.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(s)}startTask(t,r,n,o){if(!this.transport)return o();let s=k.current(),a=s?.contextType==="apm"?s.id:void 0,i=process.memoryUsage?process.memoryUsage().heapUsed:0,p=process.cpuUsage?process.cpuUsage():void 0,c={id:(0,ht.randomUUID)(),contextType:"task",startTime:performance.now(),rootSpanId:U(),startMemory:i,startCpu:p,data:{taskName:t,taskType:r,triggerTraceId:a,...n},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return c.activeSpanId=c.rootSpanId,k.run(c,o)}endTask(t,r={}){let n=k.current();if(!n||n.contextType!=="task"||!this.transport||n.state.ended)return;n.state.ended=!0;let o;if(process.memoryUsage&&n.startMemory!==void 0&&process.cpuUsage&&n.startCpu){let a=process.memoryUsage().heapUsed,i=process.cpuUsage(n.startCpu);o={memoryDeltaBytes:a-n.startMemory,cpuUserUs:i.user,cpuSystemUs:i.system}}let s={runId:n.id,taskName:n.data.taskName,taskType:n.data.taskType,triggerTraceId:n.data.triggerTraceId,queueDelay:n.data.queueDelay,attempts:n.data.attempts,isDeadLetter:n.data.isDeadLetter,metadata:{...n.data.metadata,...r,droppedSpans:n.state.droppedSpans},resourceMetrics:o,status:t,duration:performance.now()-n.startTime,spans:n.spans,timestamp:new Date().toISOString()};this.transport.addTask(s)}wrapTask(t,r,n={},o){return(async(...s)=>this.startTask(t,r,n,async()=>{try{let a=await o(...s);return this.endTask("success"),a}catch(a){throw this.captureError(a,{taskName:t}),this.endTask("failed"),a}}))}captureError(t,r={}){if(!this.transport)return;let n;t instanceof Error?n=t:n=new Error(String(t));let o=k.current(),s={errorClass:n.name||"Error",message:n.message,stackTrace:n.stack,context:R(r,this.options||void 0),timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...s,runId:o.id},"task"):this.transport.addError({...s,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:ne(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,r="custom"){let n=b(t,r,{},this.options||void 0);return n?{end:(o,s)=>n.end(s,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},y=new me;var mt=()=>function(t,r,n){y.startTrace({method:t.method,path:t.originalUrl||t.url,ip:z(t),userAgent:t.headers["user-agent"],headers:t.headers},()=>{r.once("finish",()=>{try{let o="UNKNOWN";t.route&&t.route.path?o=(t.baseUrl||"")+t.route.path:r.statusCode===404?o="Not Found":o=t.path||"Wildcard",y.endTrace(r.statusCode,{route:o})}catch{}}),n()})},yt=()=>function(t,r,n,o){y.captureError(t),o(t)};var gt=e=>t=>{let r=t.node.req,n=r.originalUrl||r.url||"/";return y.startTrace({method:r.method||"GET",path:n,ip:z(r),userAgent:r.headers["user-agent"],headers:r.headers},async()=>{try{let o=N(t,n),s=await T(e,void 0,[t],{framework:"h3",type:"event_handler",name:`h3.event_handler ${r.method||"GET"} ${o}`,route:o,method:r.method||"GET",handlerName:e.name||"handler",request:r,response:t.node.res,attributes:{"h3.type":"event_handler","http.route":o}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),s&&s.statusCode&&(a=s.statusCode),y.endTrace(a,{route:o}),s}catch(o){y.captureError(o);let s=o.statusCode||o.status||500;throw y.endTrace(s,{route:N(t,n)}),o}})};var St=e=>async(t,r)=>{let n=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",s={},a,i;return typeof t.headers.get=="function"?(a=t.headers.get("user-agent"),i=t.headers.get("x-forwarded-for"),t.headers.forEach((p,c)=>{s[c]=p})):(s=t.headers,a=s["user-agent"],i=s["x-forwarded-for"]),y.startTrace({method:o,path:n.pathname,userAgent:a,ip:i||z(t),headers:s},async()=>{try{let p=x(n.pathname),c=await T(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.app_route_handler ${o} ${p}`,route:p,method:o,handlerName:e.name||"handler",request:t,attributes:{"next.router":"app","http.route":p,"url.path":n.pathname}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),u=c?.status||200;return y.endTrace(u,{route:p}),c}catch(p){throw y.captureError(p),y.endTrace(500,{route:x(n.pathname)}),p}})},kt=e=>async(t,r)=>{let n=t.url?t.url.split("?")[0]:"/";return y.startTrace({method:t.method||"GET",path:n,userAgent:t.headers["user-agent"],ip:z(t),headers:t.headers},async()=>{let o=()=>{y.endTrace(r.statusCode||200,{route:x(n)})};r.once("finish",o),r.once("close",o);try{let s=x(n);return await T(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.pages_api_handler ${t.method||"GET"} ${s}`,route:s,method:t.method||"GET",handlerName:e.name||"handler",request:t,response:r,attributes:{"next.router":"pages","http.route":s}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!0})}catch(s){throw y.captureError(s),s}})};var wt=(e,t,r)=>{t&&t.apiKey&&y.init(t),We(e,t),e.addHook("onRequest",function(o,s,a){y.startTrace({method:o.method,path:o.raw.url||o.url,ip:z(o),userAgent:o.headers["user-agent"],headers:o.headers},()=>a())}),e.addHook("onError",function(o,s,a,i){y.captureError(a),i()}),e.addHook("onResponse",function(o,s,a){let i=o.routeOptions?.url||o.routerPath||"UNKNOWN";y.endTrace(s.statusCode,{route:i}),a()}),r()};var bt={preload:(e={})=>y.preload(e),init:e=>y.init(e),flush:()=>y.flush(),track:y.track.bind(y),startSpan:y.startSpan.bind(y),captureException:y.captureError.bind(y),wrapTask:y.wrapTask.bind(y),startTask:y.startTask.bind(y),requestHandler:mt,errorHandler:yt,wrapNextRoute:St,wrapNextPages:kt,wrapH3:gt,fastifyPlugin:wt},Fr=bt;0&&(module.exports={Senzor});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|