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