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