@senzops/apm-node 1.2.5 → 1.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +11 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/register.js +1 -1
- package/dist/register.js.map +1 -1
- package/dist/register.mjs +1 -1
- package/dist/register.mjs.map +1 -1
- package/package.json +8 -3
- package/src/core/client.ts +37 -39
- package/src/core/context.ts +46 -2
- package/src/core/runtime.ts +15 -0
- package/src/core/transport.ts +2 -0
- package/src/index.ts +15 -7
- package/src/instrumentation/hook.ts +16 -12
- package/src/instrumentation/http.ts +15 -8
- package/src/register.ts +19 -18
- package/src/utils/getClientIp.ts +190 -175
- package/src/utils/ids.ts +20 -3
- package/src/wrappers/nitro.ts +60 -0
- package/src/wrappers/worker.ts +45 -0
- package/tsup.config.ts +9 -0
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.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);
|
|
1
|
+
"use strict";var ue=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Dt=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var A=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},jt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ut(t))!Dt.call(e,o)&&o!==n&&ue(e,o,{get:()=>t[o],enumerable:!(r=Ht(t,o))||r.enumerable});return e};var x=e=>jt(ue({},"__esModule",{value:!0}),e);var O,J=w(()=>{"use strict";O="x-senzor-sdk-internal"});var pe,Qt,K,S,P=w(()=>{"use strict";pe=class{run(t,n,...r){let o=this.store;this.store=t;try{return n(...r)}finally{this.store=o}}getStore(){return this.store}},Qt=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof require<"u"){let{AsyncLocalStorage:e}=require("async_hooks");if(e)return new e}}catch{}try{if(typeof require<"u"){let{AsyncLocalStorage:e}=require("async_hooks");if(e)return new e}}catch{}return new pe},K=Qt(),S={run:(e,t)=>K.run(e,t),withActiveSpan:(e,t)=>{let n=K.getStore();return n?K.run({...n,activeSpanId:e,data:n.data,spans:n.spans},t):t()},current:()=>K.getStore(),addSpan:e=>{let t=K.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 Kt,Oe,L,X=w(()=>{"use strict";Kt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Oe=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(Kt);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}},L=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var _e,ee,Z,le=w(()=>{"use strict";_e=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof require<"u"){let{randomUUID:e}=require("crypto");if(e)return e()}}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},ee=()=>_e().replace(/-/g,""),Z=()=>_e().replace(/-/g,"").slice(0,16)});var Zt,me,Bt,Gt,Vt,Jt,M,Yt,Xt,he,q,Pe,N,te,$=w(()=>{"use strict";Zt=64,me=2048,Bt=4,Gt=20,Vt=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Jt=e=>({maxAttributes:e?.maxAttributes??Zt,maxAttributeLength:e?.maxAttributeLength??me}),M=(e,t=me)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Yt=e=>Vt.test(e),Xt=(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 M(e,t)},he=(e,t,n,r)=>{if(Yt(e))return"[REDACTED]";let o=Xt(t,n.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:M(t.name,n.maxAttributeLength),message:M(t.message,n.maxAttributeLength),stack:t.stack?M(t.stack,n.maxAttributeLength):void 0};if(r>=Bt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Gt).map(a=>he(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]=he(i,u,n,r+1),s++}return a}return M(String(t),n.maxAttributeLength)},q=(e={},t)=>{let n=Jt(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]=he(s,i,r,0),a++}return o},Pe=(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 q(n,t)},N=(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 M(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??me)},te=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var b,T,R=w(()=>{"use strict";P();$();le();b=(e,t,n={},r)=>{let o=S.current();if(!o)return null;let a=Z(),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=q({...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})}}},T=(e,t)=>e?S.withActiveSpan(e.spanId,t):t()});var I,Fe,B=w(()=>{"use strict";I=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],Fe=(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:I(t)});var en,tn,Le,nn,rn,on,_,Me,sn,an,qe,Ne=w(()=>{"use strict";en=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,tn=/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$|^::(?:[a-fA-F0-9]{1,4}:){0,5}[a-fA-F0-9]{1,4}$|^[a-fA-F0-9]{1,4}::(?:[a-fA-F0-9]{1,4}:){0,4}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,2}:(?:[a-fA-F0-9]{1,4}:){0,3}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,3}:(?:[a-fA-F0-9]{1,4}:){0,2}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,4}:(?:[a-fA-F0-9]{1,4}:)?[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,5}:[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,6}:$|^::$|^::1$|^fe80:.*$/i,Le=e=>en.test(e)?4:tn.test(e)?6:0,nn=e=>e.startsWith("::ffff:")?e.slice(7):e,rn=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return Le(n)===4?n:e},on=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},_=e=>{if(!e)return null;let t=e.trim();return t?(t=on(t),t=rn(t),t=nn(t),Le(t)!==0?t:null):null},Me=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")),sn=e=>{let t=e.split(",");for(let n of t){let r=n.match(/for=["[]?([^\]",;>\s]+)/i);if(r){let o=_(r[1]);if(o&&!Me(o))return o}}return null},an=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=_(n);if(r&&!Me(r))return r}for(let n of t){let r=_(n);if(r)return r}return null},qe=e=>{let t=e.headers;{let n=_(t["cf-connecting-ip"]);if(n)return n}{let n=_(t["true-client-ip"]);if(n)return n}{let n=_(t["x-real-ip"]);if(n)return n}{let n=t.forwarded;if(n){let r=sn(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=an(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=_(n);if(r)return r}return null}});var $e,ve,y,C=w(()=>{"use strict";$e=Symbol.for("senzor.patch.keys"),ve=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[$e];if(a?.has(n))return!1;let s=o[ve]||o,i=r(o),u=new Set(a||[]);u.add(n);try{Object.defineProperty(i,$e,{value:u,enumerable:!1}),Object.defineProperty(i,ve,{value:s,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}}});var ge={};A(ge,{instrumentFetch:()=>fn,instrumentHttp:()=>ln});var cn,He,un,je,Qe,ye,v,pn,dn,Ue,De,fn,ln,Se=w(()=>{"use strict";P();B();$();Ne();J();X();C();R();cn=e=>!!e?.debug,He=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),un=(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}}},je=e=>String(un(e,O)||"").toLowerCase()==="true",Qe=(e,t,n)=>{if(je(n))return!0;if(!e)return!1;try{let r=new URL(e),o=new URL(t);return r.hostname===o.hostname&&r.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},ye=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}:{}},v=(e,t,n)=>{let r=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[r||t]=n},pn=(e,t)=>{let n=[...e],r=0,o={},a=null;if(typeof n[0]=="string"||n[0]instanceof URL){try{a=new URL(n[0].toString())}catch{a=null}He(n[1])?(r=1,o={...n[1],headers:ye(n[1].headers)},n[1]=o):(r=1,o={headers:{}},n.splice(1,0,o))}else He(n[0])?(r=0,o={...n[0],headers:ye(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}},dn=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return Fe(e,n)}catch{return I(n)}},Ue=(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 je(f)?o.call(this,s,...i):n.startTrace({method:u.method||"GET",path:p,route:I(d),ip:qe(u),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:u.httpVersion,headers:r?.captureHeaders?Pe(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:dn(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}})})},De=(e,t,n,r)=>{let o=t==="https:"?"senzor.https":"senzor.http",a=s=>function(...u){let c=pn(u,t);if(Qe(c.url,n,c.options.headers))return s.apply(this,u);let p=S.current();if(!p)return s.apply(this,u);let d=b(`${c.method} ${c.hostname}`,"http",{url:c.url,method:c.method,library:t==="https:"?"https":"http","http.request.method":c.method,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},r);d&&(v(c.options.headers,"traceparent",L(p.id,d.spanId)),v(c.options.headers,"x-senzor-trace-id",p.id),v(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,V={})=>{m||(m=!0,d.end(k,V))};return l.once("response",k=>{let V=k?.statusCode||0,Ce=()=>h(V,{"http.response.status_code":V});k.once("end",Ce),k.once("close",Ce),k.once("error",Re=>h(500,{error:Re.message,"error.type":Re.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 cn(r)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),T(d,f)};y(e,"request",`${o}.request`,a),y(e,"get",`${o}.get`,a)},fn=(e,t)=>{globalThis.fetch&&y(globalThis,"fetch","senzor.fetch",n=>async function(o,a){let s=typeof o=="string"?o:o instanceof URL?o.toString():o?.url||"",i=a?.headers||o?.headers;if(Qe(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 URL(s);c=h.hostname,p=`${h.pathname}${h.search}`}catch{}let d=String(a?.method||o?.method||"GET").toUpperCase(),f=b(`${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):ye(i);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",L(u.id,f.spanId)),m.set("x-senzor-trace-id",u.id),m.set("x-senzor-parent-span-id",f.spanId)):(v(m,"traceparent",L(u.id,f.spanId)),v(m,"x-senzor-trace-id",u.id),v(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,T(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}})})},ln=(e,t,n)=>{let r,o;try{r=require("http")}catch{return}try{o=require("https")}catch{}r?.Server?.prototype&&Ue(r.Server.prototype,"http",e,n),o?.Server?.prototype&&Ue(o.Server.prototype,"https",e,n),De(r,"http:",t,n),o&&De(o,"https:",t,n)}});function hn(){let e=H;return e[ne]||Object.defineProperty(e,ne,{value:new Map,enumerable:!1}),e[ne]}function mn(e,t){let n=H[ne];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 yn(){let e=H;if(e[We])return;let t=e._load;e._load=function(r,o,a){let s=t.apply(this,arguments);return mn(r,s)},Object.defineProperty(e,We,{value:!0,enumerable:!1})}function gn(e,t){try{let n=U.resolve(e),r=U.cache?.[n];if(r?.exports){let o=t(r.exports);o!==void 0&&(r.exports=o)}}catch{}}function Sn(e,t){try{let n=U(e);n&&t(n)}catch{}}function kn(e,t){let n=0,r=5,o=setInterval(()=>{n++;try{let a=U(e);a&&(t(a),clearInterval(o))}catch{}n>=r&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var H,U,We,ne,g,z=w(()=>{"use strict";try{H=require("module"),U=H.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}We=Symbol.for("senzor.require.patched"),ne=Symbol.for("senzor.require.hooks");g=(e,t)=>{if(!H||!U)return;let n=hn();n.has(e)||n.set(e,[]),n.get(e).push(t),yn(),gn(e,t),Sn(e,t),kn(e,t)}});var wn,bn,D,En,Tn,xn,re,j,oe=w(()=>{"use strict";P();R();wn=new Set([void 0,null,"route","router"]),bn=(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)),D=(e,t=0)=>{let n=e.response;return n?.statusCode||n?.status||n?.raw?.statusCode||n?.status_code||t},En=e=>!!(e&&typeof e.then=="function"),Tn=(e,t)=>e.parentSpanId?S.withActiveSpan(e.parentSpanId,t):t(),xn=(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{}},re=(e,t,n,r,o,a={})=>{if(!bn(r.type,o)||!S.current())return e.apply(t,n);let s=b(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=D(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(D(r),{completion:"response.finish"}),l=()=>c(D(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=!wn.has(h);return c(k?500:D(r),{completion:"callback",error:k?String(h?.message||h):void 0,"error.type":k?h?.name||typeof h:void 0}),Tn(s,()=>f.apply(this,m))}}return T(s,()=>{try{let f=e.apply(t,n);return En(f)?f.then(l=>(c(D(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(D(r),{completion:"sync.return"}),f)}catch(f){throw c(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},j=(e,t,n,r={})=>{if(typeof e!="function")return e;let o=(s,i)=>re(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 xn(e,a),a}});var Ye={};A(Ye,{instrumentExpress:()=>Rn});var Ke,An,we,ke,Ze,zn,Be,Ge,se,Cn,Ve,Je,Rn,Xe=w(()=>{"use strict";B();z();C();oe();Ke=Symbol.for("senzor.express.layer.patched"),An=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"]),we=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(we).filter(Boolean).join(",");if(typeof e=="number")return String(e)},ke=e=>{for(let t of e){if(typeof t=="function")return;let n=we(t);if(n)return n}},Ze=(e,t,n)=>{if(t?.route?.path){let o=we(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?I(String(r).split("?")[0]):void 0},zn=(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"),Be=(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},Ge=(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{}},se=(e,t,n,r)=>{!e||e[Ke]||typeof e.handle!="function"||(Object.defineProperty(e,Ke,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",o=>{let a=zn(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=Ze(d,e,t);return re(o,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||s}`,route:m,method:Be(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 Ge(o,u),u}let i=function(c,p,d){let f=Ze(c,e,t),l=Be(e,c),m=f||t||s,h=a==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${a} ${m}`;return re(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 Ge(o,i),i}))},Cn=(e,t,n)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let r of An)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)se(c,t,n,"request_handler");return i})}},Ve=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Je=(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=ke(a),u=this?.stack||[],c=u[u.length-1];return se(c,i,t,"router"),Cn(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++)se(u[c],ke(a),t);return i}),y(e.application,"use","senzor.express.application.use",r=>function(...a){let i=Ve(this)?.stack?.length||0,u=r.apply(this,a),p=Ve(this)?.stack||[];for(let d=i;d<p.length;d++)se(p[d],ke(a),t);return u})},Rn=e=>{g("express",t=>{Je(t,e),t?.default&&Je(t.default,e)})}});var ot={};A(ot,{instrumentFastify:()=>Ln,instrumentFastifyInstance:()=>Mn});var et,tt,In,On,Ee,nt,_n,Pn,rt,Fn,be,Ln,Mn,st=w(()=>{"use strict";z();C();oe();et=Symbol.for("senzor.fastify.factory.patched"),tt=Symbol.for("senzor.fastify.instance.patched"),In=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),On=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],Ee=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,nt=(e,t,n,r)=>typeof t!="function"?t:j(t,(o,a)=>{let s=a[0],i=a[1],u=Ee(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}),_n=(e,t,n)=>typeof e!="function"?e:j(e,(r,o)=>{let a=o[0],s=o[1],i=Ee(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}),Pn=(e,t)=>Array.isArray(e)?e.map(t):t(e),rt=(e,t)=>(!e||e[tt]||(Object.defineProperty(e,tt,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(o,a){return In.has(o)?n.call(this,o,nt(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=_n(a.handler,t,s));for(let i of On)a[i]&&(a[i]=Pn(a[i],u=>nt(i,u,t,s)));return n.call(this,a)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(o){return n.call(this,j(o,(a,s)=>{let i=s[1],u=s[2],c=Ee(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),Fn=(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{}},be=(e,t)=>{if(typeof e!="function"||e[et])return e;let n=function(...a){let s=e.apply(this,a);return rt(s,t)};Fn(e,n),Object.defineProperty(n,et,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},Ln=e=>{g("fastify",t=>typeof t=="function"?be(t,e):(t?.fastify&&(t.fastify=be(t.fastify,e)),t?.default&&(t.default=be(t.default,e)),t))},Mn=(e,t)=>rt(e,t)});var ut={};A(ut,{instrumentKoa:()=>$n});var qn,ct,at,Te,Nn,it,$n,pt=w(()=>{"use strict";B();z();C();oe();qn=["all","del","delete","get","head","options","patch","post","put"],ct=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ct).filter(Boolean).join(",")},at=e=>{for(let t of e){if(typeof t=="function")return;let n=ct(t);if(n)return n}},Te=(e,t,n,r="middleware",o)=>typeof e!="function"?e:j(e,(a,s)=>{let i=s[0],u=i?._matchedRoute||i?.matched?.[0]?.path||n||I(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}),Nn=(e,t)=>{let n=e?.prototype||e?.default?.prototype;n&&y(n,"use","senzor.koa.application.use",r=>function(a){return r.call(this,Te(a,t,void 0,"middleware"))})},it=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",o=>function(...s){let i=at(s),u=s.map(c=>typeof c=="function"?Te(c,t,i,"router"):c);return o.apply(this,u)});for(let o of qn)y(r,o,`senzor.koa.router.${o}`,a=>function(...i){let u=at(i),c=i.map(p=>typeof p=="function"?Te(p,t,u,"route_handler",o.toUpperCase()):p);return a.apply(this,c)})}},$n=e=>{g("koa",t=>{Nn(t,e)}),g("@koa/router",t=>{it(t,e)}),g("koa-router",t=>{it(t,e)})}});var dt={};A(dt,{instrumentUndici:()=>Dn});var vn,xe,Hn,ae,Un,Dn,ft=w(()=>{"use strict";B();J();X();z();C();R();vn=e=>e?Array.isArray(e)?e.some(([t,n])=>String(t).toLowerCase()===O&&String(n).toLowerCase()==="true"):Object.entries(e).some(([t,n])=>t.toLowerCase()===O&&String(n).toLowerCase()==="true"):!1,xe=(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},Hn=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:"/"}}},ae=(e,t,n,r)=>{y(e,t,n,o=>function(s,i,u){if(vn(i?.headers))return o.apply(this,arguments);let c=Hn(s?.origin?s.origin:s),p=String(i?.method||"GET").toUpperCase(),d=b(`${p} ${c.hostname}`,"http",{url:c.url,method:p,route:I(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=xe(f.headers,"traceparent",L(d.trace.id,d.spanId)),f.headers=xe(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=xe(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 T(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}})})},Un=(e,t)=>{ae(e,"request","senzor.undici.request",t),ae(e,"stream","senzor.undici.stream",t),ae(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((n,r)=>{ae(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},Dn=e=>{g("undici",t=>Un(t,e))}});var mt={};A(mt,{instrumentMongo:()=>Zn});var jn,lt,Qn,Wn,ht,Kn,Zn,yt=w(()=>{"use strict";z();C();R();jn=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",lt=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,Qn=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Wn=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...a){let s=jn(this),i=b(`MongoDB ${t}`,"db",{collection:s,operation:t,"db.system.name":"mongodb","db.collection.name":s,"db.namespace":lt(this)?`${lt(this)}.${s}`:s,"db.operation.name":t,library:"mongodb"},n);return i?T(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)})},ht=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,o=>function(...s){let i=Qn(this),u=b(`MongoDB ${n}`,"db",{collection:i,operation:n,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":n,library:"mongodb"},r);return u?T(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)})},Kn=(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=>Wn(r,s,t));let o=e?.FindCursor||e?.default?.FindCursor,a=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(s=>ht(o?.prototype,s,"find",t)),["toArray","next","forEach"].forEach(s=>ht(a?.prototype,s,"aggregate",t))},Zn=e=>{g("mongodb",t=>Kn(t,e))}});var wt={};A(wt,{instrumentMongoose:()=>Gn});var St,kt,ie,gt,Bn,Gn,bt=w(()=>{"use strict";z();C();R();St=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",kt=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",ie=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...a){let s=String(this?.op||this?._op||t).toUpperCase(),i=kt(this),u=b(`Mongoose ${s}`,"db",{collection:i,model:St(this),operation:s,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":s,library:"mongoose"},n);return u?T(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)})},gt=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...o){let a=kt(this),s=b("Mongoose SAVE","db",{collection:a,model:St(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":a,"db.operation.name":"SAVE",library:"mongoose"},t);return s?T(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)})},Bn=(e,t)=>{ie(e?.Query?.prototype,"query",t),ie(e?.Aggregate?.prototype,"aggregate",t),gt(e?.Model?.prototype,t),e?.default&&(ie(e.default?.Query?.prototype,"query",t),ie(e.default?.Aggregate?.prototype,"aggregate",t),gt(e.default?.Model?.prototype,t))},Gn=e=>{g("mongoose",t=>Bn(t,e))}});var Et={};A(Et,{instrumentPg:()=>Yn});var Vn,ce,Jn,Yn,Tt=w(()=>{"use strict";$();z();C();R();Vn=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},ce=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...a){let s=Vn(a),i=te(s)||"QUERY",u=b(`Postgres ${i}`,"db",{query:N(s,n),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":N(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 T(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}})})},Jn=(e,t)=>{e&&(ce(e.Client?.prototype,"client",t),ce(e.Pool?.prototype,"pool",t),e.default&&(ce(e.default.Client?.prototype,"default.client",t),ce(e.default.Pool?.prototype,"default.pool",t)))},Yn=e=>{g("pg",t=>Jn(t,e))}});var At={};A(At,{instrumentMysql:()=>nr});var Xn,Q,er,tr,xt,nr,zt=w(()=>{"use strict";$();z();C();R();Xn=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},Q=(e,t,n,r)=>{y(e,t,`senzor.${n}.${t}`,o=>function(...s){let i=Xn(s),u=te(i)||t.toUpperCase(),c=b(`MySQL ${u}`,"db",{query:N(i,r),operation:u,"db.system.name":"mysql","db.operation.name":u,"db.query.text":N(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 T(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}})})},er=(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=>{Q(r,"query",t,n),Q(r,"execute",t,n)})},tr=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,o=>function(...s){let i=o.apply(this,s);return Q(i,"query",t,n),Q(i,"execute",t,n),Q(Object.getPrototypeOf(i),"query",t,n),Q(Object.getPrototypeOf(i),"execute",t,n),i})})},xt=(e,t,n)=>{er(e,t,n),tr(e,t,n)},nr=e=>{g("mysql",t=>xt(t,"mysql",e)),g("mysql2",t=>xt(t,"mysql2",e))}});var Ct={};A(Ct,{instrumentRedis:()=>ir});var rr,W,or,sr,ar,ir,Rt=w(()=>{"use strict";z();C();R();rr=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",W=(e,t,n)=>{y(e,"sendCommand",`senzor.redis.${t}.sendCommand`,r=>function(a,...s){let i=rr(a),u=b(`Redis ${i}`,"db",{command:i,operation:i,"db.system.name":"redis","db.operation.name":i,library:t},n);return u?T(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)})},or=(e,t,n)=>(W(e,t,n),W(Object.getPrototypeOf(e),t,n),e),sr=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...a){let s=r.apply(this,a);return or(s,"redis",t)})})},ar=(e,t)=>{W(e?.prototype,"ioredis",t),W(e?.Redis?.prototype,"ioredis",t),W(e?.Cluster?.prototype,"ioredis-cluster",t),W(e?.default?.prototype,"ioredis",t)},ir=e=>{g("redis",t=>sr(t,e)),g("ioredis",t=>ar(t,e))}});var _t={};A(_t,{instrumentBullMQ:()=>cr});function Ot(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,o=r.processJob;typeof o!="function"||o[It]||(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,It,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var It,cr,Pt=w(()=>{"use strict";z();P();It=Symbol.for("senzor.bullmq.patched");cr=(e,t)=>{g("bullmq",n=>{Ot(n,e,t),n?.default&&Ot(n.default,e,t)})}});var Mt={};A(Mt,{instrumentNodeCron:()=>pr});function ur(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function Lt(e,t,n){let r=e.schedule;if(typeof r!="function"||r[Ft])return;let o=r,a=function(s,i,u){if(typeof i!="function")return o.call(this,s,i,u);try{let c=ur(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,Ft,{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 Ft,pr,qt=w(()=>{"use strict";z();Ft=Symbol.for("senzor.cron.patched");pr=(e,t)=>{g("node-cron",n=>{n&&(Lt(n,e,t),n.default&&Lt(n.default,e,t))})}});J();var Y=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,[O]:"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(){if(typeof process>"u"||typeof process.once!="function")return;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)}};P();var Ie=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",F=()=>Ie;var E=e=>{if(Ie)return process.env[e]};var de={name:"@senzops/apm-node",version:"1.2.6",description:"Universal APM SDK for Senzor",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",worker:"./dist/index.mjs",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",bun:">=1.0.0"},keywords:["apm","monitoring","senzor","node","javascript","api","observability","cloudflare-workers","edge","universal"],author:"Senzops",license:"MIT"};var fe={name:de.name,version:de.version};X();le();$();R();var dr=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})},Ae=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 Y({...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{if(this.isInstrumentationEnabled("fetch")){let{instrumentFetch:r}=(Se(),x(ge));r(t,this.options||void 0)}}catch{}if(F()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(Se(),x(ge));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(Xe(),x(Ye));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(st(),x(ot));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(pt(),x(ut));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(ft(),x(dt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(yt(),x(mt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(bt(),x(wt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(Tt(),x(Et));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(zt(),x(At));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(Rt(),x(Ct));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(Pt(),x(_t));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=(qt(),x(Mt));r(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(dr(d));i={...i,...q(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(!F()||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:fe.name,version:fe.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=Oe(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=Z(),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=F()&&process.memoryUsage?process.memoryUsage().heapUsed:0,u=F()&&process.cpuUsage?process.cpuUsage():void 0,c={id:ee(),contextType:"task",startTime:performance.now(),rootSpanId:Z(),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(F()&&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:q(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=b(t,n,{},this.options||void 0);return r?{end:(o,a)=>r.end(a,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},ze=new Ae;var Nt=e=>e==="1"||e==="true"||e==="yes",G=e=>{if(!e)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},vt=E("SENZOR_API_KEY")||E("SENZOR_APM_API_KEY")||E("SENZOR_SERVICE_API_KEY"),fr=E("SENZOR_ENDPOINT")||E("SENZOR_APM_ENDPOINT"),$t={apiKey:vt||"",endpoint:fr,debug:Nt(E("SENZOR_DEBUG")),autoLogs:E("SENZOR_AUTO_LOGS")==="false"?!1:void 0,batchSize:G(E("SENZOR_BATCH_SIZE")),flushInterval:G(E("SENZOR_FLUSH_INTERVAL")),flushTimeoutMs:G(E("SENZOR_FLUSH_TIMEOUT_MS")),maxQueueSize:G(E("SENZOR_MAX_QUEUE_SIZE")),maxSpansPerTrace:G(E("SENZOR_MAX_SPANS_PER_TRACE")),captureHeaders:Nt(E("SENZOR_CAPTURE_HEADERS")),captureDbStatement:E("SENZOR_CAPTURE_DB_STATEMENT")==="false"?!1:void 0,frameworkSpans:E("SENZOR_FRAMEWORK_SPANS")==="false"?!1:void 0,captureMiddlewareSpans:E("SENZOR_CAPTURE_MIDDLEWARE_SPANS")==="false"?!1:void 0,captureRouterSpans:E("SENZOR_CAPTURE_ROUTER_SPANS")==="false"?!1:void 0,captureLifecycleHookSpans:E("SENZOR_CAPTURE_LIFECYCLE_HOOK_SPANS")==="false"?!1:void 0};vt?ze.init($t):ze.preload($t);
|
|
2
2
|
//# sourceMappingURL=register.js.map
|