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