@senzops/apm-node 1.2.8 → 1.3.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +527 -398
  3. package/dist/index.d.mts +5 -0
  4. package/dist/index.d.ts +5 -0
  5. package/dist/index.global.js +1 -1
  6. package/dist/index.global.js.map +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/index.mjs +1 -1
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/lambda-handler.d.mts +13 -0
  12. package/dist/lambda-handler.d.ts +13 -0
  13. package/dist/lambda-handler.js +2 -0
  14. package/dist/lambda-handler.js.map +1 -0
  15. package/dist/lambda-handler.mjs +2 -0
  16. package/dist/lambda-handler.mjs.map +1 -0
  17. package/dist/register.js +1 -1
  18. package/dist/register.js.map +1 -1
  19. package/dist/register.mjs +1 -1
  20. package/dist/register.mjs.map +1 -1
  21. package/package.json +6 -1
  22. package/src/core/client.ts +57 -0
  23. package/src/core/transport.ts +20 -3
  24. package/src/core/types.ts +5 -1
  25. package/src/index.ts +4 -0
  26. package/src/instrumentation/amqplib.ts +371 -0
  27. package/src/instrumentation/anthropic.ts +245 -0
  28. package/src/instrumentation/aws-sdk.ts +403 -0
  29. package/src/instrumentation/azure-openai.ts +177 -0
  30. package/src/instrumentation/bunyan.ts +93 -0
  31. package/src/instrumentation/cassandra.ts +367 -0
  32. package/src/instrumentation/cohere.ts +227 -0
  33. package/src/instrumentation/connect.ts +200 -0
  34. package/src/instrumentation/dataloader.ts +291 -0
  35. package/src/instrumentation/dns.ts +220 -0
  36. package/src/instrumentation/firebase.ts +445 -0
  37. package/src/instrumentation/fs.ts +260 -0
  38. package/src/instrumentation/generic-pool.ts +317 -0
  39. package/src/instrumentation/google-genai.ts +426 -0
  40. package/src/instrumentation/graphql.ts +434 -0
  41. package/src/instrumentation/grpc.ts +666 -0
  42. package/src/instrumentation/hapi.ts +257 -0
  43. package/src/instrumentation/kafka.ts +360 -0
  44. package/src/instrumentation/knex.ts +249 -0
  45. package/src/instrumentation/lru-memoizer.ts +175 -0
  46. package/src/instrumentation/memcached.ts +190 -0
  47. package/src/instrumentation/mistral.ts +254 -0
  48. package/src/instrumentation/nestjs.ts +243 -0
  49. package/src/instrumentation/net.ts +171 -0
  50. package/src/instrumentation/openai.ts +281 -0
  51. package/src/instrumentation/pino.ts +170 -0
  52. package/src/instrumentation/restify.ts +213 -0
  53. package/src/instrumentation/runtime.ts +352 -0
  54. package/src/instrumentation/socketio.ts +272 -0
  55. package/src/instrumentation/tedious.ts +509 -0
  56. package/src/instrumentation/winston.ts +149 -0
  57. package/src/lambda-handler.ts +262 -0
  58. package/src/register.ts +22 -3
  59. package/src/wrappers/lambda.ts +417 -0
  60. package/tsup.config.ts +4 -4
  61. package/wiki.md +1693 -852
package/dist/register.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var de=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Wt=Object.prototype.hasOwnProperty;var z=(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)de(e,n,{get:t[n],enumerable:!0})},Kt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qt(t))!Wt.call(e,o)&&o!==n&&de(e,o,{get:()=>t[o],enumerable:!(r=jt(t,o))||r.enumerable});return e};var x=e=>Kt(de({},"__esModule",{value:!0}),e);var _,Y=w(()=>{"use strict";_="x-senzor-sdk-internal"});var ee,_e,fe,Z,S,F=w(()=>{"use strict";ee=class{run(t,n,...r){let o=this.store;this.store=t;let s;try{s=n(...r)}catch(a){throw this.store=o,a}return s!=null&&typeof s.then=="function"?s.then(i=>(this.store=o,i),i=>{throw this.store=o,i}):(this.store=o,s)}getStore(){return this.store}},_e=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof z<"u"){let e=z("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}try{if(typeof z<"u"){let e=z("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}return null},fe=class{constructor(){this.resolved=!1;this.inner=_e()||new ee,this.resolved=!(this.inner instanceof ee)}ensureResolved(){if(this.resolved)return;let t=_e();t&&(this.inner=t,this.resolved=!0)}run(t,n,...r){return this.ensureResolved(),this.inner.run(t,n,...r)}getStore(){return this.inner.getStore()}},Z=new fe,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 Bt,Fe,M,te=w(()=>{"use strict";Bt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Fe=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(Bt);if(!n)return null;let r=n[1],o=n[2],s=n[3];if(r==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:r,parentSpanId:o,sampled:a}},M=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var Le,ne,B,me=w(()=>{"use strict";Le=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof z<"u"){let{randomUUID:e}=z("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)})},ne=()=>Le().replace(/-/g,""),B=()=>Le().replace(/-/g,"").slice(0,16)});var Gt,ge,Vt,Jt,Yt,Xt,q,en,tn,ye,v,Me,N,re,$=w(()=>{"use strict";Gt=64,ge=2048,Vt=4,Jt=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,Xt=e=>({maxAttributes:e?.maxAttributes??Gt,maxAttributeLength:e?.maxAttributeLength??ge}),q=(e,t=ge)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,en=e=>Yt.test(e),tn=(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)},ye=(e,t,n,r)=>{if(en(e))return"[REDACTED]";let o=tn(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>=Vt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Jt).map(s=>ye(e,s,n,r+1));if(typeof t=="object"){let s={},a=0;for(let[i,u]of Object.entries(t)){if(a>=n.maxAttributes){s.__truncated=!0;break}s[i]=ye(i,u,n,r+1),a++}return s}return q(String(t),n.maxAttributeLength)},v=(e={},t)=>{let n=Xt(t),r={maxAttributes:n.maxAttributes,maxAttributeLength:n.maxAttributeLength},o={},s=0;for(let[a,i]of Object.entries(e)){if(s>=r.maxAttributes){o.__truncated=!0;break}o[a]=ye(a,i,r,0),s++}return o},Me=(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 v(n,t)},N=(e,t)=>{if(typeof e!="string")return;let n=e.replace(/\s+/g," ").trim();if(!n)return;let r=n.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return q(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??ge)},re=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var b,T,I=w(()=>{"use strict";F();$();me();b=(e,t,n={},r)=>{let o=S.current();if(!o)return null;let s=B(),a=o.activeSpanId,i=performance.now()-o.startTime,u=performance.now(),c=!1;return{spanId:s,parentSpanId:a,trace:o,end:(p,d={})=>{if(c)return;c=!0;let f=v({...n,...d,parentSpanId:a},r);S.addSpanToTrace(o,{spanId:s,parentSpanId:a,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,qe,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],qe=(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 nn,rn,ve,on,sn,an,P,Ne,cn,un,$e,He=w(()=>{"use strict";nn=/^(?:(?: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)$/,rn=/^(?:[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,ve=e=>nn.test(e)?4:rn.test(e)?6:0,on=e=>e.startsWith("::ffff:")?e.slice(7):e,sn=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return ve(n)===4?n:e},an=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},P=e=>{if(!e)return null;let t=e.trim();return t?(t=an(t),t=sn(t),t=on(t),ve(t)!==0?t:null):null},Ne=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")),cn=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&&!Ne(o))return o}}return null},un=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=P(n);if(r&&!Ne(r))return r}for(let n of t){let r=P(n);if(r)return r}return null},$e=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=cn(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=un(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=P(n);if(r)return r}return null}});var Ue,De,y,C=w(()=>{"use strict";Ue=Symbol.for("senzor.patch.keys"),De=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 s=o[Ue];if(s?.has(n))return!1;let a=o[De]||o,i=r(o),u=new Set(s||[]);u.add(n);try{Object.defineProperty(i,Ue,{value:u,enumerable:!1}),Object.defineProperty(i,De,{value:a,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}}});var ke={};A(ke,{instrumentFetch:()=>hn,instrumentHttp:()=>mn});var pn,je,dn,Ke,Ze,Se,H,fn,ln,Qe,We,hn,mn,we=w(()=>{"use strict";F();G();$();He();Y();te();C();I();pn=e=>!!e?.debug,je=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),dn=(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}}},Ke=e=>String(dn(e,_)||"").toLowerCase()==="true",Ze=(e,t,n)=>{if(Ke(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}},Se=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},fn=(e,t)=>{let n=[...e],r=0,o={},s=null;if(typeof n[0]=="string"||n[0]instanceof URL){try{s=new URL(n[0].toString())}catch{s=null}je(n[1])?(r=1,o={...n[1],headers:Se(n[1].headers)},n[1]=o):(r=1,o={headers:{}},n.splice(1,0,o))}else je(n[0])?(r=0,o={...n[0],headers:Se(n[0].headers)},n[0]=o):(r=0,o={headers:{}},n[0]=o);o.headers||(o.headers={}),n[r]=o;let a=o.protocol||s?.protocol||(o.port===443?"https:":t),i=o.hostname||o.host||s?.hostname||"localhost",u=o.path||`${s?.pathname||"/"}${s?.search||""}`,c=s?s.toString():`${a}//${i}${u}`,p=String(o.method||"GET").toUpperCase();return{args:n,options:o,url:c,method:p,hostname:String(i).replace(/:\d+$/,""),path:u}},ln=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return qe(e,n)}catch{return O(n)}},Qe=(e,t,n,r)=>{y(e,"emit",`senzor.${t}.server`,o=>function(a,...i){if(a!=="request")return o.call(this,a,...i);let u=i[0],c=i[1];if(!u||!c||S.current()?.contextType==="apm")return o.call(this,a,...i);let p=u.originalUrl||u.url||"/",d=String(p).split("?")[0]||"/",f=u.headers||{};return Ke(f)?o.call(this,a,...i):n.startTrace({method:u.method||"GET",path:p,route:O(d),ip:$e(u),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:u.httpVersion,headers:r?.captureHeaders?Me(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:ln(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,a,...i)}catch(k){throw n.captureError(k,{instrumentation:`${t}.server`}),h("error"),k}})})},We=(e,t,n,r)=>{let o=t==="https:"?"senzor.https":"senzor.http",s=a=>function(...u){let c=fn(u,t);if(Ze(c.url,n,c.options.headers))return a.apply(this,u);let p=S.current();if(!p)return a.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=a.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,Ie=()=>h(J,{"http.response.status_code":J});k.once("end",Ie),k.once("close",Ie),k.once("error",Oe=>h(500,{error:Oe.message,"error.type":Oe.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 pn(r)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),T(d,f)};y(e,"request",`${o}.request`,s),y(e,"get",`${o}.get`,s)},hn=(e,t)=>{globalThis.fetch&&y(globalThis,"fetch","senzor.fetch",n=>async function(o,s){let a=typeof o=="string"?o:o instanceof URL?o.toString():o?.url||"",i=s?.headers||o?.headers;if(Ze(a,e,i))return n.call(this,o,s);let u=S.current();if(!u)return n.call(this,o,s);let c="unknown",p="/";try{let h=new URL(a);c=h.hostname,p=`${h.pathname}${h.search}`}catch{}let d=String(s?.method||o?.method||"GET").toUpperCase(),f=b(`${d} ${c}`,"http",{url:a,method:d,library:"fetch","http.request.method":d,"url.full":a,"url.path":p,"server.address":c},t);if(!f)return n.call(this,o,s);let l={...s||{}},m=typeof Headers<"u"?new Headers(i||void 0):Se(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}})})},mn=(e,t,n)=>{let r,o;try{r=z("http")}catch{return}try{o=z("https")}catch{}r?.Server?.prototype&&Qe(r.Server.prototype,"http",e,n),o?.Server?.prototype&&Qe(o.Server.prototype,"https",e,n),We(r,"http:",t,n),o&&We(o,"https:",t,n)}});function yn(){let e=U;return e[oe]||Object.defineProperty(e,oe,{value:new Map,enumerable:!1}),e[oe]}function gn(e,t){let n=U[oe];if(!n)return t;let r=n.get(e);if(!r?.length)return t;let o=t;for(let s of r)try{let a=s(o);a!==void 0&&(o=a)}catch(a){console.error(`[Senzor] instrumentation failed for ${e}`,a)}return o}function Sn(){let e=U;if(e[Be])return;let t=e._load;e._load=function(r,o,s){let a=t.apply(this,arguments);return gn(r,a)},Object.defineProperty(e,Be,{value:!0,enumerable:!1})}function kn(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 wn(e,t){try{let n=D(e);n&&t(n)}catch{}}function bn(e,t){let n=0,r=5,o=setInterval(()=>{n++;try{let s=D(e);s&&(t(s),clearInterval(o))}catch{}n>=r&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var U,D,Be,oe,g,R=w(()=>{"use strict";try{U=z("module"),D=U.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}Be=Symbol.for("senzor.require.patched"),oe=Symbol.for("senzor.require.hooks");g=(e,t)=>{if(!U||!D)return;let n=yn();n.has(e)||n.set(e,[]),n.get(e).push(t),Sn(),kn(e,t),wn(e,t),bn(e,t)}});var En,Tn,j,xn,An,Rn,se,Q,ae=w(()=>{"use strict";F();I();En=new Set([void 0,null,"route","router"]),Tn=(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},xn=e=>!!(e&&typeof e.then=="function"),An=(e,t)=>e.parentSpanId?S.withActiveSpan(e.parentSpanId,t):t(),Rn=(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{}},se=(e,t,n,r,o,s={})=>{if(!Tn(r.type,o)||!S.current())return e.apply(t,n);let a=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(!a)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{}a.end(f,l)}},p=r.response;if(s.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=s.callbackIndex??n.findIndex(f=>typeof f=="function");if(s.callbackCompletesSpan!==!1&&d>=0&&typeof n[d]=="function"){let f=n[d];n[d]=function(...m){let h=m[0],k=!En.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}),An(a,()=>f.apply(this,m))}}return T(a,()=>{try{let f=e.apply(t,n);return xn(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&&s.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=(a,i)=>se(e,a,i,t(a,i),n,r),s;switch(e.length){case 4:s=function(i,u,c,p){return o(this,[i,u,c,p])};break;case 3:s=function(i,u,c){return o(this,[i,u,c])};break;case 2:s=function(i,u){return o(this,[i,u])};break;case 1:s=function(i){return o(this,[i])};break;default:s=function(){return o(this,Array.from(arguments))};break}return Rn(e,s),s}});var tt={};A(tt,{instrumentExpress:()=>On});var Ge,zn,Ee,be,Ve,Cn,Je,Ye,ie,In,Xe,et,On,nt=w(()=>{"use strict";G();R();C();ae();Ge=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"]),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)},be=e=>{for(let t of e){if(typeof t=="function")return;let n=Ee(t);if(n)return n}},Ve=(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?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"),Je=(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},Ye=(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{}},ie=(e,t,n,r)=>{!e||e[Ge]||typeof e.handle!="function"||(Object.defineProperty(e,Ge,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",o=>{let s=Cn(e,o,r),a=o.name||e.name||(s==="request_handler"?"handler":s);if(o.length===4){let u=function(p,d,f,l){let m=Ve(d,e,t);return se(o,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||a}`,route:m,method:Je(e,d),layerPath:t,handlerName:a,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 Ye(o,u),u}let i=function(c,p,d){let f=Ve(c,e,t),l=Je(e,c),m=f||t||a,h=s==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${s} ${m}`;return se(o,this,[c,p,d],{framework:"express",type:s,name:h,route:f,method:l,layerPath:t,handlerName:a,request:c,response:p,attributes:{"express.type":s,"express.layer.name":e.name,"http.route":f}},n,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Ye(o,i),i}))},In=(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(...a){let i=o.apply(this,a),u=this?.stack||[];for(let c of u)ie(c,t,n,"request_handler");return i})}},Xe=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},et=(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(...s){let a=r.apply(this,s),i=be(s),u=this?.stack||[],c=u[u.length-1];return ie(c,i,t,"router"),In(a,i,t),a}),y(n,"use","senzor.express.router.use",r=>function(...s){let a=this?.stack?.length||0,i=r.apply(this,s),u=this?.stack||[];for(let c=a;c<u.length;c++)ie(u[c],be(s),t);return i}),y(e.application,"use","senzor.express.application.use",r=>function(...s){let i=Xe(this)?.stack?.length||0,u=r.apply(this,s),p=Xe(this)?.stack||[];for(let d=i;d<p.length;d++)ie(p[d],be(s),t);return u})},On=e=>{g("express",t=>{et(t,e),t?.default&&et(t.default,e)})}});var it={};A(it,{instrumentFastify:()=>qn,instrumentFastifyInstance:()=>vn});var rt,ot,_n,Pn,xe,st,Fn,Ln,at,Mn,Te,qn,vn,ct=w(()=>{"use strict";R();C();ae();rt=Symbol.for("senzor.fastify.factory.patched"),ot=Symbol.for("senzor.fastify.instance.patched"),_n=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Pn=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],xe=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,st=(e,t,n,r)=>typeof t!="function"?t:Q(t,(o,s)=>{let a=s[0],i=s[1],u=xe(a,r);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${u||a?.url||""}`.trim(),route:u,method:a?.method,handlerName:t.name||e,request:a,response:i?.raw||i,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":u,url:a?.url}}},n,{callbackCompletesSpan:!0,responseEndsSpan:!1}),Fn=(e,t,n)=>typeof e!="function"?e:Q(e,(r,o)=>{let s=o[0],a=o[1],i=xe(s,n);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${s?.method||""} ${i||s?.url||""}`.trim(),route:i,method:s?.method,handlerName:e.name||"handler",request:s,response:a?.raw||a,attributes:{"fastify.type":"route_handler","http.route":i,url:s?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),Ln=(e,t)=>Array.isArray(e)?e.map(t):t(e),at=(e,t)=>(!e||e[ot]||(Object.defineProperty(e,ot,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(o,s){return _n.has(o)?n.call(this,o,st(o,s,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 s={...o},a=s.url||s.path||s.routePath;s.handler&&(s.handler=Fn(s.handler,t,a));for(let i of Pn)s[i]&&(s[i]=Ln(s[i],u=>st(i,u,t,a)));return n.call(this,s)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(o){return n.call(this,Q(o,(s,a)=>{let i=a[1],u=a[2],c=xe(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:a[0]?.message,"error.type":a[0]?.name||typeof a[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),Mn=(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[rt])return e;let n=function(...s){let a=e.apply(this,s);return at(a,t)};Mn(e,n),Object.defineProperty(n,rt,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},qn=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))},vn=(e,t)=>at(e,t)});var ft={};A(ft,{instrumentKoa:()=>Hn});var Nn,dt,ut,Ae,$n,pt,Hn,lt=w(()=>{"use strict";G();R();C();ae();Nn=["all","del","delete","get","head","options","patch","post","put"],dt=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(dt).filter(Boolean).join(",")},ut=e=>{for(let t of e){if(typeof t=="function")return;let n=dt(t);if(n)return n}},Ae=(e,t,n,r="middleware",o)=>typeof e!="function"?e:Q(e,(s,a)=>{let i=a[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(s){return r.call(this,Ae(s,t,void 0,"middleware"))})},pt=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",o=>function(...a){let i=ut(a),u=a.map(c=>typeof c=="function"?Ae(c,t,i,"router"):c);return o.apply(this,u)});for(let o of Nn)y(r,o,`senzor.koa.router.${o}`,s=>function(...i){let u=ut(i),c=i.map(p=>typeof p=="function"?Ae(p,t,u,"route_handler",o.toUpperCase()):p);return s.apply(this,c)})}},Hn=e=>{g("koa",t=>{$n(t,e)}),g("@koa/router",t=>{pt(t,e)}),g("koa-router",t=>{pt(t,e)})}});var ht={};A(ht,{instrumentUndici:()=>Qn});var Un,Re,Dn,ce,jn,Qn,mt=w(()=>{"use strict";G();Y();te();R();C();I();Un=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,Re=(e,t,n)=>{if(Array.isArray(e))return e.push([t,n]),e;let r={...e||{}},o=Object.keys(r).find(s=>s.toLowerCase()===t.toLowerCase());return r[o||t]=n,r},Dn=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:"/"}}},ce=(e,t,n,r)=>{y(e,t,n,o=>function(a,i,u){if(Un(i?.headers))return o.apply(this,arguments);let c=Dn(a?.origin?a.origin:a),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=Re(f.headers,"traceparent",M(d.trace.id,d.spanId)),f.headers=Re(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=Re(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,a,f,l);return m&&typeof m.then=="function"?m.then(h=>(d.end(h?.statusCode||h?.status||0,{"http.response.status_code":h?.statusCode||h?.status}),h),h=>{throw d.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}):(typeof l!="function"&&d.end(0),m)}catch(m){throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},jn=(e,t)=>{ce(e,"request","senzor.undici.request",t),ce(e,"stream","senzor.undici.stream",t),ce(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((n,r)=>{ce(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},Qn=e=>{g("undici",t=>jn(t,e))}});var St={};A(St,{instrumentMongo:()=>Gn});var Wn,yt,Kn,Zn,gt,Bn,Gn,kt=w(()=>{"use strict";R();C();I();Wn=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",yt=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,Kn=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Zn=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...s){let a=Wn(this),i=b(`MongoDB ${t}`,"db",{collection:a,operation:t,"db.system.name":"mongodb","db.collection.name":a,"db.namespace":yt(this)?`${yt(this)}.${a}`:a,"db.operation.name":t,library:"mongodb"},n);return i?T(i,()=>{try{let u=r.apply(this,s);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,s)})},gt=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,o=>function(...a){let i=Kn(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,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}}):o.apply(this,a)})},Bn=(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(a=>Zn(r,a,t));let o=e?.FindCursor||e?.default?.FindCursor,s=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(a=>gt(o?.prototype,a,"find",t)),["toArray","next","forEach"].forEach(a=>gt(s?.prototype,a,"aggregate",t))},Gn=e=>{g("mongodb",t=>Bn(t,e))}});var Tt={};A(Tt,{instrumentMongoose:()=>Jn});var bt,Et,ue,wt,Vn,Jn,xt=w(()=>{"use strict";R();C();I();bt=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",Et=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",ue=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...s){let a=String(this?.op||this?._op||t).toUpperCase(),i=Et(this),u=b(`Mongoose ${a}`,"db",{collection:i,model:bt(this),operation:a,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":a,library:"mongoose"},n);return u?T(u,()=>{try{let c=r.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}}):r.apply(this,s)})},wt=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...o){let s=Et(this),a=b("Mongoose SAVE","db",{collection:s,model:bt(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":s,"db.operation.name":"SAVE",library:"mongoose"},t);return a?T(a,()=>{try{let i=n.apply(this,o);return i&&typeof i.then=="function"?i.then(u=>(a.end(0),u),u=>{throw a.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(a.end(0),i)}catch(i){throw a.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):n.apply(this,o)})},Vn=(e,t)=>{ue(e?.Query?.prototype,"query",t),ue(e?.Aggregate?.prototype,"aggregate",t),wt(e?.Model?.prototype,t),e?.default&&(ue(e.default?.Query?.prototype,"query",t),ue(e.default?.Aggregate?.prototype,"aggregate",t),wt(e.default?.Model?.prototype,t))},Jn=e=>{g("mongoose",t=>Vn(t,e))}});var At={};A(At,{instrumentPg:()=>er});var Yn,pe,Xn,er,Rt=w(()=>{"use strict";$();R();C();I();Yn=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},pe=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...s){let a=Yn(s),i=re(a)||"QUERY",u=b(`Postgres ${i}`,"db",{query:N(a,n),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":N(a,n),library:"pg"},n);if(!u)return r.apply(this,s);let c=s.findIndex(p=>typeof p=="function");if(c>=0){let p=s[c];s[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,s);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}})})},Xn=(e,t)=>{e&&(pe(e.Client?.prototype,"client",t),pe(e.Pool?.prototype,"pool",t),e.default&&(pe(e.default.Client?.prototype,"default.client",t),pe(e.default.Pool?.prototype,"default.pool",t)))},er=e=>{g("pg",t=>Xn(t,e))}});var Ct={};A(Ct,{instrumentMysql:()=>or});var tr,W,nr,rr,zt,or,It=w(()=>{"use strict";$();R();C();I();tr=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(...a){let i=tr(a),u=re(i)||t.toUpperCase(),c=b(`MySQL ${u}`,"db",{query:N(i,r),operation:u,"db.system.name":"mysql","db.operation.name":u,"db.query.text":N(i,r),library:n},r);if(!c)return o.apply(this,a);let p=a.findIndex(d=>typeof d=="function");if(p>=0){let d=a[p];a[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,a);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return c.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw c.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(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}})})},nr=(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)})},rr=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,o=>function(...a){let i=o.apply(this,a);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})})},zt=(e,t,n)=>{nr(e,t,n),rr(e,t,n)},or=e=>{g("mysql",t=>zt(t,"mysql",e)),g("mysql2",t=>zt(t,"mysql2",e))}});var Ot={};A(Ot,{instrumentRedis:()=>ur});var sr,K,ar,ir,cr,ur,_t=w(()=>{"use strict";R();C();I();sr=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(s,...a){let i=sr(s),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,s,...a);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)})},ar=(e,t,n)=>(K(e,t,n),K(Object.getPrototypeOf(e),t,n),e),ir=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...s){let a=r.apply(this,s);return ar(a,"redis",t)})})},cr=(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)},ur=e=>{g("redis",t=>ir(t,e)),g("ioredis",t=>cr(t,e))}});var Lt={};A(Lt,{instrumentBullMQ:()=>pr});function Ft(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,o=r.processJob;typeof o!="function"||o[Pt]||(r.processJob=async function(s){let a=s.timestamp?Date.now()-s.timestamp:0,i=(s.attemptsMade||0)+1,u=s.opts?.attempts??1,c=i>=u,p=s.name==="__default__"?s.queueName:`${s.queueName}:${s.name}`;return t.startTask(p,"queue",{queueDelay:a,attempts:i,isDeadLetter:!1,metadata:{jobId:s.id,queueName:s.queueName,maxAttempts:u}},async()=>{try{let d=await o.call(this,s);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:s.queueName,jobId:s.id,isDeadLetter:c}),t.endTask("failed"),d}})},Object.defineProperty(r.processJob,Pt,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var Pt,pr,Mt=w(()=>{"use strict";R();F();Pt=Symbol.for("senzor.bullmq.patched");pr=(e,t)=>{g("bullmq",n=>{Ft(n,e,t),n?.default&&Ft(n.default,e,t)})}});var Nt={};A(Nt,{instrumentNodeCron:()=>fr});function dr(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function vt(e,t,n){let r=e.schedule;if(typeof r!="function"||r[qt])return;let o=r,s=function(a,i,u){if(typeof i!="function")return o.call(this,a,i,u);try{let c=dr(u),p=c?.name??`cron: ${a}`,d=t.wrapTask(p,"cron",{expression:a,metadata:c},i);return o.call(this,a,d,u)}catch(c){return n&&console.error("[Senzor] cron wrap failed",c),o.call(this,a,i,u)}};Object.defineProperty(s,qt,{value:!0,enumerable:!1});try{e.schedule=s}catch{n&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}n&&console.log("[Senzor] node-cron instrumented")}var qt,fr,$t=w(()=>{"use strict";R();qt=Symbol.for("senzor.cron.patched");fr=(e,t)=>{g("node-cron",n=>{n&&(vt(n,e,t),n.default&&vt(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.timerStarted=!1;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`}ensureTimer(){if(!this.timerStarted){this.timerStarted=!0;try{typeof setInterval<"u"&&(this.timer=setInterval(()=>{this.flush()},this.config.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}catch{}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){this.ensureTimer(),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 s=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(!s.ok)throw new Error(`Senzor ingest failed with status ${s.status}`)}finally{clearTimeout(o)}}async flush(){if(this.isFlushing){this.flushAgain=!0;return}this.isFlushing=!0;try{do{this.flushAgain=!1;let t=this.takeApmPayload(),n=this.takeTaskPayload(),r=[];if(this.hasApmPayload(t)&&r.push(this.postJson(this.apmEndpoint,t).catch(a=>{throw this.restoreApmPayload(t),a})),this.hasTaskPayload(n)&&r.push(this.postJson(this.taskEndpoint,n).catch(a=>{throw this.restoreTaskPayload(n),a})),!r.length)continue;let s=(await Promise.allSettled(r)).filter(a=>a.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=${s.length}, dropped=${this.droppedItems}`)}while(this.flushAgain)}catch(t){this.config.debug&&console.error("[Senzor] Transport Flush Error:",t)}finally{this.isFlushing=!1}}installShutdownFlush(){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 Pe=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",L=()=>Pe;var E=e=>{if(Pe)return process.env[e]};var le={name:"@senzops/apm-node",version:"1.2.8",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 he={name:le.name,version:le.version};te();me();$();I();var lr=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}=(we(),x(ke));r(t,this.options||void 0)}}catch{}if(L()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(we(),x(ke));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(nt(),x(tt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(ct(),x(it));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(lt(),x(ft));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(mt(),x(ht));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(kt(),x(St));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(xt(),x(Tt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(Rt(),x(At));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(It(),x(Ct));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(_t(),x(Ot));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(Mt(),x(Lt));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=($t(),x(Nt));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]=(...s)=>{if(n[o].apply(console,s),!(r||!this.transport)){r=!0;try{let a="",i={};s.forEach(d=>{if(typeof d=="string")a+=(a?" ":"")+d;else if(d instanceof Error)a+=(a?" ":"")+d.message,i.errorStack=d.stack,i.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(lr(d));i={...i,...v(f,this.options||void 0)}}catch{i.unparseableObject=!0}else a+=(a?" ":"")+String(d)}),!a&&Object.keys(i).length>0&&(a="Object Log");let u=S.current(),c=u?.contextType==="task"?"task":"apm",p={message:a||"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,s={})=>{try{let a;if(o instanceof Error)a=o;else if(typeof o=="string")a=new Error(o);else try{a=new Error(JSON.stringify(o))}catch{a=new Error("Non-serializable rejection reason")}let i={...s,runtime:{name:"node",version:process.version},process:t(),memory:n(),sdk:{name:he.name,version:he.version}};this.captureError(a,i)}catch(a){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",a)}catch{}}};process.on("uncaughtExceptionMonitor",o=>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,s,a)=>r(a||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:o,severity:"warning"})),process.on("rejectionHandled",o=>{if(this.options?.debug)try{console.warn("[Senzor] rejectionHandled event detected")}catch{}}),process.on("SIGTERM",()=>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,s;if(t.headers){let c=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},p=c("traceparent"),d=Fe(p);if(d)o=d.traceId,s=d.parentSpanId;else{let f=c("x-senzor-trace-id"),l=c("x-senzor-parent-span-id");o=Array.isArray(f)?f[0]:f,s=Array.isArray(l)?l[0]:l}}let a=o||ne(),i=B(),u={id:a,contextType:"apm",startTime:performance.now(),rootSpanId:i,activeSpanId:i,data:{...t,parentTraceId:o,parentSpanId:s,rootSpanId:i},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return 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,s={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(s)}startTask(t,n,r,o){if(!this.transport)return o();let s=S.current(),a=s?.contextType==="apm"?s.id:void 0,i=L()&&process.memoryUsage?process.memoryUsage().heapUsed:0,u=L()&&process.cpuUsage?process.cpuUsage():void 0,c={id:ne(),contextType:"task",startTime:performance.now(),rootSpanId:B(),startMemory:i,startCpu:u,data:{taskName:t,taskType:n,triggerTraceId:a,...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 a=process.memoryUsage().heapUsed,i=process.cpuUsage(r.startCpu);o={memoryDeltaBytes:a-r.startMemory,cpuUserUs:i.user,cpuSystemUs:i.system}}let s={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(s)}wrapTask(t,n,r={},o){return(async(...s)=>this.startTask(t,n,r,async()=>{try{let a=await o(...s);return this.endTask("success"),a}catch(a){throw this.captureError(a,{taskName:t}),this.endTask("failed"),a}}))}captureError(t,n={}){if(!this.transport)return;let r;t instanceof Error?r=t:r=new Error(String(t));let o=S.current(),s={errorClass:r.name||"Error",message:r.message,stackTrace:r.stack,context:v(n,this.options||void 0),timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...s,runId:o.id},"task"):this.transport.addError({...s,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:ne(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=b(t,n,{},this.options||void 0);return r?{end:(o,s)=>r.end(s,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},Ce=new ze;var Ht=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},Dt=E("SENZOR_API_KEY")||E("SENZOR_APM_API_KEY")||E("SENZOR_SERVICE_API_KEY"),hr=E("SENZOR_ENDPOINT")||E("SENZOR_APM_ENDPOINT"),Ut={apiKey:Dt||"",endpoint:hr,debug:Ht(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:Ht(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};Dt?Ce.init(Ut):Ce.preload(Ut);
1
+ var Be=Object.defineProperty;var xo=Object.getOwnPropertyDescriptor;var Oo=Object.getOwnPropertyNames;var Mo=Object.prototype.hasOwnProperty;var M=(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 _=(e,t)=>()=>(e&&(t=e(e=0)),t);var R=(e,t)=>{for(var n in t)Be(e,n,{get:t[n],enumerable:!0})},Io=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Oo(t))!Mo.call(e,s)&&s!==n&&Be(e,s,{get:()=>t[s],enumerable:!(r=xo(t,s))||r.enumerable});return e};var z=e=>Io(Be({},"__esModule",{value:!0}),e);var K,Ce=_(()=>{"use strict";K="x-senzor-sdk-internal"});var we,bt,We,le,E,N=_(()=>{"use strict";we=class{run(t,n,...r){let s=this.store;this.store=t;let i;try{i=n(...r)}catch(o){throw this.store=s,o}return i!=null&&typeof i.then=="function"?i.then(a=>(this.store=s,a),a=>{throw this.store=s,a}):(this.store=s,i)}getStore(){return this.store}},bt=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof M<"u"){let e=M("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}try{if(typeof M<"u"){let e=M("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}return null},We=class{constructor(){this.resolved=!1;this.inner=bt()||new we,this.resolved=!(this.inner instanceof we)}ensureResolved(){if(this.resolved)return;let t=bt();t&&(this.inner=t,this.resolved=!0)}run(t,n,...r){return this.ensureResolved(),this.inner.run(t,n,...r)}getStore(){return this.inner.getStore()}},le=new We,E={run:(e,t)=>le.run(e,t),withActiveSpan:(e,t)=>{let n=le.getStore();return n?le.run({...n,activeSpanId:e,data:n.data,spans:n.spans},t):t()},current:()=>le.getStore(),addSpan:e=>{let t=le.getStore();t&&E.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 Po,j,L,G=_(()=>{"use strict";Po=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,j=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(Po);if(!n)return null;let r=n[1],s=n[2],i=n[3];if(r==="00000000000000000000000000000000"||s==="0000000000000000")return null;let o=(parseInt(i,16)&1)===1;return{traceId:r,parentSpanId:s,sampled:o}},L=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var Ct,Ee,he,Ke=_(()=>{"use strict";Ct=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof M<"u"){let{randomUUID:e}=M("crypto");if(e)return e()}}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},Ee=()=>Ct().replace(/-/g,""),he=()=>Ct().replace(/-/g,"").slice(0,16)});var qo,Ze,No,$o,Lo,Uo,Y,Fo,Do,Ge,J,_t,v,q,H=_(()=>{"use strict";qo=64,Ze=2048,No=4,$o=20,Lo=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Uo=e=>({maxAttributes:e?.maxAttributes??qo,maxAttributeLength:e?.maxAttributeLength??Ze}),Y=(e,t=Ze)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Fo=e=>Lo.test(e),Do=(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 Y(e,t)},Ge=(e,t,n,r)=>{if(Fo(e))return"[REDACTED]";let s=Do(t,n.maxAttributeLength);if(s!==void 0||t===void 0)return s;if(t instanceof Error)return{name:Y(t.name,n.maxAttributeLength),message:Y(t.message,n.maxAttributeLength),stack:t.stack?Y(t.stack,n.maxAttributeLength):void 0};if(r>=No)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,$o).map(i=>Ge(e,i,n,r+1));if(typeof t=="object"){let i={},o=0;for(let[a,c]of Object.entries(t)){if(o>=n.maxAttributes){i.__truncated=!0;break}i[a]=Ge(a,c,n,r+1),o++}return i}return Y(String(t),n.maxAttributeLength)},J=(e={},t)=>{let n=Uo(t),r={maxAttributes:n.maxAttributes,maxAttributeLength:n.maxAttributeLength},s={},i=0;for(let[o,a]of Object.entries(e)){if(i>=r.maxAttributes){s.__truncated=!0;break}s[o]=Ge(o,a,r,0),i++}return s},_t=(e,t)=>{if(!e||typeof e!="object")return{};let n={};if(typeof e.forEach=="function")e.forEach((r,s)=>{n[s.toLowerCase()]=r});else for(let[r,s]of Object.entries(e))n[r.toLowerCase()]=Array.isArray(s)?s.join(", "):s;return J(n,t)},v=(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 Y(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??Ze)},q=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var S,b,x=_(()=>{"use strict";N();H();Ke();S=(e,t,n={},r)=>{let s=E.current();if(!s)return null;let i=he(),o=s.activeSpanId,a=performance.now()-s.startTime,c=performance.now(),p=!1;return{spanId:i,parentSpanId:o,trace:s,end:(u,d={})=>{if(p)return;p=!0;let f=J({...n,...d,parentSpanId:o},r);E.addSpanToTrace(s,{spanId:i,parentSpanId:o,name:e,type:t,startTime:a,duration:performance.now()-c,status:u,meta:f})}}},b=(e,t)=>e?E.withActiveSpan(e.spanId,t):t()});var F,wt,me=_(()=>{"use strict";F=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],wt=(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:F(t)});var Bo,Wo,Et,jo,Qo,Ko,Z,zt,Go,Zo,Rt,At=_(()=>{"use strict";Bo=/^(?:(?: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)$/,Wo=/^(?:[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,Et=e=>Bo.test(e)?4:Wo.test(e)?6:0,jo=e=>e.startsWith("::ffff:")?e.slice(7):e,Qo=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return Et(n)===4?n:e},Ko=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},Z=e=>{if(!e)return null;let t=e.trim();return t?(t=Ko(t),t=Qo(t),t=jo(t),Et(t)!==0?t:null):null},zt=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")),Go=e=>{let t=e.split(",");for(let n of t){let r=n.match(/for=["[]?([^\]",;>\s]+)/i);if(r){let s=Z(r[1]);if(s&&!zt(s))return s}}return null},Zo=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=Z(n);if(r&&!zt(r))return r}for(let n of t){let r=Z(n);if(r)return r}return null},Rt=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=Go(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=Zo(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=Z(n);if(r)return r}return null}});var Tt,xt,y,A=_(()=>{"use strict";Tt=Symbol.for("senzor.patch.keys"),xt=Symbol.for("senzor.patch.original"),y=(e,t,n,r)=>{if(!e)return!1;let s=e[t];if(typeof s!="function")return!1;let i=s[Tt];if(i?.has(n))return!1;let o=s[xt]||s,a=r(s),c=new Set(i||[]);c.add(n);try{Object.defineProperty(a,Tt,{value:c,enumerable:!1}),Object.defineProperty(a,xt,{value:o,enumerable:!1})}catch{return!1}try{return e[t]=a,!0}catch{return!1}}});var et={};R(et,{instrumentFetch:()=>es,instrumentHttp:()=>ts});var Vo,Ot,Yo,vt,Pt,Xe,X,Jo,Xo,Mt,It,es,ts,tt=_(()=>{"use strict";N();me();H();At();Ce();G();A();x();Vo=e=>!!e?.debug,Ot=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),Yo=(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,s]of Object.entries(e))if(r.toLowerCase()===n)return s}}},vt=e=>String(Yo(e,K)||"").toLowerCase()==="true",Pt=(e,t,n)=>{if(vt(n))return!0;if(!e)return!1;try{let r=new URL(e),s=new URL(t);return r.hostname===s.hostname&&r.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},Xe=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}:{}},X=(e,t,n)=>{let r=Object.keys(e).find(s=>s.toLowerCase()===t.toLowerCase());e[r||t]=n},Jo=(e,t)=>{let n=[...e],r=0,s={},i=null;if(typeof n[0]=="string"||n[0]instanceof URL){try{i=new URL(n[0].toString())}catch{i=null}Ot(n[1])?(r=1,s={...n[1],headers:Xe(n[1].headers)},n[1]=s):(r=1,s={headers:{}},n.splice(1,0,s))}else Ot(n[0])?(r=0,s={...n[0],headers:Xe(n[0].headers)},n[0]=s):(r=0,s={headers:{}},n[0]=s);s.headers||(s.headers={}),n[r]=s;let o=s.protocol||i?.protocol||(s.port===443?"https:":t),a=s.hostname||s.host||i?.hostname||"localhost",c=s.path||`${i?.pathname||"/"}${i?.search||""}`,p=i?i.toString():`${o}//${a}${c}`,u=String(s.method||"GET").toUpperCase();return{args:n,options:s,url:p,method:u,hostname:String(a).replace(/:\d+$/,""),path:c}},Xo=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return wt(e,n)}catch{return F(n)}},Mt=(e,t,n,r)=>{y(e,"emit",`senzor.${t}.server`,s=>function(o,...a){if(o!=="request")return s.call(this,o,...a);let c=a[0],p=a[1];if(!c||!p||E.current()?.contextType==="apm")return s.call(this,o,...a);let u=c.originalUrl||c.url||"/",d=String(u).split("?")[0]||"/",f=c.headers||{};return vt(f)?s.call(this,o,...a):n.startTrace({method:c.method||"GET",path:u,route:F(d),ip:Rt(c),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:c.httpVersion,headers:r?.captureHeaders?_t(f,r):void 0}},()=>{let l=E.current(),h=!1,m=g=>{h||!l||(h=!0,setImmediate(()=>{l.state.ended||E.run(l,()=>{n.endTrace(p.statusCode||0,{route:Xo(c,p,d),statusMessage:p.statusMessage,meta:{...l.data.meta,endReason:g}})})}))};p.once("finish",()=>m("finish")),p.once("close",()=>m("close")),p.once("error",g=>{n.captureError(g,{instrumentation:`${t}.server`}),m("error")});try{return s.call(this,o,...a)}catch(g){throw n.captureError(g,{instrumentation:`${t}.server`}),m("error"),g}})})},It=(e,t,n,r)=>{let s=t==="https:"?"senzor.https":"senzor.http",i=o=>function(...c){let p=Jo(c,t);if(Pt(p.url,n,p.options.headers))return o.apply(this,c);let u=E.current();if(!u)return o.apply(this,c);let d=S(`${p.method} ${p.hostname}`,"http",{url:p.url,method:p.method,library:t==="https:"?"https":"http","http.request.method":p.method,"url.full":p.url,"url.path":p.path,"server.address":p.hostname},r);d&&(X(p.options.headers,"traceparent",L(u.id,d.spanId)),X(p.options.headers,"x-senzor-trace-id",u.id),X(p.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=o.apply(this,p.args);if(!d||!l||typeof l.once!="function")return l;let h=!1,m=(g,C={})=>{h||(h=!0,d.end(g,C))};return l.once("response",g=>{let C=g?.statusCode||0,w=()=>m(C,{"http.response.status_code":C});g.once("end",w),g.once("close",w),g.once("error",O=>m(500,{error:O.message,"error.type":O.name}))}),l.once("timeout",()=>m(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",g=>m(500,{error:g.message,"error.type":g.name})),l};return Vo(r)&&console.log(`[Senzor] Injecting trace headers to ${p.url}`),b(d,f)};y(e,"request",`${s}.request`,i),y(e,"get",`${s}.get`,i)},es=(e,t)=>{globalThis.fetch&&y(globalThis,"fetch","senzor.fetch",n=>async function(s,i){let o=typeof s=="string"?s:s instanceof URL?s.toString():s?.url||"",a=i?.headers||s?.headers;if(Pt(o,e,a))return n.call(this,s,i);let c=E.current();if(!c)return n.call(this,s,i);let p="unknown",u="/";try{let m=new URL(o);p=m.hostname,u=`${m.pathname}${m.search}`}catch{}let d=String(i?.method||s?.method||"GET").toUpperCase(),f=S(`${d} ${p}`,"http",{url:o,method:d,library:"fetch","http.request.method":d,"url.full":o,"url.path":u,"server.address":p},t);if(!f)return n.call(this,s,i);let l={...i||{}},h=typeof Headers<"u"?new Headers(a||void 0):Xe(a);return typeof Headers<"u"&&h instanceof Headers?(h.set("traceparent",L(c.id,f.spanId)),h.set("x-senzor-trace-id",c.id),h.set("x-senzor-parent-span-id",f.spanId)):(X(h,"traceparent",L(c.id,f.spanId)),X(h,"x-senzor-trace-id",c.id),X(h,"x-senzor-parent-span-id",f.spanId)),l.headers=h,b(f,async()=>{try{let m=await n.call(this,s,l);return f.end(m.status,{"http.response.status_code":m.status}),m}catch(m){throw f.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},ts=(e,t,n)=>{let r,s;try{r=M("http")}catch{return}try{s=M("https")}catch{}r?.Server?.prototype&&Mt(r.Server.prototype,"http",e,n),s?.Server?.prototype&&Mt(s.Server.prototype,"https",e,n),It(r,"http:",t,n),s&&It(s,"https:",t,n)}});function ns(){let e=ee;return e[Re]||Object.defineProperty(e,Re,{value:new Map,enumerable:!1}),e[Re]}function rs(e,t){let n=ee[Re];if(!n)return t;let r=n.get(e);if(!r?.length)return t;let s=t;for(let i of r)try{let o=i(s);o!==void 0&&(s=o)}catch(o){console.error(`[Senzor] instrumentation failed for ${e}`,o)}return s}function os(){let e=ee;if(e[qt])return;let t=e._load;e._load=function(r,s,i){let o=t.apply(this,arguments);return rs(r,o)},Object.defineProperty(e,qt,{value:!0,enumerable:!1})}function ss(e,t){try{let n=te.resolve(e),r=te.cache?.[n];if(r?.exports){let s=t(r.exports);s!==void 0&&(r.exports=s)}}catch{}}function as(e,t){try{let n=te(e);n&&t(n)}catch{}}function is(e,t){let n=0,r=5,s=setInterval(()=>{n++;try{let i=te(e);i&&(t(i),clearInterval(s))}catch{}n>=r&&clearInterval(s)},200);typeof s.unref=="function"&&s.unref()}var ee,te,qt,Re,k,T=_(()=>{"use strict";try{ee=M("module"),te=ee.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}qt=Symbol.for("senzor.require.patched"),Re=Symbol.for("senzor.require.hooks");k=(e,t)=>{if(!ee||!te)return;let n=ns();n.has(e)||n.set(e,[]),n.get(e).push(t),os(),ss(e,t),as(e,t),is(e,t)}});var cs,us,ne,ps,ds,fs,Ae,re,Te=_(()=>{"use strict";N();x();cs=new Set([void 0,null,"route","router"]),us=(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)),ne=(e,t=0)=>{let n=e.response;return n?.statusCode||n?.status||n?.raw?.statusCode||n?.status_code||t},ps=e=>!!(e&&typeof e.then=="function"),ds=(e,t)=>e.parentSpanId?E.withActiveSpan(e.parentSpanId,t):t(),fs=(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{}},Ae=(e,t,n,r,s,i={})=>{if(!us(r.type,s)||!E.current())return e.apply(t,n);let o=S(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},s);if(!o)return e.apply(t,n);let a=!1,c=[],p=(f=ne(r),l={})=>{if(!a){a=!0;for(let h of c)try{h()}catch{}o.end(f,l)}},u=r.response;if(i.responseEndsSpan!==!1&&u?.once){let f=()=>p(ne(r),{completion:"response.finish"}),l=()=>p(ne(r),{completion:"response.close"});u.once("finish",f),u.once("close",l),c.push(()=>{try{u.removeListener?.("finish",f)}catch{}try{u.removeListener?.("close",l)}catch{}})}let d=i.callbackIndex??n.findIndex(f=>typeof f=="function");if(i.callbackCompletesSpan!==!1&&d>=0&&typeof n[d]=="function"){let f=n[d];n[d]=function(...h){let m=h[0],g=!cs.has(m);return p(g?500:ne(r),{completion:"callback",error:g?String(m?.message||m):void 0,"error.type":g?m?.name||typeof m:void 0}),ds(o,()=>f.apply(this,h))}}return b(o,()=>{try{let f=e.apply(t,n);return ps(f)?f.then(l=>(p(ne(r),{completion:"promise.resolve"}),l),l=>{throw p(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&i.responseEndsSpan===!1&&p(ne(r),{completion:"sync.return"}),f)}catch(f){throw p(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},re=(e,t,n,r={})=>{if(typeof e!="function")return e;let s=(o,a)=>Ae(e,o,a,t(o,a),n,r),i;switch(e.length){case 4:i=function(a,c,p,u){return s(this,[a,c,p,u])};break;case 3:i=function(a,c,p){return s(this,[a,c,p])};break;case 2:i=function(a,c){return s(this,[a,c])};break;case 1:i=function(a){return s(this,[a])};break;default:i=function(){return s(this,Array.from(arguments))};break}return fs(e,i),i}});var Ht={};R(Ht,{instrumentExpress:()=>ys});var Nt,ls,rt,nt,$t,hs,Lt,Ut,xe,ms,Ft,Dt,ys,Bt=_(()=>{"use strict";me();T();A();Te();Nt=Symbol.for("senzor.express.layer.patched"),ls=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"]),rt=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(rt).filter(Boolean).join(",");if(typeof e=="number")return String(e)},nt=e=>{for(let t of e){if(typeof t=="function")return;let n=rt(t);if(n)return n}},$t=(e,t,n)=>{if(t?.route?.path){let s=rt(t.route.path);return`${e?.baseUrl||""}${s}`||s}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(n){let s=e?.baseUrl||"";return s===n||s.endsWith(n)?s:`${s}${n}`||n}let r=e?.originalUrl||e?.url||e?.path;return r?F(String(r).split("?")[0]):void 0},hs=(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"),Lt=(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},Ut=(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{}},xe=(e,t,n,r)=>{!e||e[Nt]||typeof e.handle!="function"||(Object.defineProperty(e,Nt,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",s=>{let i=hs(e,s,r),o=s.name||e.name||(i==="request_handler"?"handler":i);if(s.length===4){let c=function(u,d,f,l){let h=$t(d,e,t);return Ae(s,this,[u,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${h||o}`,route:h,method:Lt(e,d),layerPath:t,handlerName:o,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 Ut(s,c),c}let a=function(p,u,d){let f=$t(p,e,t),l=Lt(e,p),h=f||t||o,m=i==="request_handler"?`express.request_handler ${l||""} ${h}`.trim():`express.${i} ${h}`;return Ae(s,this,[p,u,d],{framework:"express",type:i,name:m,route:f,method:l,layerPath:t,handlerName:o,request:p,response:u,attributes:{"express.type":i,"express.layer.name":e.name,"http.route":f}},n,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Ut(s,a),a}))},ms=(e,t,n)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let r of ls)typeof e[r]=="function"&&y(e,r,`senzor.express.route.${r}`,s=>function(...o){let a=s.apply(this,o),c=this?.stack||[];for(let p of c)xe(p,t,n,"request_handler");return a})}},Ft=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Dt=(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(...i){let o=r.apply(this,i),a=nt(i),c=this?.stack||[],p=c[c.length-1];return xe(p,a,t,"router"),ms(o,a,t),o}),y(n,"use","senzor.express.router.use",r=>function(...i){let o=this?.stack?.length||0,a=r.apply(this,i),c=this?.stack||[];for(let p=o;p<c.length;p++)xe(c[p],nt(i),t);return a}),y(e.application,"use","senzor.express.application.use",r=>function(...i){let a=Ft(this)?.stack?.length||0,c=r.apply(this,i),u=Ft(this)?.stack||[];for(let d=a;d<u.length;d++)xe(u[d],nt(i),t);return c})},ys=e=>{k("express",t=>{Dt(t,e),t?.default&&Dt(t.default,e)})}});var Gt={};R(Gt,{instrumentFastify:()=>_s,instrumentFastifyInstance:()=>ws});var Wt,jt,gs,Ss,st,Qt,bs,ks,Kt,Cs,ot,_s,ws,Zt=_(()=>{"use strict";T();A();Te();Wt=Symbol.for("senzor.fastify.factory.patched"),jt=Symbol.for("senzor.fastify.instance.patched"),gs=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Ss=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],st=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,Qt=(e,t,n,r)=>typeof t!="function"?t:re(t,(s,i)=>{let o=i[0],a=i[1],c=st(o,r);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${c||o?.url||""}`.trim(),route:c,method:o?.method,handlerName:t.name||e,request:o,response:a?.raw||a,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":c,url:o?.url}}},n,{callbackCompletesSpan:!0,responseEndsSpan:!1}),bs=(e,t,n)=>typeof e!="function"?e:re(e,(r,s)=>{let i=s[0],o=s[1],a=st(i,n);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${i?.method||""} ${a||i?.url||""}`.trim(),route:a,method:i?.method,handlerName:e.name||"handler",request:i,response:o?.raw||o,attributes:{"fastify.type":"route_handler","http.route":a,url:i?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),ks=(e,t)=>Array.isArray(e)?e.map(t):t(e),Kt=(e,t)=>(!e||e[jt]||(Object.defineProperty(e,jt,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(s,i){return gs.has(s)?n.call(this,s,Qt(s,i,t)):n.apply(this,arguments)}),y(e,"route","senzor.fastify.route",n=>function(s){if(!s||typeof s!="object")return n.apply(this,arguments);let i={...s},o=i.url||i.path||i.routePath;i.handler&&(i.handler=bs(i.handler,t,o));for(let a of Ss)i[a]&&(i[a]=ks(i[a],c=>Qt(a,c,t,o)));return n.call(this,i)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(s){return n.call(this,re(s,(i,o)=>{let a=o[1],c=o[2],p=st(a);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${p||a?.url||""}`.trim(),route:p,method:a?.method,handlerName:s?.name||"errorHandler",request:a,response:c?.raw||c,attributes:{"fastify.type":"error_handler",error:o[0]?.message,"error.type":o[0]?.name||typeof o[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),Cs=(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{}},ot=(e,t)=>{if(typeof e!="function"||e[Wt])return e;let n=function(...i){let o=e.apply(this,i);return Kt(o,t)};Cs(e,n),Object.defineProperty(n,Wt,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},_s=e=>{k("fastify",t=>typeof t=="function"?ot(t,e):(t?.fastify&&(t.fastify=ot(t.fastify,e)),t?.default&&(t.default=ot(t.default,e)),t))},ws=(e,t)=>Kt(e,t)});var Xt={};R(Xt,{instrumentKoa:()=>Rs});var Es,Jt,Vt,at,zs,Yt,Rs,en=_(()=>{"use strict";me();T();A();Te();Es=["all","del","delete","get","head","options","patch","post","put"],Jt=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(Jt).filter(Boolean).join(",")},Vt=e=>{for(let t of e){if(typeof t=="function")return;let n=Jt(t);if(n)return n}},at=(e,t,n,r="middleware",s)=>typeof e!="function"?e:re(e,(i,o)=>{let a=o[0],c=a?._matchedRoute||a?.matched?.[0]?.path||n||F(a?.path||a?.request?.path||"/"),p=s||a?.method||a?.request?.method,u=e.name||r;return{framework:"koa",type:r,name:r==="route_handler"?`koa.request_handler ${p||""} ${c}`.trim():`koa.${r} ${c||u}`,route:c,method:p,layerPath:n,handlerName:u,request:a?.req||a?.request,response:a?.res||a?.response,attributes:{"koa.type":r,"http.route":c,path:a?.path||a?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),zs=(e,t)=>{let n=e?.prototype||e?.default?.prototype;n&&y(n,"use","senzor.koa.application.use",r=>function(i){return r.call(this,at(i,t,void 0,"middleware"))})},Yt=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",s=>function(...o){let a=Vt(o),c=o.map(p=>typeof p=="function"?at(p,t,a,"router"):p);return s.apply(this,c)});for(let s of Es)y(r,s,`senzor.koa.router.${s}`,i=>function(...a){let c=Vt(a),p=a.map(u=>typeof u=="function"?at(u,t,c,"route_handler",s.toUpperCase()):u);return i.apply(this,p)})}},Rs=e=>{k("koa",t=>{zs(t,e)}),k("@koa/router",t=>{Yt(t,e)}),k("koa-router",t=>{Yt(t,e)})}});var tn={};R(tn,{instrumentUndici:()=>Os});var As,it,Ts,Oe,xs,Os,nn=_(()=>{"use strict";me();Ce();G();T();A();x();As=e=>e?Array.isArray(e)?e.some(([t,n])=>String(t).toLowerCase()===K&&String(n).toLowerCase()==="true"):Object.entries(e).some(([t,n])=>t.toLowerCase()===K&&String(n).toLowerCase()==="true"):!1,it=(e,t,n)=>{if(Array.isArray(e))return e.push([t,n]),e;let r={...e||{}},s=Object.keys(r).find(i=>i.toLowerCase()===t.toLowerCase());return r[s||t]=n,r},Ts=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:"/"}}},Oe=(e,t,n,r)=>{y(e,t,n,s=>function(o,a,c){if(As(a?.headers))return s.apply(this,arguments);let p=Ts(o?.origin?o.origin:o),u=String(a?.method||"GET").toUpperCase(),d=S(`${u} ${p.hostname}`,"http",{url:p.url,method:u,route:F(p.path),library:"undici","http.request.method":u,"url.full":p.url,"url.path":p.path,"server.address":p.hostname},r);if(!d)return s.apply(this,arguments);let f={...a||{}};f.headers=it(f.headers,"traceparent",L(d.trace.id,d.spanId)),f.headers=it(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=it(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof c=="function"?function(m,g){return d.end(m?500:g?.statusCode||0,{error:m?.message,"error.type":m?.name,"http.response.status_code":g?.statusCode}),c.apply(this,arguments)}:c;return b(d,()=>{try{let h=s.call(this,o,f,l);return h&&typeof h.then=="function"?h.then(m=>(d.end(m?.statusCode||m?.status||0,{"http.response.status_code":m?.statusCode||m?.status}),m),m=>{throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}):(typeof l!="function"&&d.end(0),h)}catch(h){throw d.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}})})},xs=(e,t)=>{Oe(e,"request","senzor.undici.request",t),Oe(e,"stream","senzor.undici.stream",t),Oe(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((n,r)=>{Oe(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},Os=e=>{k("undici",t=>xs(t,e))}});var sn={};R(sn,{instrumentMongo:()=>qs});var Ms,rn,Is,vs,on,Ps,qs,an=_(()=>{"use strict";T();A();x();Ms=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",rn=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,Is=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",vs=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...i){let o=Ms(this),a=S(`MongoDB ${t}`,"db",{collection:o,operation:t,"db.system.name":"mongodb","db.collection.name":o,"db.namespace":rn(this)?`${rn(this)}.${o}`:o,"db.operation.name":t,library:"mongodb"},n);return a?b(a,()=>{try{let c=r.apply(this,i);return c&&typeof c.then=="function"?c.then(p=>(a.end(0,{matchedCount:p?.matchedCount,modifiedCount:p?.modifiedCount,deletedCount:p?.deletedCount,insertedCount:p?.insertedCount}),p),p=>{throw a.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(a.end(0),c)}catch(c){throw a.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):r.apply(this,i)})},on=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,s=>function(...o){let a=Is(this),c=S(`MongoDB ${n}`,"db",{collection:a,operation:n,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":n,library:"mongodb"},r);return c?b(c,()=>{try{let p=s.apply(this,o);return p&&typeof p.then=="function"?p.then(u=>(c.end(0,{resultCount:Array.isArray(u)?u.length:void 0}),u),u=>{throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(c.end(0),p)}catch(p){throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}}):s.apply(this,o)})},Ps=(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(o=>vs(r,o,t));let s=e?.FindCursor||e?.default?.FindCursor,i=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(o=>on(s?.prototype,o,"find",t)),["toArray","next","forEach"].forEach(o=>on(i?.prototype,o,"aggregate",t))},qs=e=>{k("mongodb",t=>Ps(t,e))}});var dn={};R(dn,{instrumentMongoose:()=>$s});var un,pn,Me,cn,Ns,$s,fn=_(()=>{"use strict";T();A();x();un=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",pn=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",Me=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...i){let o=String(this?.op||this?._op||t).toUpperCase(),a=pn(this),c=S(`Mongoose ${o}`,"db",{collection:a,model:un(this),operation:o,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":o,library:"mongoose"},n);return c?b(c,()=>{try{let p=r.apply(this,i);return p&&typeof p.then=="function"?p.then(u=>(c.end(0,{resultCount:Array.isArray(u)?u.length:void 0}),u),u=>{throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(c.end(0),p)}catch(p){throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}}):r.apply(this,i)})},cn=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...s){let i=pn(this),o=S("Mongoose SAVE","db",{collection:i,model:un(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":i,"db.operation.name":"SAVE",library:"mongoose"},t);return o?b(o,()=>{try{let a=n.apply(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(o.end(0),a)}catch(a){throw o.end(500,{error:a?.message,"error.type":a?.name||"Error"}),a}}):n.apply(this,s)})},Ns=(e,t)=>{Me(e?.Query?.prototype,"query",t),Me(e?.Aggregate?.prototype,"aggregate",t),cn(e?.Model?.prototype,t),e?.default&&(Me(e.default?.Query?.prototype,"query",t),Me(e.default?.Aggregate?.prototype,"aggregate",t),cn(e.default?.Model?.prototype,t))},$s=e=>{k("mongoose",t=>Ns(t,e))}});var ln={};R(ln,{instrumentPg:()=>Fs});var Ls,Ie,Us,Fs,hn=_(()=>{"use strict";H();T();A();x();Ls=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},Ie=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...i){let o=Ls(i),a=q(o)||"QUERY",c=S(`Postgres ${a}`,"db",{query:v(o,n),operation:a,"db.system.name":"postgresql","db.operation.name":a,"db.query.text":v(o,n),library:"pg"},n);if(!c)return r.apply(this,i);let p=i.findIndex(u=>typeof u=="function");if(p>=0){let u=i[p];i[p]=function(f,l){return c.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(c,()=>{try{let u=r.apply(this,i);return u&&typeof u.then=="function"?u.then(d=>(c.end(0,{rowCount:d?.rowCount,"db.response.row_count":d?.rowCount}),d),d=>{throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(p<0&&u&&typeof u.once=="function"?(u.once("end",()=>c.end(0)),u.once("error",d=>c.end(500,{error:d.message,"error.type":d.name}))):p<0&&c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}})})},Us=(e,t)=>{e&&(Ie(e.Client?.prototype,"client",t),Ie(e.Pool?.prototype,"pool",t),e.default&&(Ie(e.default.Client?.prototype,"default.client",t),Ie(e.default.Pool?.prototype,"default.pool",t)))},Fs=e=>{k("pg",t=>Us(t,e))}});var yn={};R(yn,{instrumentMysql:()=>Ws});var Ds,oe,Hs,Bs,mn,Ws,gn=_(()=>{"use strict";H();T();A();x();Ds=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},oe=(e,t,n,r)=>{y(e,t,`senzor.${n}.${t}`,s=>function(...o){let a=Ds(o),c=q(a)||t.toUpperCase(),p=S(`MySQL ${c}`,"db",{query:v(a,r),operation:c,"db.system.name":"mysql","db.operation.name":c,"db.query.text":v(a,r),library:n},r);if(!p)return s.apply(this,o);let u=o.findIndex(d=>typeof d=="function");if(u>=0){let d=o[u];o[u]=function(l,h){return p.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(h)?h.length:void 0}),d.apply(this,arguments)}}return b(p,()=>{try{let d=s.apply(this,o);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return p.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw p.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(u<0&&d&&typeof d.once=="function"?(d.once("end",()=>p.end(0)),d.once("error",f=>p.end(500,{error:f.message,"error.type":f.name}))):u<0&&p.end(0),d)}catch(d){throw p.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},Hs=(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=>{oe(r,"query",t,n),oe(r,"execute",t,n)})},Bs=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,s=>function(...o){let a=s.apply(this,o);return oe(a,"query",t,n),oe(a,"execute",t,n),oe(Object.getPrototypeOf(a),"query",t,n),oe(Object.getPrototypeOf(a),"execute",t,n),a})})},mn=(e,t,n)=>{Hs(e,t,n),Bs(e,t,n)},Ws=e=>{k("mysql",t=>mn(t,"mysql",e)),k("mysql2",t=>mn(t,"mysql2",e))}});var Sn={};R(Sn,{instrumentRedis:()=>Zs});var js,se,Qs,Ks,Gs,Zs,bn=_(()=>{"use strict";T();A();x();js=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",se=(e,t,n)=>{y(e,"sendCommand",`senzor.redis.${t}.sendCommand`,r=>function(i,...o){let a=js(i),c=S(`Redis ${a}`,"db",{command:a,operation:a,"db.system.name":"redis","db.operation.name":a,library:t},n);return c?b(c,()=>{try{let p=r.call(this,i,...o);return p&&typeof p.then=="function"?p.then(u=>(c.end(0),u),u=>{throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(c.end(0),p)}catch(p){throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}}):r.apply(this,arguments)})},Qs=(e,t,n)=>(se(e,t,n),se(Object.getPrototypeOf(e),t,n),e),Ks=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...i){let o=r.apply(this,i);return Qs(o,"redis",t)})})},Gs=(e,t)=>{se(e?.prototype,"ioredis",t),se(e?.Redis?.prototype,"ioredis",t),se(e?.Cluster?.prototype,"ioredis-cluster",t),se(e?.default?.prototype,"ioredis",t)},Zs=e=>{k("redis",t=>Ks(t,e)),k("ioredis",t=>Gs(t,e))}});var _n={};R(_n,{instrumentBullMQ:()=>Vs});function Cn(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,s=r.processJob;typeof s!="function"||s[kn]||(r.processJob=async function(i){let o=i.timestamp?Date.now()-i.timestamp:0,a=(i.attemptsMade||0)+1,c=i.opts?.attempts??1,p=a>=c,u=i.name==="__default__"?i.queueName:`${i.queueName}:${i.name}`;return t.startTask(u,"queue",{queueDelay:o,attempts:a,isDeadLetter:!1,metadata:{jobId:i.id,queueName:i.queueName,maxAttempts:c}},async()=>{try{let d=await s.call(this,i);return t.endTask("success"),d}catch(d){try{let f=E.current();f&&f.contextType==="task"&&p&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:i.queueName,jobId:i.id,isDeadLetter:p}),t.endTask("failed"),d}})},Object.defineProperty(r.processJob,kn,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var kn,Vs,wn=_(()=>{"use strict";T();N();kn=Symbol.for("senzor.bullmq.patched");Vs=(e,t)=>{k("bullmq",n=>{Cn(n,e,t),n?.default&&Cn(n.default,e,t)})}});var Rn={};R(Rn,{instrumentNodeCron:()=>Js});function Ys(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function zn(e,t,n){let r=e.schedule;if(typeof r!="function"||r[En])return;let s=r,i=function(o,a,c){if(typeof a!="function")return s.call(this,o,a,c);try{let p=Ys(c),u=p?.name??`cron: ${o}`,d=t.wrapTask(u,"cron",{expression:o,metadata:p},a);return s.call(this,o,d,c)}catch(p){return n&&console.error("[Senzor] cron wrap failed",p),s.call(this,o,a,c)}};Object.defineProperty(i,En,{value:!0,enumerable:!1});try{e.schedule=i}catch{n&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}n&&console.log("[Senzor] node-cron instrumented")}var En,Js,An=_(()=>{"use strict";T();En=Symbol.for("senzor.cron.patched");Js=(e,t)=>{k("node-cron",n=>{n&&(zn(n,e,t),n.default&&zn(n.default,e,t))})}});var Mn={};R(Mn,{instrumentGrpc:()=>na});var Pe,U,ye,Tn,xn,On,ve,Xs,ea,ta,na,In=_(()=>{"use strict";N();T();A();x();G();Pe={0:"OK",1:"CANCELLED",2:"UNKNOWN",3:"INVALID_ARGUMENT",4:"DEADLINE_EXCEEDED",5:"NOT_FOUND",6:"ALREADY_EXISTS",7:"PERMISSION_DENIED",8:"RESOURCE_EXHAUSTED",9:"FAILED_PRECONDITION",10:"ABORTED",11:"OUT_OF_RANGE",12:"UNIMPLEMENTED",13:"INTERNAL",14:"UNAVAILABLE",15:"DATA_LOSS",16:"UNAUTHENTICATED"},U=e=>e===0?0:e===1?499:e===3||e===9||e===11?400:e===4?504:e===5?404:e===6?409:e===7?403:e===8?429:e===10?409:e===12?501:e===16?401:500,ye=e=>{let t=e.replace(/^\//,"").split("/");return{service:t[0]||"unknown",method:t[1]||"unknown"}},Tn="traceparent",xn="x-senzor-trace-id",On="x-senzor-parent-span-id",ve=(e,t,n)=>{try{e&&typeof e.set=="function"&&(e.set(Tn,L(t,n)),e.set(xn,t),e.set(On,n))}catch{}},Xs=e=>{try{if(!e||typeof e.get!="function")return{};let t=e.get(Tn),n=Array.isArray(t)?t[0]:t;if(n){let i=j(String(n));if(i)return i}let r=e.get(xn),s=e.get(On);return{traceId:Array.isArray(r)?r[0]:r||void 0,parentSpanId:Array.isArray(s)?s[0]:s||void 0}}catch{return{}}},ea=(e,t)=>{let n=e?.Client?.prototype;n&&(y(n,"makeUnaryRequest","senzor.grpc.client.makeUnaryRequest",r=>function(i,...o){let a=E.current();if(!a)return r.call(this,i,...o);let{service:c,method:p}=ye(i),u=S(`gRPC ${c}/${p}`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":p,"rpc.grpc.full_method":i,"network.transport":"tcp"},t);if(!u)return r.call(this,i,...o);let d=-1,f=-1;for(let l=0;l<o.length;l++)o[l]&&typeof o[l]=="object"&&typeof o[l].set=="function"&&typeof o[l].get=="function"&&(d=l),typeof o[l]=="function"&&l===o.length-1&&(f=l);if(d>=0&&ve(o[d],a.id,u.spanId),f>=0){let l=o[f];o[f]=function(m,g){if(m){let C=m.code??2;u.end(U(C),{"rpc.grpc.status_code":C,"rpc.grpc.status_text":Pe[C]||"UNKNOWN","error.message":m.details||m.message,"error.type":m.name||"GrpcError"})}else u.end(0,{"rpc.grpc.status_code":0,"rpc.grpc.status_text":"OK"});return l.call(this,m,g)}}return b(u,()=>{try{let l=r.call(this,i,...o);if(f<0&&l&&typeof l.on=="function"){let h=!1;l.on("status",m=>{if(h)return;h=!0;let g=m?.code??0;u.end(U(g),{"rpc.grpc.status_code":g,"rpc.grpc.status_text":Pe[g]||"UNKNOWN"})}),l.on("error",m=>{if(h)return;h=!0;let g=m?.code??2;u.end(U(g),{"rpc.grpc.status_code":g,"error.message":m?.details||m?.message,"error.type":m?.name||"GrpcError"})})}return l}catch(l){throw u.end(500,{"rpc.grpc.status_code":13,"rpc.grpc.status_text":"INTERNAL","error.message":l?.message,"error.type":l?.name||"Error"}),l}})}),y(n,"makeClientStreamRequest","senzor.grpc.client.makeClientStreamRequest",r=>function(i,...o){let a=E.current();if(!a)return r.call(this,i,...o);let{service:c,method:p}=ye(i),u=S(`gRPC ${c}/${p} (client-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":p,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"client_stream","network.transport":"tcp"},t);if(!u)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"&&typeof o[d].get=="function"){ve(o[d],a.id,u.spanId);break}for(let d=o.length-1;d>=0;d--)if(typeof o[d]=="function"){let f=o[d];o[d]=function(h,m){if(h){let g=h.code??2;u.end(U(g),{"rpc.grpc.status_code":g,"error.message":h.details||h.message})}else u.end(0,{"rpc.grpc.status_code":0});return f.call(this,h,m)};break}return b(u,()=>{try{return r.call(this,i,...o)}catch(d){throw u.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}),y(n,"makeServerStreamRequest","senzor.grpc.client.makeServerStreamRequest",r=>function(i,...o){let a=E.current();if(!a)return r.call(this,i,...o);let{service:c,method:p}=ye(i),u=S(`gRPC ${c}/${p} (server-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":p,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"server_stream","network.transport":"tcp"},t);if(!u)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"){ve(o[d],a.id,u.spanId);break}return b(u,()=>{try{let d=r.call(this,i,...o);if(d&&typeof d.on=="function"){let f=!1;d.on("status",l=>{if(f)return;f=!0;let h=l?.code??0;u.end(U(h),{"rpc.grpc.status_code":h,"rpc.grpc.status_text":Pe[h]||"UNKNOWN"})}),d.on("error",l=>{f||(f=!0,u.end(U(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw u.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}),y(n,"makeBidiStreamRequest","senzor.grpc.client.makeBidiStreamRequest",r=>function(i,...o){let a=E.current();if(!a)return r.call(this,i,...o);let{service:c,method:p}=ye(i),u=S(`gRPC ${c}/${p} (bidi-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":p,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"bidi_stream","network.transport":"tcp"},t);if(!u)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"){ve(o[d],a.id,u.spanId);break}return b(u,()=>{try{let d=r.call(this,i,...o);if(d&&typeof d.on=="function"){let f=!1;d.on("status",l=>{if(f)return;f=!0;let h=l?.code??0;u.end(U(h),{"rpc.grpc.status_code":h})}),d.on("error",l=>{f||(f=!0,u.end(U(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw u.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}))},ta=(e,t,n)=>{let r=e?.Server?.prototype;r&&y(r,"register","senzor.grpc.server.register",s=>function(o,a,c,p,u){if(typeof a!="function")return s.call(this,o,a,c,p,u);let d=function(f,l){let{service:h,method:m}=ye(o),g=f?.metadata,C=Xs(g),w=S(`gRPC ${h}/${m}`,"http",{"rpc.system":"grpc","rpc.service":h,"rpc.method":m,"rpc.grpc.full_method":o,"rpc.grpc.call_type":u||"unary","server.type":"grpc",...C.traceId?{"parent.trace_id":C.traceId}:{}},n);if(!w)return a.call(this,f,l);if(typeof l=="function"){let O=function(P,fe,Q,V){if(P){let He=P.code??2;w.end(U(He),{"rpc.grpc.status_code":He,"rpc.grpc.status_text":Pe[He]||"UNKNOWN","error.message":P.details||P.message,"error.type":P.name||"GrpcError"})}else w.end(0,{"rpc.grpc.status_code":0,"rpc.grpc.status_text":"OK"});return l(P,fe,Q,V)};return b(w,()=>{try{return a.call(this,f,O)}catch(P){throw w.end(500,{"rpc.grpc.status_code":13,"error.message":P?.message,"error.type":P?.name||"Error"}),P}})}return b(w,()=>{try{let O=a.call(this,f);if(f&&typeof f.on=="function"){let P=!1,fe=(Q,V)=>{P||(P=!0,w.end(Q,V))};f.on("error",Q=>{let V=Q?.code??2;fe(U(V),{"rpc.grpc.status_code":V,"error.message":Q?.details||Q?.message})}),f.on("end",()=>{fe(0,{"rpc.grpc.status_code":0})}),f.on("cancelled",()=>{fe(U(1),{"rpc.grpc.status_code":1,"rpc.grpc.status_text":"CANCELLED"})})}return O}catch(O){throw w.end(500,{"rpc.grpc.status_code":13,"error.message":O?.message,"error.type":O?.name||"Error"}),O}})};return s.call(this,o,d,c,p,u)})},na=(e,t)=>{k("@grpc/grpc-js",n=>{ea(n,t),ta(n,e,t)})}});var Nn={};R(Nn,{instrumentGraphQL:()=>oa});var vn,qe,Pn,qn,ie,ae,ra,oa,$n=_(()=>{"use strict";T();A();x();vn=4096,qe=e=>!e||typeof e!="string"?"":e.length<=vn?e:e.slice(0,vn)+"...[truncated]",Pn=(e,t)=>{let n={operationType:"query",name:t||"anonymous"};if(!e||!e.definitions||!Array.isArray(e.definitions))return n;let r=e.definitions.filter(i=>i.kind==="OperationDefinition");if(r.length===0)return n;let s=r[0];if(t){let i=r.find(o=>o.name?.value===t);i&&(s=i)}return{operationType:s.operation||"query",name:s.name?.value||t||"anonymous"}},qn=e=>e?typeof e=="string"?e:e.loc?.source?.body?e.loc.source.body:e.source?.body?e.source.body:"":"",ie=e=>e&&Array.isArray(e.errors)&&e.errors.length>0,ae=e=>{if(!e||e.length===0)return"";let t=e.slice(0,5).map(n=>n.message||String(n)).join("; ");return t.length>1024?t.slice(0,1024)+"...":t},ra=(e,t)=>{e&&(y(e,"graphql","senzor.graphql.graphql",n=>function(...s){let i,o,a;s.length===1&&typeof s[0]=="object"&&s[0]!==null?(i=s[0].source,o=s[0].operationName):(i=s[1],o=s[5]);let c=S(`GraphQL ${o||"query"}`,"custom",{"graphql.operation.name":o||"anonymous","graphql.source":i?qe(i):void 0},t);return c?b(c,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(u=>(ie(u)?c.end(500,{"graphql.error_count":u.errors.length,"error.message":ae(u.errors)}):c.end(0),u),u=>{throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"GraphQLError"}),u}):(ie(p)?c.end(500,{"graphql.error_count":p.errors.length,"error.message":ae(p.errors)}):c.end(0),p)}catch(p){throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}}):n.apply(this,s)}),y(e,"execute","senzor.graphql.execute",n=>function(...s){let i,o;s.length===1&&typeof s[0]=="object"&&s[0]!==null&&!Array.isArray(s[0])?(i=s[0].document,o=s[0].operationName):(i=s[1],o=s[5]);let a=Pn(i,o),c=qn(i),p=S(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":qe(c)},t);return p?b(p,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(d=>(ie(d)?p.end(500,{"graphql.error_count":d.errors.length,"error.message":ae(d.errors)}):p.end(0),d),d=>{throw p.end(500,{"error.message":d?.message,"error.type":d?.name||"GraphQLError"}),d}):(ie(u)?p.end(500,{"graphql.error_count":u.errors.length,"error.message":ae(u.errors)}):p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}}):n.apply(this,s)}),y(e,"parse","senzor.graphql.parse",n=>function(s,...i){let o=typeof s=="string"?s:s?.body||"",a=S("GraphQL parse","custom",{"graphql.operation":"parse","graphql.source":qe(o)},t);return a?b(a,()=>{try{let c=n.call(this,s,...i);return a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.name||"GraphQLError","graphql.error_count":1}),c}}):n.call(this,s,...i)}),y(e,"validate","senzor.graphql.validate",n=>function(s,i,...o){let a=S("GraphQL validate","custom",{"graphql.operation":"validate"},t);return a?b(a,()=>{try{let c=n.call(this,s,i,...o);return Array.isArray(c)&&c.length>0?a.end(500,{"graphql.error_count":c.length,"error.message":ae(c)}):a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.name||"Error"}),c}}):n.call(this,s,i,...o)}))},oa=e=>{k("graphql",t=>ra(t,e)),k("graphql/execution",t=>{t?.execute&&y(t,"execute","senzor.graphql.execution.execute",n=>function(...s){let i,o;s.length===1&&typeof s[0]=="object"&&s[0]!==null?(i=s[0].document,o=s[0].operationName):(i=s[1],o=s[5]);let a=Pn(i,o),c=qn(i),p=S(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":qe(c)},e);return p?b(p,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(d=>(ie(d)?p.end(500,{"graphql.error_count":d.errors.length,"error.message":ae(d.errors)}):p.end(0),d),d=>{throw p.end(500,{"error.message":d?.message}),d}):(ie(u)?p.end(500,{"graphql.error_count":u.errors.length}):p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):n.apply(this,s)})})}});var Ln={};R(Ln,{instrumentDns:()=>ia});var sa,aa,ia,Un=_(()=>{"use strict";A();x();sa=(e,t,n)=>{y(e,t,`senzor.dns.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=S(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);if(!a)return r.apply(this,i);let c=i.findIndex((p,u)=>typeof p=="function"&&u===i.length-1);if(c>=0){let p=i[c];i[c]=function(d,...f){if(d)a.end(500,{"error.message":d.message,"error.type":d.code||d.name||"DnsError","dns.error_code":d.code});else{let l={};t==="lookup"&&f[0]?(l["network.peer.address"]=f[0],l["dns.address_family"]=f[1]===6?"IPv6":"IPv4"):(t==="resolve4"||t==="resolve6"||t==="resolve")&&(l["dns.result_count"]=Array.isArray(f[0])?f[0].length:0),a.end(0,l)}return p.call(this,d,...f)}}return b(a,()=>{try{return r.apply(this,i)}catch(p){throw a.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}})})},aa=(e,t,n)=>{y(e,t,`senzor.dns.promises.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=S(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);return a?b(a,async()=>{try{let c=await r.apply(this,i),p={};return t==="lookup"&&c?(p["network.peer.address"]=c.address,p["dns.address_family"]=c.family===6?"IPv6":"IPv4"):Array.isArray(c)&&(p["dns.result_count"]=c.length),a.end(0,p),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.code||c?.name||"DnsError","dns.error_code":c?.code}),c}}):r.apply(this,i)})},ia=e=>{let t;try{t=M("dns")}catch{return}if(!t)return;let n=["lookup","resolve","resolve4","resolve6","resolveMx","resolveTxt","resolveSrv","resolveCname","resolveNs","resolvePtr","resolveSoa","resolveNaptr","resolveCaa","reverse"];for(let s of n)typeof t[s]=="function"&&sa(t,s,e);let r=t.promises;if(r){let s=["lookup","resolve","resolve4","resolve6","resolveMx","resolveTxt","resolveSrv","resolveCname","resolveNs","resolvePtr","resolveSoa","resolveNaptr","resolveCaa","reverse"];for(let i of s)typeof r[i]=="function"&&aa(r,i,e)}}});var Fn={};R(Fn,{instrumentNet:()=>da});var ca,ua,pa,da,Dn=_(()=>{"use strict";A();x();ca=e=>{let t=e[0];if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t.path?{host:t.path,port:"ipc",isIPC:!0}:{host:t.host||"localhost",port:t.port||0,isIPC:!1};if(typeof t=="string"&&!Number.isFinite(Number(t)))return{host:t,port:"ipc",isIPC:!0};let n=Number(t)||0;return{host:typeof e[1]=="string"?e[1]:"localhost",port:n,isIPC:!1}},ua=(e,t)=>{let n=e?.Socket?.prototype;n&&y(n,"connect","senzor.net.socket.connect",r=>function(...i){let{host:o,port:a,isIPC:c}=ca(i),p=c?`TCP connect ${o}`:`TCP connect ${o}:${a}`,u=S(p,"custom",{"net.peer.name":o,"net.peer.port":c?void 0:a,"net.transport":c?"unix":"tcp","network.transport":c?"unix":"tcp"},t);return u?b(u,()=>{let d=r.apply(this,i),f=!1,l=(h,m={})=>{f||(f=!0,u.end(h,m))};return d.once("connect",()=>{l(0,{"net.peer.address":d.remoteAddress,"net.peer.port":d.remotePort,"net.local.address":d.localAddress,"net.local.port":d.localPort})}),d.once("error",h=>{l(500,{"error.message":h?.message,"error.type":h?.code||h?.name||"NetError","net.error_code":h?.code})}),d.once("timeout",()=>{l(504,{"error.message":"Connection timed out","error.type":"TimeoutError"})}),d.once("close",h=>{h?l(500,{"error.message":"Connection closed with error"}):l(0)}),d}):r.apply(this,i)})},pa=(e,t)=>{},da=e=>{let t;try{t=M("net")}catch{return}t&&(ua(t,e),pa(t,e))}});var Kn={};R(Kn,{instrumentKafka:()=>ma});var Wn,jn,Qn,Hn,fa,la,ha,Bn,ma,Gn=_(()=>{"use strict";N();T();A();x();G();Wn="traceparent",jn="x-senzor-trace-id",Qn="x-senzor-parent-span-id",Hn=(e,t,n)=>{let r=e?{...e}:{};return r[Wn]=Buffer.from(L(t,n)),r[jn]=Buffer.from(t),r[Qn]=Buffer.from(n),r},fa=e=>{if(!e)return{};try{let t=e[Wn];if(t){let s=Buffer.isBuffer(t)?t.toString():String(t),i=j(s);if(i)return i}let n=e[jn],r=e[Qn];return{traceId:n?Buffer.isBuffer(n)?n.toString():String(n):void 0,parentSpanId:r?Buffer.isBuffer(r)?r.toString():String(r):void 0}}catch{return{}}},la=(e,t)=>{y(e,"send","senzor.kafka.producer.send",n=>function(s){let i=E.current();if(!i)return n.call(this,s);let o=s?.topic||"unknown",a=s?.messages?.length||0,c=S(`Kafka publish ${o}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":o,"messaging.operation.name":"publish","messaging.batch.message_count":a},t);return c?(s?.messages&&Array.isArray(s.messages)&&(s={...s,messages:s.messages.map(p=>({...p,headers:Hn(p.headers,i.id,c.spanId)}))}),b(c,()=>{let p=n.call(this,s);return p&&typeof p.then=="function"?p.then(u=>(c.end(0,{"messaging.kafka.partitions":Array.isArray(u)?u.map(d=>d.partition).join(","):void 0}),u),u=>{throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"KafkaError"}),u}):(c.end(0),p)})):n.call(this,s)}),y(e,"sendBatch","senzor.kafka.producer.sendBatch",n=>function(s){let i=E.current();if(!i)return n.call(this,s);let o=s?.topicMessages||[],a=o.map(u=>u.topic).join(","),c=o.reduce((u,d)=>u+(d.messages?.length||0),0),p=S(`Kafka publishBatch ${a}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":a,"messaging.operation.name":"publish","messaging.batch.message_count":c,"messaging.kafka.batch_topic_count":o.length},t);return p?(o.length>0&&(s={...s,topicMessages:o.map(u=>({...u,messages:(u.messages||[]).map(d=>({...d,headers:Hn(d.headers,i.id,p.spanId)}))}))}),b(p,()=>{let u=n.call(this,s);return u&&typeof u.then=="function"?u.then(d=>(p.end(0),d),d=>{throw p.end(500,{"error.message":d?.message,"error.type":d?.name||"KafkaError"}),d}):(p.end(0),u)})):n.call(this,s)})},ha=(e,t)=>{y(e,"run","senzor.kafka.consumer.run",n=>function(s){if(!s)return n.call(this,s);let i={...s};if(typeof s.eachMessage=="function"){let o=s.eachMessage;i.eachMessage=async a=>{let{topic:c,partition:p,message:u}=a,d=fa(u?.headers),f=S(`Kafka receive ${c}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":c,"messaging.operation.name":"receive","messaging.kafka.partition":p,"messaging.kafka.message.offset":u?.offset,"messaging.kafka.message.key":u?.key?.toString(),...d.traceId?{"messaging.parent_trace_id":d.traceId}:{}},t);return f?b(f,async()=>{try{let l=await o(a);return f.end(0),l}catch(l){throw f.end(500,{"error.message":l?.message,"error.type":l?.name||"Error"}),l}}):o(a)}}if(typeof s.eachBatch=="function"){let o=s.eachBatch;i.eachBatch=async a=>{let{batch:c}=a,p=c?.topic||"unknown",u=c?.messages?.length||0,d=S(`Kafka receiveBatch ${p}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":p,"messaging.operation.name":"receive","messaging.kafka.partition":c?.partition,"messaging.batch.message_count":u,"messaging.kafka.first_offset":c?.messages?.[0]?.offset,"messaging.kafka.last_offset":c?.messages?.[u-1]?.offset},t);return d?b(d,async()=>{try{let f=await o(a);return d.end(0),f}catch(f){throw d.end(500,{"error.message":f?.message,"error.type":f?.name||"Error"}),f}}):o(a)}}return n.call(this,i)})},Bn=(e,t)=>{let n=e?.Kafka;n?.prototype&&(y(n.prototype,"producer","senzor.kafka.producer",r=>function(...i){let o=r.apply(this,i);return o&&la(o,t),o}),y(n.prototype,"consumer","senzor.kafka.consumer",r=>function(...i){let o=r.apply(this,i);return o&&ha(o,t),o}))},ma=e=>{k("kafkajs",t=>{Bn(t,e),t?.default?.Kafka&&Bn(t.default,e)})}});var er={};R(er,{instrumentAmqplib:()=>Sa});var Yn,Jn,Xn,Zn,ya,ce,ga,Vn,Sa,tr=_(()=>{"use strict";N();T();A();x();G();Yn="traceparent",Jn="x-senzor-trace-id",Xn="x-senzor-parent-span-id",Zn=(e,t,n)=>{let r=e?{...e}:{},s=r.headers?{...r.headers}:{};return s[Yn]=L(t,n),s[Jn]=t,s[Xn]=n,r.headers=s,r},ya=e=>{let t=e?.properties?.headers;if(!t)return{};try{let n=t[Yn];if(n){let i=Buffer.isBuffer(n)?n.toString():String(n),o=j(i);if(o)return o}let r=t[Jn],s=t[Xn];return{traceId:r?Buffer.isBuffer(r)?r.toString():String(r):void 0,parentSpanId:s?Buffer.isBuffer(s)?s.toString():String(s):void 0}}catch{return{}}},ce=(e,t)=>{e&&(y(e,"publish","senzor.amqplib.channel.publish",n=>function(s,i,o,a){let c=E.current();if(!c)return n.call(this,s,i,o,a);let p=s||i||"default",u=S(`RabbitMQ publish ${p}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":p,"messaging.operation.name":"publish","messaging.rabbitmq.exchange":s||"(default)","messaging.rabbitmq.routing_key":i,"messaging.message.body_size":o?.length||0},t);if(!u)return n.call(this,s,i,o,a);let d=Zn(a,c.id,u.spanId);return b(u,()=>{try{let f=n.call(this,s,i,o,d);return u.end(0,{"messaging.rabbitmq.backpressure":f===!1}),f}catch(f){throw u.end(500,{"error.message":f?.message,"error.type":f?.name||"AmqpError"}),f}})}),y(e,"sendToQueue","senzor.amqplib.channel.sendToQueue",n=>function(s,i,o){let a=E.current();if(!a)return n.call(this,s,i,o);let c=S(`RabbitMQ send ${s}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":s,"messaging.operation.name":"publish","messaging.rabbitmq.routing_key":s,"messaging.message.body_size":i?.length||0},t);if(!c)return n.call(this,s,i,o);let p=Zn(o,a.id,c.spanId);return b(c,()=>{try{let u=n.call(this,s,i,p);return c.end(0,{"messaging.rabbitmq.backpressure":u===!1}),u}catch(u){throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"AmqpError"}),u}})}),y(e,"consume","senzor.amqplib.channel.consume",n=>function(s,i,o){if(typeof i!="function")return n.call(this,s,i,o);let a=function(c){if(!c)return i(c);let p=ya(c),u=c.fields?.exchange||"",d=c.fields?.routingKey||s,f=u||d||s,l=S(`RabbitMQ receive ${f}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":f,"messaging.operation.name":"receive","messaging.rabbitmq.exchange":u||"(default)","messaging.rabbitmq.routing_key":d,"messaging.rabbitmq.delivery_tag":c.fields?.deliveryTag,"messaging.rabbitmq.redelivered":c.fields?.redelivered,"messaging.rabbitmq.consumer_tag":c.fields?.consumerTag,"messaging.message.body_size":c.content?.length||0,...p.traceId?{"messaging.parent_trace_id":p.traceId}:{}},t);return l?b(l,()=>{try{let h=i(c);return h&&typeof h.then=="function"?h.then(m=>(l.end(0),m),m=>{throw l.end(500,{"error.message":m?.message,"error.type":m?.name||"Error"}),m}):(l.end(0),h)}catch(h){throw l.end(500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}}):i(c)};return n.call(this,s,a,o)}))},ga=(e,t)=>{try{let n=M("amqplib/lib/channel_model");n?.Channel?.prototype&&ce(n.Channel.prototype,t),n?.ConfirmChannel?.prototype&&ce(n.ConfirmChannel.prototype,t)}catch{}},Vn=(e,t)=>{y(e,"connect","senzor.amqplib.connect",n=>function(...s){let i=n.apply(this,s);return i&&typeof i.then=="function"?i.then(o=>o&&(y(o,"createChannel","senzor.amqplib.createChannel",a=>function(...p){let u=a.apply(this,p);return u&&typeof u.then=="function"?u.then(d=>(d&&ce(d,t),d)):(u&&ce(u,t),u)}),y(o,"createConfirmChannel","senzor.amqplib.createConfirmChannel",a=>function(...p){let u=a.apply(this,p);return u&&typeof u.then=="function"?u.then(d=>(d&&ce(d,t),d)):(u&&ce(u,t),u)}),o)):i})},Sa=e=>{k("amqplib",t=>{ga(t,e),Vn(t,e)}),k("amqplib/callback_api",t=>{Vn(t,e)})}});var rr={};R(rr,{instrumentSocketIO:()=>_a});var ba,nr,ge,ct,ka,Ca,_a,or=_(()=>{"use strict";N();T();A();x();ba=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener","error","ping","pong","connection"]),nr=e=>typeof e!="string"?!1:!ba.has(e),ge=(e,t,n,r)=>{y(e,"emit",t,s=>function(o,...a){if(!nr(o))return s.call(this,o,...a);if(!E.current())return s.call(this,o,...a);let p=this.nsp?.name||this.name||"/",u=S(`Socket.IO ${n} emit ${o}`,"messaging",{"messaging.system":"socket.io","messaging.destination.name":o,"messaging.operation.name":"send","messaging.socketio.namespace":p,"messaging.socketio.side":n,"messaging.socketio.event":o},r);if(!u)return s.call(this,o,...a);let d=a[a.length-1],f=typeof d=="function";if(f){let l=d;a[a.length-1]=function(...m){return u.end(0,{"messaging.socketio.acknowledged":!0}),l.apply(this,m)}}return b(u,()=>{try{let l=s.call(this,o,...a);return f||u.end(0),l}catch(l){throw u.end(500,{"error.message":l?.message,"error.type":l?.name||"SocketIOError"}),l}})})},ct=(e,t,n,r)=>{y(e,"on",t,s=>function(o,a){if(!nr(o)||typeof a!="function")return s.call(this,o,a);let c=this.nsp?.name||this.name||"/",p=function(...u){let d=S(`Socket.IO ${n} receive ${o}`,"messaging",{"messaging.system":"socket.io","messaging.destination.name":o,"messaging.operation.name":"receive","messaging.socketio.namespace":c,"messaging.socketio.side":n,"messaging.socketio.event":o},r);return d?b(d,()=>{try{let f=a.apply(this,u);return f&&typeof f.then=="function"?f.then(l=>(d.end(0),l),l=>{throw d.end(500,{"error.message":l?.message,"error.type":l?.name||"Error"}),l}):(d.end(0),f)}catch(f){throw d.end(500,{"error.message":f?.message,"error.type":f?.name||"Error"}),f}}):a.apply(this,u)};return p.__senzorOriginal=a,s.call(this,o,p)})},ka=(e,t)=>{let n=e?.Socket;n?.prototype&&(ge(n.prototype,"senzor.socketio.server.socket.emit","server",t),ct(n.prototype,"senzor.socketio.server.socket.on","server",t));let r=e?.Namespace;r?.prototype&&ge(r.prototype,"senzor.socketio.server.namespace.emit","server",t)},Ca=(e,t)=>{let n=e?.Socket||e?.io?.Socket;n?.prototype&&(ge(n.prototype,"senzor.socketio.client.emit","client",t),ct(n.prototype,"senzor.socketio.client.on","client",t)),e?.Manager?.prototype},_a=e=>{k("socket.io",t=>{if(ka(t,e),!t.Socket)try{let n=M("socket.io/dist/socket");n?.Socket?.prototype&&(ge(n.Socket.prototype,"senzor.socketio.server.socket.emit","server",e),ct(n.Socket.prototype,"senzor.socketio.server.socket.on","server",e))}catch{}if(!t.Namespace)try{let n=M("socket.io/dist/namespace");n?.Namespace?.prototype&&ge(n.Namespace.prototype,"senzor.socketio.server.namespace.emit","server",e)}catch{}}),k("socket.io-client",t=>{Ca(t,e)})}});var ar={};R(ar,{instrumentNestJS:()=>za});var sr,wa,Ea,za,ir=_(()=>{"use strict";T();A();x();sr=e=>e&&e.constructor?.name||"UnknownController",wa=(e,t)=>{let n;try{n=M("@nestjs/core/router/router-execution-context")?.RouterExecutionContext}catch{}n||(n=e?.RouterExecutionContext),n?.prototype?.create&&y(n.prototype,"create","senzor.nestjs.routerExecutionContext.create",r=>function(i,o,a,c,p,...u){let d=r.call(this,i,o,a,c,p,...u);if(typeof d!="function")return d;let f=sr(i);return function(h,m,g){let C=h?.route?.path||h?.url?.split("?")[0]||"/",w=S(`NestJS ${f}.${a}`,"function",{"nestjs.controller":f,"nestjs.method":a,"nestjs.module":c,"nestjs.type":"request_handler","http.route":C},t);return w?b(w,()=>{try{let O=d.call(this,h,m,g);return O&&typeof O.then=="function"?O.then(P=>(w.end(0),P),P=>{throw w.end(500,{"error.message":P?.message,"error.type":P?.name||"Error"}),P}):(w.end(0),O)}catch(O){throw w.end(500,{"error.message":O?.message,"error.type":O?.name||"Error"}),O}}):d.call(this,h,m,g)}})},Ea=(e,t)=>{let n;try{n=M("@nestjs/core/router/router-explorer")?.RouterExplorer}catch{}n||(n=e?.RouterExplorer),n?.prototype?.applyCallbackToRouter&&y(n.prototype,"applyCallbackToRouter","senzor.nestjs.routerExplorer.applyCallbackToRouter",r=>function(i,o,a,c,...p){let u=o?.methodName||"unknown",d=o?.path||"/",f=o?.requestMethod,l=a?.metatype?.name||a?.name||"UnknownController",h=r.call(this,i,o,a,c,...p);return t?.debug&&console.log(`[Senzor] NestJS route registered: ${l}.${u} \u2192 ${d}`),h})},za=e=>{k("@nestjs/core",t=>{wa(t,e),Ea(t,e)}),k("@nestjs/core/router/router-execution-context",t=>{t?.RouterExecutionContext?.prototype?.create&&y(t.RouterExecutionContext.prototype,"create","senzor.nestjs.rec.create.direct",n=>function(s,i,o,a,c,...p){let u=n.call(this,s,i,o,a,c,...p);if(typeof u!="function")return u;let d=sr(s);return function(l,h,m){let g=l?.route?.path||l?.url?.split("?")[0]||"/",C=S(`NestJS ${d}.${o}`,"function",{"nestjs.controller":d,"nestjs.method":o,"nestjs.module":a,"nestjs.type":"request_handler","http.route":g},e);return C?b(C,()=>{try{let w=u.call(this,l,h,m);return w&&typeof w.then=="function"?w.then(O=>(C.end(0),O),O=>{throw C.end(500,{"error.message":O?.message}),O}):(C.end(0),w)}catch(w){throw C.end(500,{"error.message":w?.message}),w}}):u.call(this,l,h,m)}})})}});var dr={};R(dr,{instrumentHapi:()=>Ta});var Ra,Aa,ut,cr,ur,pr,Ta,fr=_(()=>{"use strict";T();A();x();Ra={0:"GET",1:"HEAD",2:"POST",3:"PUT",4:"DELETE",5:"OPTIONS",6:"PATCH"},Aa=e=>typeof e=="string"?e.toUpperCase():typeof e=="number"&&Ra[e]||"UNKNOWN",ut=(e,t,n,r)=>typeof e!="function"?e:function(i,o){let a=Aa(n),c=t||i?.route?.path||i?.path||"/",p=S(`Hapi ${a} ${c}`,"function",{"hapi.type":"route_handler","hapi.route":c,"hapi.method":a,"http.route":c,framework:"hapi"},r);return p?b(p,()=>{try{let u=e.call(this,i,o);return u&&typeof u.then=="function"?u.then(d=>{let f=d?.statusCode||i?.response?.statusCode||200;return p.end(f>=400?f:0,{"http.response.status_code":f}),d},d=>{let f=d?.output?.statusCode||500;throw p.end(f,{"error.message":d?.message,"error.type":d?.name||"Error","http.response.status_code":f}),d}):(p.end(0),u)}catch(u){let d=u?.output?.statusCode||500;throw p.end(d,{"error.message":u?.message,"error.type":u?.name||"Error","http.response.status_code":d}),u}}):e.call(this,i,o)},cr=(e,t)=>{if(!e)return e;let n=e.method||"GET",r=e.path||"/",s={...e};return typeof s.handler=="function"?s.handler=ut(s.handler,r,n,t):s.options&&typeof s.options.handler=="function"?(s.options={...s.options},s.options.handler=ut(s.options.handler,r,n,t)):s.config&&typeof s.config.handler=="function"&&(s.config={...s.config},s.config.handler=ut(s.config.handler,r,n,t)),s},ur=(e,t)=>{e&&y(e,"route","senzor.hapi.server.route",n=>function(s){if(Array.isArray(s)){let o=s.map(a=>cr(a,t));return n.call(this,o)}let i=cr(s,t);return n.call(this,i)})},pr=(e,t)=>{e&&y(e,"ext","senzor.hapi.server.ext",n=>function(s,i,o){if(typeof s=="string"&&typeof i=="function"){let a=s,c=i,p=function(u,d){let f=S(`Hapi ext ${a}`,"function",{"hapi.type":"lifecycle_hook","hapi.hook":a,framework:"hapi"},t);return f?b(f,()=>{try{let l=c.call(this,u,d);return l&&typeof l.then=="function"?l.then(h=>(f.end(0),h),h=>{throw f.end(500,{"error.message":h?.message}),h}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):c.call(this,u,d)};return n.call(this,s,p,o)}return n.call(this,s,i,o)})},Ta=e=>{k("@hapi/hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(ur(n.prototype,e),e?.frameworkSpans!==!1&&pr(n.prototype,e))}),k("hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(ur(n.prototype,e),e?.frameworkSpans!==!1&&pr(n.prototype,e))})}});var hr={};R(hr,{instrumentPino:()=>Oa});var lr,xa,Oa,mr=_(()=>{"use strict";N();T();A();lr=()=>{let e=E.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t["senzor.context"]=e.contextType,t},xa=(e,t)=>{let n=e;if(typeof e=="function")try{let s=e({level:"silent"},{write:()=>{}}),i=Object.getPrototypeOf(s);if(i&&!i.__senzorPatched){let o=Object.getOwnPropertySymbols(i).find(c=>c.toString().includes("write")||c.toString().includes("pino.write"));if(o){let c=i[o];typeof c=="function"&&(i[o]=function(u,d,f){let l=lr();return l&&u&&typeof u=="object"&&Object.assign(u,l),c.call(this,u,d,f)})}let a=["trace","debug","info","warn","error","fatal"];for(let c of a)typeof i[c]=="function"&&y(i,c,`senzor.pino.${c}`,p=>function(...d){let f=lr();if(!f)return p.apply(this,d);if(d.length>0&&typeof d[0]=="object"&&d[0]!==null&&!(d[0]instanceof Error))d[0]={...d[0],...f};else if(d.length>0&&typeof d[0]=="string")d.unshift(f);else if(d.length>0&&d[0]instanceof Error){let l=d[0];d[0]={...f,err:l},typeof d[1]!="string"&&d.splice(1,0,l.message)}return p.apply(this,d)});typeof i.child=="function"&&y(i,"child","senzor.pino.child",c=>function(u,...d){return c.call(this,u,...d)}),i.__senzorPatched=!0}}catch{}},Oa=e=>{k("pino",t=>{xa(t,e)})}});var Sr={};R(Sr,{instrumentWinston:()=>Ia});var yr,gr,Ma,Ia,br=_(()=>{"use strict";N();T();A();yr=()=>{let e=E.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t["senzor.context"]=e.contextType,t},gr=(e,t)=>{let n=e?.Logger;if(!n)try{let r=M("winston/lib/winston/logger");n=r?.Logger||r}catch{}n?.prototype&&(y(n.prototype,"write","senzor.winston.logger.write",r=>function(i){if(i&&typeof i=="object"){let o=yr();o&&(i.traceId=o.traceId,o.spanId&&(i.spanId=o.spanId),i["senzor.context"]=o["senzor.context"])}return r.call(this,i)}),y(n.prototype,"log","senzor.winston.logger.log",r=>function(...i){let o=yr();return o&&i.length>0&&typeof i[0]=="object"&&i[0]!==null&&!(i[0]instanceof Error)&&(i[0]={...i[0],...o}),r.apply(this,i)}))},Ma=(e,t)=>{typeof e?.createLogger=="function"&&y(e,"createLogger","senzor.winston.createLogger",n=>function(s){let i=n.call(this,s);if(i&&!i.__senzorPatched){let o=Object.getPrototypeOf(i);o&&!o.__senzorPatched&&(gr({Logger:{prototype:o}},t),o.__senzorPatched=!0),i.__senzorPatched=!0}return i})},Ia=e=>{k("winston",t=>{gr(t,e),Ma(t,e)})}});var Cr={};R(Cr,{instrumentBunyan:()=>Pa});var va,kr,Pa,_r=_(()=>{"use strict";N();T();A();va=()=>{let e=E.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t.senzor_context=e.contextType,t},kr=(e,t)=>{let n=e?.prototype;n&&y(n,"_emit","senzor.bunyan.logger._emit",r=>function(i,o){if(i&&typeof i=="object"){let a=va();a&&(i.traceId=a.traceId,a.spanId&&(i.spanId=a.spanId),i.senzor_context=a.senzor_context)}return r.call(this,i,o)})},Pa=e=>{k("bunyan",t=>{kr(t,e),t?.default?.prototype?._emit&&kr(t.default,e)})}});var zr={};R(zr,{instrumentAwsSdk:()=>Ba});var wr,qa,Er,Na,$a,La,Ua,Fa,Da,pt,Ha,Ba,Rr=_(()=>{"use strict";T();A();x();wr={S3Client:"S3",DynamoDBClient:"DynamoDB",SQSClient:"SQS",SNSClient:"SNS",LambdaClient:"Lambda",SESClient:"SES",SESv2Client:"SESv2",CloudWatchClient:"CloudWatch",CloudWatchLogsClient:"CloudWatchLogs",KinesisClient:"Kinesis",EventBridgeClient:"EventBridge",SecretsManagerClient:"SecretsManager",SSMClient:"SSM",STSClient:"STS",IAMClient:"IAM",EC2Client:"EC2",ECSClient:"ECS",EKSClient:"EKS",RDSClient:"RDS",ElastiCacheClient:"ElastiCache",RedshiftClient:"Redshift",CognitoIdentityProviderClient:"CognitoIdentityProvider",Route53Client:"Route53",CloudFrontClient:"CloudFront",APIGatewayClient:"APIGateway",StepFunctionsClient:"StepFunctions",CodeBuildClient:"CodeBuild",CodePipelineClient:"CodePipeline",ACMClient:"ACM",KMSClient:"KMS",BedrockRuntimeClient:"BedrockRuntime"},qa={anthropic:"anthropic",amazon:"aws_bedrock",meta:"meta",cohere:"cohere",mistral:"mistral",ai21:"ai21",stability:"stability"},Er=e=>{if(!e)return"aws_bedrock";let t=e.split(".")[0]?.toLowerCase();return qa[t]||"aws_bedrock"},Na=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;s&&(n["gen_ai.system"]=Er(s),n["gen_ai.request.model"]=s);try{let i;if(t?.body&&(typeof t.body=="string"?i=t.body:t.body instanceof Uint8Array?i=new TextDecoder().decode(t.body):Buffer.isBuffer(t.body)&&(i=t.body.toString("utf-8"))),i){let o=JSON.parse(i);o.usage&&(o.usage.input_tokens!==void 0&&(n["gen_ai.usage.input_tokens"]=o.usage.input_tokens),o.usage.output_tokens!==void 0&&(n["gen_ai.usage.output_tokens"]=o.usage.output_tokens)),o.inputTextTokenCount!==void 0&&(n["gen_ai.usage.input_tokens"]=n["gen_ai.usage.input_tokens"]||o.inputTextTokenCount),o.results?.[0]?.tokenCount!==void 0&&(n["gen_ai.usage.output_tokens"]=n["gen_ai.usage.output_tokens"]||o.results[0].tokenCount),o.meta?.billed_units&&(n["gen_ai.usage.input_tokens"]=n["gen_ai.usage.input_tokens"]||o.meta.billed_units.input_tokens,n["gen_ai.usage.output_tokens"]=n["gen_ai.usage.output_tokens"]||o.meta.billed_units.output_tokens),o.stop_reason&&(n["gen_ai.response.finish_reason"]=o.stop_reason),o.completionReason&&(n["gen_ai.response.finish_reason"]=o.completionReason)}}catch{}return n},$a=e=>e==="InvokeModel"||e==="InvokeModelWithResponseStream"||e==="Converse"||e==="ConverseStream",La=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;return s&&(n["gen_ai.system"]=Er(s),n["gen_ai.request.model"]=s),t?.usage&&(t.usage.inputTokens!==void 0&&(n["gen_ai.usage.input_tokens"]=t.usage.inputTokens),t.usage.outputTokens!==void 0&&(n["gen_ai.usage.output_tokens"]=t.usage.outputTokens),t.usage.totalTokens!==void 0&&(n["gen_ai.usage.total_tokens"]=t.usage.totalTokens)),t?.stopReason&&(n["gen_ai.response.finish_reason"]=t.stopReason),n},Ua=e=>{let t=e?.constructor?.name;if(t&&wr[t])return wr[t];if(e?.config?.serviceId)return e.config.serviceId;if(e?.middlewareStack?.identify)try{let n=e.middlewareStack.identify();if(typeof n=="string"&&n.length>0)return n.split(" ")[0]}catch{}return t&&t.endsWith("Client")&&t.slice(0,-6)||"AWS"},Fa=e=>{let t=e?.constructor?.name;return t?t.endsWith("Command")?t.slice(0,-7):t:"UnknownCommand"},Da=async e=>{try{let t=e?.config?.region;return typeof t=="function"?await t():t||void 0}catch{return}},pt=(e,t)=>{e&&y(e,"send","senzor.aws-sdk.client.send",n=>function(s,...i){let o=Ua(this),a=Fa(s),c=`AWS ${o} ${a}`,p=S(c,"http",{"rpc.system":"aws-api","rpc.service":o,"rpc.method":a,"cloud.provider":"aws","aws.service":o,"aws.operation":a},t);return p?(Da(this).then(u=>{u&&p&&(p.__awsRegion=u)}).catch(()=>{}),b(p,()=>{try{let u=n.call(this,s,...i);return u&&typeof u.then=="function"?u.then(d=>{let f=d?.$metadata?.httpStatusCode,h={"aws.request_id":d?.$metadata?.requestId,"aws.region":p.__awsRegion,"http.response.status_code":f};if($a(a)){let m=a,g=m==="Converse"||m==="ConverseStream"?La(s,d):Na(s,d);Object.assign(h,g)}return p.end(f&&f>=400?f:0,h),d},d=>{let f=d?.$metadata?.httpStatusCode||500,l=d?.$metadata?.requestId;throw p.end(f,{"error.message":d?.message,"error.type":d?.name||d?.code||"AwsError","aws.request_id":l,"aws.region":p.__awsRegion,"http.response.status_code":f}),d}):(p.end(0),u)}catch(u){throw p.end(u?.$metadata?.httpStatusCode||500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}})):n.call(this,s,...i)})},Ha=["@aws-sdk/client-s3","@aws-sdk/client-dynamodb","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-lambda","@aws-sdk/client-ses","@aws-sdk/client-sesv2","@aws-sdk/client-cloudwatch","@aws-sdk/client-cloudwatch-logs","@aws-sdk/client-kinesis","@aws-sdk/client-eventbridge","@aws-sdk/client-secrets-manager","@aws-sdk/client-ssm","@aws-sdk/client-sts","@aws-sdk/client-iam","@aws-sdk/client-ec2","@aws-sdk/client-ecs","@aws-sdk/client-rds","@aws-sdk/client-cognito-identity-provider","@aws-sdk/client-route-53","@aws-sdk/client-cloudfront","@aws-sdk/client-api-gateway","@aws-sdk/client-sfn","@aws-sdk/client-codebuild","@aws-sdk/client-kms","@aws-sdk/client-bedrock-runtime"],Ba=e=>{k("@smithy/smithy-client",t=>{let n=t?.Client;n?.prototype&&pt(n.prototype,e)}),k("@aws-sdk/smithy-client",t=>{let n=t?.Client;n?.prototype&&pt(n.prototype,e)});for(let t of Ha)k(t,n=>{for(let r of Object.keys(n))r.endsWith("Client")&&n[r]?.prototype?.send&&pt(n[r].prototype,e)})}});var xr={};R(xr,{instrumentKnex:()=>Qa});var Wa,Ar,ja,Ne,Tr,Qa,Or=_(()=>{"use strict";H();T();A();x();Wa={pg:"postgresql","pg-native":"postgresql",mysql:"mysql",mysql2:"mysql",sqlite3:"sqlite","better-sqlite3":"sqlite",mssql:"mssql",oracledb:"oracle",oracle:"oracle",redshift:"redshift",cockroachdb:"cockroachdb"},Ar=e=>{let t=e?.config?.client||e?.dialect||e?.driverName||"unknown",n=typeof t=="string"?t.toLowerCase():"unknown";return Wa[n]||n},ja=e=>e&&e.match(/(?:FROM|INTO|UPDATE|JOIN)\s+[`"[\]]?(\w+)[`"\]]?/i)?.[1]||void 0,Ne=(e,t)=>{let n;if(n=e?.Client,!n)try{n=M("knex/lib/client")}catch{}n?.prototype&&(y(n.prototype,"query","senzor.knex.client.query",r=>function(i,o){let a=o?.sql,c=o?.method||"raw",p=q(a)||c.toUpperCase(),u=Ar(this),d=ja(a),f=S(`Knex ${p}`,"db",{"db.system.name":u,"db.operation.name":p,"db.query.text":v(a,t),"db.collection.name":d,"knex.method":c,library:"knex"},t);return f?b(f,()=>{try{let l=r.call(this,i,o);return l&&typeof l.then=="function"?l.then(h=>{let m=Array.isArray(h)?h.length:h?.rowCount??h?.affectedRows;return f.end(0,{"db.response.row_count":m}),h},h=>{throw f.end(500,{"error.message":h?.message,"error.type":h?.name||"Error","db.error.code":h?.code}),h}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message,"error.type":l?.name||"Error","db.error.code":l?.code}),l}}):r.call(this,i,o)}),typeof n.prototype._stream=="function"&&y(n.prototype,"_stream","senzor.knex.client._stream",r=>function(i,o,a,c){let p=o?.sql,u=q(p)||"STREAM",d=Ar(this),f=S(`Knex STREAM ${u}`,"db",{"db.system.name":d,"db.operation.name":`STREAM_${u}`,"db.query.text":v(p,t),"knex.method":"stream",library:"knex"},t);return f?b(f,()=>{try{let l=r.call(this,i,o,a,c);return l&&typeof l.then=="function"?l.then(h=>(f.end(0),h),h=>{throw f.end(500,{"error.message":h?.message}),h}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):r.call(this,i,o,a,c)}))},Tr=(e,t)=>{typeof e=="function"&&e.Client?.prototype&&Ne(e,t)},Qa=e=>{k("knex",t=>{Tr(t,e),Ne(t,e),t?.default&&(Tr(t.default,e),Ne(t.default,e))}),k("knex/lib/client",t=>{t?.prototype&&Ne({Client:t},e)})}});var Mr={};R(Mr,{instrumentTedious:()=>Za});var ue,Ka,Se,Ga,Za,Ir=_(()=>{"use strict";H();T();A();x();ue=e=>{let t=e?.config;if(!t)return{};let n={"db.system.name":"mssql"};return t.server&&(n["server.address"]=t.server),t.options?.port&&(n["server.port"]=t.options.port),t.options?.database&&(n["db.namespace"]=t.options.database),n},Ka=(e,t)=>{let n=e?.Connection;if(!n?.prototype)return;let r=n.prototype;y(r,"execSql","senzor.tedious.connection.execSql",s=>function(o){let a=o?.sqlTextOrProcedure,c=q(a)||"QUERY",p=ue(this),u=S(`MSSQL ${c}`,"db",{...p,"db.operation.name":c,"db.query.text":v(a,t),"tedious.method":"execSql",library:"tedious"},t);return u?b(u,()=>(Se(o,u),s.call(this,o))):s.call(this,o)}),y(r,"execSqlBatch","senzor.tedious.connection.execSqlBatch",s=>function(o){let a=o?.sqlTextOrProcedure,c=q(a)||"BATCH",p=ue(this),u=S(`MSSQL BATCH ${c}`,"db",{...p,"db.operation.name":`BATCH_${c}`,"db.query.text":v(a,t),"tedious.method":"execSqlBatch",library:"tedious"},t);return u?b(u,()=>(Se(o,u),s.call(this,o))):s.call(this,o)}),y(r,"callProcedure","senzor.tedious.connection.callProcedure",s=>function(o){let a=o?.sqlTextOrProcedure||"unknown",c=ue(this),p=S(`MSSQL CALL ${a}`,"db",{...c,"db.operation.name":"CALL","db.query.text":a,"db.collection.name":a,"tedious.method":"callProcedure",library:"tedious"},t);return p?b(p,()=>(Se(o,p),s.call(this,o))):s.call(this,o)}),y(r,"execBulkLoad","senzor.tedious.connection.execBulkLoad",s=>function(o,...a){let c=o?.table||"unknown",p=ue(this),u=S(`MSSQL BULK INSERT ${c}`,"db",{...p,"db.operation.name":"BULK_INSERT","db.collection.name":c,"tedious.method":"execBulkLoad",library:"tedious"},t);return u?b(u,()=>{if(o&&typeof o.callback=="function"){let d=o.callback;o.callback=function(f,l){return f?u.end(500,{"error.message":f.message,"error.type":f.name||"Error"}):u.end(0,{"db.response.row_count":l}),d.call(this,f,l)}}else{let d=a.length-1;if(d>=0&&typeof a[d]=="function"){let f=a[d];a[d]=function(l,h){return l?u.end(500,{"error.message":l.message}):u.end(0,{"db.response.row_count":h}),f.apply(this,arguments)}}else u.end(0)}return s.call(this,o,...a)}):s.call(this,o,...a)}),typeof r.prepare=="function"&&y(r,"prepare","senzor.tedious.connection.prepare",s=>function(o){let a=o?.sqlTextOrProcedure,c=ue(this),p=S("MSSQL PREPARE","db",{...c,"db.operation.name":"PREPARE","db.query.text":v(a,t),"tedious.method":"prepare",library:"tedious"},t);return p?b(p,()=>(Se(o,p),s.call(this,o))):s.call(this,o)}),typeof r.execute=="function"&&y(r,"execute","senzor.tedious.connection.execute",s=>function(o,a){let c=o?.sqlTextOrProcedure,p=q(c)||"EXECUTE",u=ue(this),d=S(`MSSQL EXECUTE ${p}`,"db",{...u,"db.operation.name":`EXECUTE_${p}`,"db.query.text":v(c,t),"tedious.method":"execute",library:"tedious"},t);return d?b(d,()=>(Se(o,d),s.call(this,o,a))):s.call(this,o,a)})},Se=(e,t)=>{if(!(!e||!t)){if(typeof e.callback=="function"){let n=e.callback;e.callback=function(r,s,i){return r?t.end(500,{"error.message":r.message,"error.type":r.name||"RequestError","db.error.code":r.code}):t.end(0,{"db.response.row_count":s}),n.call(this,r,s,i)};return}if(typeof e.on=="function"){let n=!1;e.on("requestCompleted",()=>{n||(n=!0,t.end(0))}),e.on("error",r=>{n||(n=!0,t.end(500,{"error.message":r?.message}))})}}},Ga=(e,t)=>{let n=e?.Request;if(!n?.prototype)return;let r=n.prototype;y(r,"query","senzor.mssql.request.query",s=>function(o){let a=q(o)||"QUERY",c=S(`MSSQL ${a}`,"db",{"db.system.name":"mssql","db.operation.name":a,"db.query.text":v(o,t),library:"mssql"},t);return c?b(c,()=>{try{let p=s.call(this,o);return p&&typeof p.then=="function"?p.then(u=>(c.end(0,{"db.response.row_count":u?.recordset?.length??u?.rowsAffected?.[0]}),u),u=>{throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"Error","db.error.code":u?.code}),u}):(c.end(0),p)}catch(p){throw c.end(500,{"error.message":p?.message}),p}}):s.call(this,o)}),y(r,"execute","senzor.mssql.request.execute",s=>function(o){let a=S(`MSSQL CALL ${o}`,"db",{"db.system.name":"mssql","db.operation.name":"CALL","db.query.text":o,"db.collection.name":o,library:"mssql"},t);return a?b(a,()=>{try{let c=s.call(this,o);return c&&typeof c.then=="function"?c.then(p=>(a.end(0),p),p=>{throw a.end(500,{"error.message":p?.message}),p}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.call(this,o)}),typeof r.batch=="function"&&y(r,"batch","senzor.mssql.request.batch",s=>function(o){let a=q(o)||"BATCH",c=S(`MSSQL BATCH ${a}`,"db",{"db.system.name":"mssql","db.operation.name":`BATCH_${a}`,"db.query.text":v(o,t),library:"mssql"},t);return c?b(c,()=>{try{let p=s.call(this,o);return p&&typeof p.then=="function"?p.then(u=>(c.end(0),u),u=>{throw c.end(500,{"error.message":u?.message}),u}):(c.end(0),p)}catch(p){throw c.end(500,{"error.message":p?.message}),p}}):s.call(this,o)})},Za=e=>{k("tedious",t=>{Ka(t,e)}),k("mssql",t=>{Ga(t,e)})}});var qr={};R(qr,{instrumentCassandra:()=>Ja});var Va,vr,$e,Pr,Ya,Ja,Nr=_(()=>{"use strict";H();T();A();x();Va={0:"any",1:"one",2:"two",3:"three",4:"quorum",5:"all",6:"localQuorum",7:"eachQuorum",8:"serial",9:"localSerial",10:"localOne"},vr=e=>{if(typeof e=="string")return e;if(typeof e=="number")return Va[e]},$e=e=>{let t={"db.system.name":"cassandra"};try{let n=e?.options;n?.keyspace&&(t["db.namespace"]=n.keyspace),n?.contactPoints?.[0]&&(t["server.address"]=n.contactPoints[0]),n?.protocolOptions?.port&&(t["server.port"]=n.protocolOptions.port),n?.localDataCenter&&(t["db.cassandra.local_datacenter"]=n.localDataCenter)}catch{}return t},Pr=e=>e&&e.match(/(?:FROM|INTO|UPDATE)\s+(?:(\w+)\.)?(\w+)/i)?.[2]||void 0,Ya=(e,t)=>{let n=e?.Client;if(!n?.prototype)return;let r=n.prototype;y(r,"execute","senzor.cassandra.client.execute",s=>function(o,...a){let c=q(o)||"QUERY",p=$e(this),u=Pr(o),d=a.find(C=>C&&typeof C=="object"&&!Array.isArray(C)&&typeof C!="function"),f=vr(d?.consistency),l=d?.fetchSize,h=S(`Cassandra ${c}`,"db",{...p,"db.operation.name":c,"db.query.text":v(o,t),"db.collection.name":u,"db.cassandra.consistency":f,"db.cassandra.page_size":l,library:"cassandra-driver"},t);if(!h)return s.call(this,o,...a);let m=a.length-1;if(m>=0&&typeof a[m]=="function"){let C=a[m];return a[m]=function(w,O){return w?h.end(500,{"error.message":w.message,"error.type":w.name||"Error","db.error.code":w.code}):h.end(0,{"db.response.row_count":O?.rowLength??O?.rows?.length,"db.cassandra.coordinator.id":O?.info?.queriedHost}),C.call(this,w,O)},b(h,()=>s.call(this,o,...a))}return b(h,()=>{try{let C=s.call(this,o,...a);return C&&typeof C.then=="function"?C.then(w=>(h.end(0,{"db.response.row_count":w?.rowLength??w?.rows?.length,"db.cassandra.coordinator.id":w?.info?.queriedHost}),w),w=>{throw h.end(500,{"error.message":w?.message,"error.type":w?.name||"Error","db.error.code":w?.code}),w}):(h.end(0),C)}catch(C){throw h.end(500,{"error.message":C?.message}),C}})}),y(r,"batch","senzor.cassandra.client.batch",s=>function(o,...a){let c=Array.isArray(o)?o.length:0,p=$e(this),u=a.find(m=>m&&typeof m=="object"&&!Array.isArray(m)&&typeof m!="function"),d=vr(u?.consistency),f=S(`Cassandra BATCH (${c} queries)`,"db",{...p,"db.operation.name":"BATCH","db.cassandra.batch_size":c,"db.cassandra.consistency":d,library:"cassandra-driver"},t);if(!f)return s.call(this,o,...a);let l=a.length-1;if(l>=0&&typeof a[l]=="function"){let m=a[l];return a[l]=function(g,C){return g?f.end(500,{"error.message":g.message}):f.end(0),m.call(this,g,C)},b(f,()=>s.call(this,o,...a))}return b(f,()=>{try{let m=s.call(this,o,...a);return m&&typeof m.then=="function"?m.then(g=>(f.end(0),g),g=>{throw f.end(500,{"error.message":g?.message}),g}):(f.end(0),m)}catch(m){throw f.end(500,{"error.message":m?.message}),m}})}),y(r,"eachRow","senzor.cassandra.client.eachRow",s=>function(o,...a){let c=q(o)||"SELECT",p=$e(this),u=Pr(o),d=S(`Cassandra EACHROW ${c}`,"db",{...p,"db.operation.name":`EACHROW_${c}`,"db.query.text":v(o,t),"db.collection.name":u,library:"cassandra-driver"},t);if(!d)return s.call(this,o,...a);let f=0;for(let l=a.length-1;l>=0;l--)if(typeof a[l]=="function"){let h=a[l];a[l]=function(m,g){return m?d.end(500,{"error.message":m.message}):d.end(0,{"db.response.row_count":f}),h.call(this,m,g)};for(let m=l-1;m>=0;m--)if(typeof a[m]=="function"){let g=a[m];a[m]=function(C,w){return f++,g.call(this,C,w)};break}break}return b(d,()=>s.call(this,o,...a))}),typeof r.stream=="function"&&y(r,"stream","senzor.cassandra.client.stream",s=>function(o,...a){let c=q(o)||"SELECT",p=$e(this),u=S(`Cassandra STREAM ${c}`,"db",{...p,"db.operation.name":`STREAM_${c}`,"db.query.text":v(o,t),library:"cassandra-driver"},t);return u?b(u,()=>{let d=s.call(this,o,...a);if(d&&typeof d.on=="function"){let f=0;d.on("data",()=>{f++}),d.on("end",()=>{u.end(0,{"db.response.row_count":f})}),d.on("error",l=>{u.end(500,{"error.message":l?.message})})}else u.end(0);return d}):s.call(this,o,...a)})},Ja=e=>{k("cassandra-driver",t=>{Ya(t,e)})}});var Lr={};R(Lr,{instrumentMemcached:()=>ai});var Xa,ei,ti,ni,ri,oi,si,pe,$r,ai,Ur=_(()=>{"use strict";T();A();x();Xa=["set","add","replace","append","prepend"],ei=["get","gets","del","delete","touch"],ti=["incr","decr"],ni=["cas"],ri=["getMulti"],oi=["stats","version","items","flush"],si=e=>{try{let t=e?.servers;return Array.isArray(t)&&t.length>0?t.length===1?t[0]:`${t[0]} (+${t.length-1})`:void 0}catch{return}},pe=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.memcached.${t}`,s=>function(...o){let a=t.toUpperCase(),c=si(this),p=n(o),u=S(`Memcached ${a}`,"db",{"db.system.name":"memcached","db.operation.name":a,"server.address":c,library:"memcached",...p},r);if(!u)return s.apply(this,o);let d=o.length-1;if(d>=0&&typeof o[d]=="function"){let f=o[d];o[d]=function(l,...h){return l?u.end(500,{"error.message":typeof l=="string"?l:l?.message,"error.type":l?.name||"MemcachedError"}):u.end(0),f.call(this,l,...h)}}else u.end(0);return b(u,()=>{try{return s.apply(this,o)}catch(f){throw u.end(500,{"error.message":f?.message}),f}})})},$r=(e,t)=>{let n=e?.prototype;if(n){for(let r of Xa)pe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ei)pe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ti)pe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ni)pe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ri)pe(n,r,s=>({"db.memcached.key_count":Array.isArray(s[0])?s[0].length:void 0}),t);for(let r of oi)pe(n,r,()=>({}),t)}},ai=e=>{k("memcached",t=>{$r(t,e),t?.default?.prototype&&$r(t.default,e)})}});var Dr={};R(Dr,{instrumentGenericPool:()=>ii});var be,dt,Fr,ii,Hr=_(()=>{"use strict";T();A();x();be=e=>{let t={"pool.type":"generic-pool"};try{typeof e.size<"u"&&(t["pool.size"]=e.size),typeof e.available<"u"&&(t["pool.available"]=e.available),typeof e.pending<"u"&&(t["pool.pending"]=e.pending),typeof e.borrowed<"u"&&(t["pool.borrowed"]=e.borrowed),e.max!==void 0&&(t["pool.max"]=e.max),e.min!==void 0&&(t["pool.min"]=e.min),e._config&&(t["pool.max"]===void 0&&e._config.max&&(t["pool.max"]=e._config.max),t["pool.min"]===void 0&&e._config.min&&(t["pool.min"]=e._config.min))}catch{}return t},dt=(e,t)=>{e&&(y(e,"acquire","senzor.generic-pool.pool.acquire",n=>function(...s){let i=be(this),o=S("Pool acquire","custom",{...i,"pool.operation":"acquire",library:"generic-pool"},t);return o?b(o,()=>{try{let a=n.apply(this,s);return a&&typeof a.then=="function"?a.then(c=>{let p=be(this);return o.end(0,{"pool.size_after":p["pool.size"],"pool.available_after":p["pool.available"],"pool.pending_after":p["pool.pending"]}),c},c=>{throw o.end(500,{"error.message":c?.message,"error.type":c?.name||"PoolError"}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message,"error.type":a?.name||"Error"}),a}}):n.apply(this,s)}),y(e,"release","senzor.generic-pool.pool.release",n=>function(s){let i=be(this),o=S("Pool release","custom",{...i,"pool.operation":"release",library:"generic-pool"},t);return o?b(o,()=>{try{let a=n.call(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{"error.message":c?.message}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message}),a}}):n.call(this,s)}),y(e,"destroy","senzor.generic-pool.pool.destroy",n=>function(s){let i=be(this),o=S("Pool destroy","custom",{...i,"pool.operation":"destroy",library:"generic-pool"},t);return o?b(o,()=>{try{let a=n.call(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{"error.message":c?.message}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message}),a}}):n.call(this,s)}),typeof e.drain=="function"&&y(e,"drain","senzor.generic-pool.pool.drain",n=>function(){let s=be(this),i=S("Pool drain","custom",{...s,"pool.operation":"drain",library:"generic-pool"},t);return i?b(i,()=>{try{let o=n.call(this);return o&&typeof o.then=="function"?o.then(a=>(i.end(0),a),a=>{throw i.end(500,{"error.message":a?.message}),a}):(i.end(0),o)}catch(o){throw i.end(500,{"error.message":o?.message}),o}}):n.call(this)}))},Fr=(e,t)=>{typeof e?.createPool=="function"&&y(e,"createPool","senzor.generic-pool.createPool",n=>function(s,i){let o=n.call(this,s,i);if(o&&!o.__senzorPatched){let a=Object.getPrototypeOf(o);a&&!a.__senzorPatched&&(dt(a,t),a.__senzorPatched=!0),o.__senzorPatched=!0}return o})},ii=e=>{k("generic-pool",t=>{Fr(t,e),t?.Pool?.prototype&&dt(t.Pool.prototype,e),t?.default&&(Fr(t.default,e),t.default.Pool?.prototype&&dt(t.default.Pool.prototype,e))})}});var Br={};R(Br,{instrumentRestify:()=>di});var ci,ui,Le,pi,di,Wr=_(()=>{"use strict";T();A();x();ci=["get","post","put","del","patch","head","opts"],ui={get:"GET",post:"POST",put:"PUT",del:"DELETE",patch:"PATCH",head:"HEAD",opts:"OPTIONS"},Le=(e,t,n,r,s)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let i=function(a,c,p){let u=ui[t]||t.toUpperCase(),d=n||a?.route?.path||a?.getPath?.()||a?.url?.split("?")[0]||"/",f=r==="middleware"?`Restify middleware ${e.name||"anonymous"}`:`Restify ${u} ${d}`,l=S(f,"function",{"restify.type":r,"http.route":d,"http.method":u,framework:"restify"},s);return l?b(l,()=>{let h=function(...m){if(m.length>0&&m[0]instanceof Error){let C=m[0];l.end(C?.statusCode||500,{"error.message":C.message,"error.type":C.name||"Error"})}else l.end(0);return p?.(...m)};try{let m=e.call(this,a,c,h);return m&&typeof m.then=="function"?m.then(g=>g,g=>{throw l.end(g?.statusCode||500,{"error.message":g?.message,"error.type":g?.name||"Error"}),g}):m}catch(m){throw l.end(m?.statusCode||500,{"error.message":m?.message,"error.type":m?.name||"Error"}),m}}):e.call(this,a,c,p)};return i.__senzorWrapped=!0,i},pi=(e,t)=>{let n;try{let r=e.createServer({name:"__senzor_probe"});n=Object.getPrototypeOf(r);try{r.close()}catch{}}catch{}if(n||(n=e?.Server?.prototype),!!n){for(let r of ci)typeof n[r]=="function"&&y(n,r,`senzor.restify.server.${r}`,s=>function(...o){let a="/";typeof o[0]=="string"?a=o[0]:o[0]&&typeof o[0]=="object"&&(a=o[0].path||o[0].url||"/");for(let c=0;c<o.length;c++)typeof o[c]=="function"?o[c]=Le(o[c],r,a,"route_handler",t):Array.isArray(o[c])&&(o[c]=o[c].map(p=>typeof p=="function"?Le(p,r,a,"route_handler",t):p));return s.apply(this,o)});t?.captureMiddlewareSpans!==!1&&typeof n.use=="function"&&y(n,"use","senzor.restify.server.use",r=>function(...i){for(let o=0;o<i.length;o++)typeof i[o]=="function"?i[o]=Le(i[o],"use","*","middleware",t):Array.isArray(i[o])&&(i[o]=i[o].map(a=>typeof a=="function"?Le(a,"use","*","middleware",t):a));return r.apply(this,i)})}},di=e=>{k("restify",t=>{pi(t,e)})}});var Qr={};R(Qr,{instrumentConnect:()=>li});var fi,jr,li,Kr=_(()=>{"use strict";T();A();x();fi=(e,t,n)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let r=e.name||"anonymous",s=e.length>=4,i;return s?i=function(a,c,p,u){let d=S(`Connect error ${r}`,"function",{"connect.type":"error_middleware","connect.name":r,"connect.route":t,framework:"connect"},n);return d?b(d,()=>{let f=function(...l){let h=l.length>0&&l[0]instanceof Error;return d.end(h?500:0,h?{"error.message":l[0].message}:{}),u?.(...l)};try{let l=e.call(this,a,c,p,f);return l&&typeof l.then=="function"?l.catch(h=>{throw d.end(500,{"error.message":h?.message}),h}):l}catch(l){throw d.end(500,{"error.message":l?.message}),l}}):e.call(this,a,c,p,u)}:i=function(a,c,p){let u=S(`Connect ${r}`,"function",{"connect.type":"middleware","connect.name":r,"connect.route":t,"http.route":t!=="/"?t:void 0,framework:"connect"},n);return u?b(u,()=>{let d=function(...f){let l=f.length>0&&f[0]instanceof Error;return u.end(l?500:0,l?{"error.message":f[0].message}:{}),p?.(...f)};try{let f=e.call(this,a,c,d);return f&&typeof f.then=="function"?f.catch(l=>{throw u.end(500,{"error.message":l?.message}),l}):f}catch(f){throw u.end(500,{"error.message":f?.message}),f}}):e.call(this,a,c,p)},Object.defineProperty(i,"length",{value:e.length}),i.__senzorWrapped=!0,i},jr=(e,t)=>{if(typeof e!="function")return;let n;try{let r=e();n=Object.getPrototypeOf(r)}catch{}n&&typeof n.use=="function"&&y(n,"use","senzor.connect.app.use",r=>function(...i){let o="/",a=0;typeof i[0]=="string"&&(o=i[0],a=1);for(let c=a;c<i.length;c++)typeof i[c]=="function"&&(i[c]=fi(i[c],o,t));return r.apply(this,i)})},li=e=>{k("connect",t=>{jr(t,e),t?.default&&jr(t.default,e)})}});var Zr={};R(Zr,{instrumentDataloader:()=>hi});var Gr,hi,Vr=_(()=>{"use strict";T();A();x();Gr=(e,t)=>{let n=e?.prototype;if(!n)return;y(n,"load","senzor.dataloader.load",s=>function(o){let a=this.name||this._name||"DataLoader",c=S(`${a} load`,"function",{"dataloader.operation":"load","dataloader.name":a,library:"dataloader"},t);return c?b(c,()=>{try{let p=s.call(this,o);return p&&typeof p.then=="function"?p.then(u=>(c.end(0),u),u=>{throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}):(c.end(0),p)}catch(p){throw c.end(500,{"error.message":p?.message}),p}}):s.call(this,o)}),y(n,"loadMany","senzor.dataloader.loadMany",s=>function(o){let a=this.name||this._name||"DataLoader",c=Array.isArray(o)?o.length:0,p=S(`${a} loadMany`,"function",{"dataloader.operation":"loadMany","dataloader.name":a,"dataloader.key_count":c,library:"dataloader"},t);return p?b(p,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(d=>{let f=Array.isArray(d)?d.filter(l=>l instanceof Error).length:0;return p.end(f>0?207:0,{"dataloader.key_count":c,"dataloader.error_count":f}),d},d=>{throw p.end(500,{"error.message":d?.message}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):s.call(this,o)});let r="_dispatchBatch"in n?"_dispatchBatch":"_dispatch"in n?"_dispatch":null;r&&typeof n[r]=="function"&&y(n,r,`senzor.dataloader.${r}`,s=>function(...o){let a=this.name||this._name||"DataLoader",c=this._queue?.length||this._batch?.length||0,p=S(`${a} batch dispatch`,"function",{"dataloader.operation":"batch","dataloader.name":a,"dataloader.batch_size":c,library:"dataloader"},t);return p?b(p,()=>{try{let u=s.apply(this,o);return p.end(0,{"dataloader.batch_size":c}),u}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):s.apply(this,o)}),typeof n.prime=="function"&&y(n,"prime","senzor.dataloader.prime",s=>function(o,a){let c=this.name||this._name||"DataLoader",p=S(`${c} prime`,"function",{"dataloader.operation":"prime","dataloader.name":c,library:"dataloader"},t);if(!p)return s.call(this,o,a);try{let u=s.call(this,o,a);return p.end(0),u}catch(u){throw p.end(500,{"error.message":u?.message}),u}}),typeof n.clearAll=="function"&&y(n,"clearAll","senzor.dataloader.clearAll",s=>function(){let o=this.name||this._name||"DataLoader",a=S(`${o} clearAll`,"function",{"dataloader.operation":"clearAll","dataloader.name":o,library:"dataloader"},t);if(!a)return s.call(this);try{let c=s.call(this);return a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message}),c}})},hi=e=>{k("dataloader",t=>{Gr(t,e),t?.default?.prototype&&Gr(t.default,e)})}});var Xr={};R(Xr,{instrumentLruMemoizer:()=>mi});var Yr,Jr,mi,eo=_(()=>{"use strict";T();x();Yr=(e,t,n)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let r=t||"memoized",s=function(...o){let a=S(`LRU ${r}`,"function",{"memoizer.operation":"lookup","memoizer.name":r,library:"lru-memoizer"},n);if(!a)return e.apply(this,o);let c=o.length-1;if(c>=0&&typeof o[c]=="function"){let u=o[c];return o[c]=function(d,...f){return d?a.end(500,{"error.message":typeof d=="string"?d:d?.message,"error.type":d?.name||"Error"}):a.end(0),u.call(this,d,...f)},b(a,()=>{try{return e.apply(this,o)}catch(d){throw a.end(500,{"error.message":d?.message}),d}})}return b(a,()=>{try{let u=e.apply(this,o);return u&&typeof u.then=="function"?u.then(d=>(a.end(0),d),d=>{throw a.end(500,{"error.message":d?.message}),d}):(a.end(0),u)}catch(u){throw a.end(500,{"error.message":u?.message}),u}})};for(let i of Object.keys(e))try{s[i]=e[i]}catch{}return s.__senzorWrapped=!0,s},Jr=(e,t)=>{if(typeof e!="function")return e;let n=function(s){let i=s?.load?.name||s?.name||"memoized",o=e.call(this,s);return Yr(o,i,t)};for(let r of Object.keys(e))try{n[r]=e[r]}catch{}if(typeof e.sync=="function"){let r=e.sync;n.sync=function(i){let o=i?.load?.name||i?.name||"memoized-sync",a=r.call(this,i);return Yr(a,o,t)}}return n},mi=e=>{k("lru-memoizer",t=>{if(typeof t=="function")return Jr(t,e);typeof t?.default=="function"&&(t.default=Jr(t.default,e))})}});var ro={};R(ro,{instrumentFs:()=>yi});var to,no,Fe,Ue,ft,lt,yi,oo=_(()=>{"use strict";T();A();x();to=["readFile","writeFile","appendFile","stat","lstat","access","readdir","mkdir","rmdir","unlink","chmod","chown","realpath","mkdtemp","truncate","readlink","exists"],no=["rename","copyFile","link","symlink"],Fe=e=>{if(typeof e!="string"&&!(e instanceof Buffer)&&!(e instanceof URL))return;let t=String(e);return t.length>200?t.slice(0,200)+"...":t},Ue=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.${t}`,s=>function(...o){let a=t.toUpperCase(),c=Fe(o[0]),p={"fs.operation":t,"fs.path":c,library:"fs"};n===2&&o[1]&&(p["fs.destination"]=Fe(o[1]));let u=S(`FS ${a}`,"custom",p,r);if(!u)return s.apply(this,o);let d=o.findIndex((f,l)=>l>=n&&typeof f=="function");if(d>=0){let f=o[d];o[d]=function(l,...h){return l?u.end(500,{"error.message":l.message,"error.type":l.name||"Error","error.code":l.code}):u.end(0),f.call(this,l,...h)}}return b(u,()=>{try{let f=s.apply(this,o);return d<0&&u.end(0),f}catch(f){throw u.end(500,{"error.message":f?.message,"error.code":f?.code}),f}})})},ft=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.promises.${t}`,s=>function(...o){let a=t.toUpperCase(),c=Fe(o[0]),p={"fs.operation":t,"fs.path":c,"fs.api":"promises",library:"fs"};n===2&&o[1]&&(p["fs.destination"]=Fe(o[1]));let u=S(`FS ${a}`,"custom",p,r);return u?b(u,()=>{try{let d=s.apply(this,o);return d&&typeof d.then=="function"?d.then(f=>(u.end(0),f),f=>{throw u.end(500,{"error.message":f?.message,"error.code":f?.code}),f}):(u.end(0),d)}catch(d){throw u.end(500,{"error.message":d?.message}),d}}):s.apply(this,o)})},lt=(e,t)=>{if(!e)return;for(let r of to)Ue(e,r,1,t);for(let r of no)Ue(e,r,2,t);Ue(e,"open",1,t),Ue(e,"close",1,t);let n=e.promises;if(n){for(let r of to)r!=="exists"&&ft(n,r,1,t);for(let r of no)ft(n,r,2,t);ft(n,"open",1,t)}},yi=e=>{try{let t=M("fs");lt(t,e)}catch{}k("fs",t=>{lt(t,e)}),k("node:fs",t=>{lt(t,e)})}});var io={};R(io,{instrumentOpenAI:()=>bi});var gi,so,ao,Si,bi,co=_(()=>{"use strict";T();A();x();gi={"chat/completions":"chat",completions:"completions",embeddings:"embeddings",images:"images","images/generations":"images.generate","images/edits":"images.edit","images/variations":"images.variation","audio/transcriptions":"audio.transcribe","audio/translations":"audio.translate","audio/speech":"audio.speech",moderations:"moderations","fine_tuning/jobs":"fine_tuning",files:"files",assistants:"assistants",threads:"threads","threads/runs":"threads.runs","threads/messages":"threads.messages",batches:"batches",vector_stores:"vector_stores"},so=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"").replace(/\/[a-f0-9-]{20,}(\/|$)/g,"/");for(let[n,r]of Object.entries(gi))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},ao=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},Si=(e,t)=>{let n=e?.OpenAI||e?.default||e;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.openai.client.${i}`,o=>function(c,p){let u=so(c),d=ao(p?.body),f=i.toUpperCase(),l=d?`OpenAI ${u} ${d}`:`OpenAI ${u}`,h=S(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":u,"gen_ai.request.model":d,"gen_ai.request.max_tokens":p?.body?.max_tokens,"gen_ai.request.temperature":p?.body?.temperature,"http.request.method":f,"url.path":c,library:"openai"},t);return h?b(h,()=>{try{let m=o.call(this,c,p);return m&&typeof m.then=="function"?m.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.prompt_tokens,C["gen_ai.usage.output_tokens"]=g.usage.completion_tokens,C["gen_ai.usage.total_tokens"]=g.usage.total_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),g?.choices?.[0]?.finish_reason&&(C["gen_ai.response.finish_reason"]=g.choices[0].finish_reason),h.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw h.end(C,{"error.message":g?.message,"error.type":g?.name||g?.type||"OpenAIError","http.response.status_code":C,"gen_ai.error.code":g?.code}),g}):(h.end(0),m)}catch(m){let g=m?.status||500;throw h.end(g,{"error.message":m?.message,"error.type":m?.name||"Error","http.response.status_code":g}),m}}):o.call(this,c,p)});typeof r._request=="function"&&y(r,"_request","senzor.openai.client._request",i=>function(a,...c){let p=a?.path||"",u=a?.method||"POST",d=so(p),f=ao(a?.body),l=f?`OpenAI ${d} ${f}`:`OpenAI ${d}`,h=S(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":u,"url.path":p,library:"openai"},t);return h?b(h,()=>{try{let m=i.call(this,a,...c);return m&&typeof m.then=="function"?m.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.prompt_tokens,C["gen_ai.usage.output_tokens"]=g.usage.completion_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),h.end(0,C),g},g=>{throw h.end(g?.status||500,{"error.message":g?.message,"error.type":g?.name||"OpenAIError"}),g}):(h.end(0),m)}catch(m){throw h.end(500,{"error.message":m?.message}),m}}):i.call(this,a,...c)})},bi=e=>{k("openai",t=>{Si(t,e)})}});var fo={};R(fo,{instrumentAnthropic:()=>_i});var ki,uo,po,Ci,_i,lo=_(()=>{"use strict";T();A();x();ki={messages:"messages","messages/batches":"messages.batches",completions:"completions"},uo=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"");for(let[n,r]of Object.entries(ki))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},po=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},Ci=(e,t)=>{let n=e?.Anthropic||e?.default||e;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.anthropic.client.${i}`,o=>function(c,p){let u=uo(c),d=po(p?.body),f=i.toUpperCase(),l=d?`Anthropic ${u} ${d}`:`Anthropic ${u}`,h=S(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":u,"gen_ai.request.model":d,"gen_ai.request.max_tokens":p?.body?.max_tokens,"gen_ai.request.temperature":p?.body?.temperature,"gen_ai.request.top_p":p?.body?.top_p,"http.request.method":f,"url.path":c,library:"anthropic"},t);return h?b(h,()=>{try{let m=o.call(this,c,p);return m&&typeof m.then=="function"?m.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.input_tokens,C["gen_ai.usage.output_tokens"]=g.usage.output_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),g?.stop_reason&&(C["gen_ai.response.stop_reason"]=g.stop_reason),h.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw h.end(C,{"error.message":g?.message,"error.type":g?.name||g?.type||"AnthropicError","http.response.status_code":C,"gen_ai.error.code":g?.error?.type}),g}):(h.end(0),m)}catch(m){throw h.end(m?.status||500,{"error.message":m?.message,"error.type":m?.name||"Error"}),m}}):o.call(this,c,p)});typeof r._request=="function"&&y(r,"_request","senzor.anthropic.client._request",i=>function(a,...c){let p=a?.path||"",u=a?.method||"POST",d=uo(p),f=po(a?.body),l=f?`Anthropic ${d} ${f}`:`Anthropic ${d}`,h=S(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":u,"url.path":p,library:"anthropic"},t);return h?b(h,()=>{try{let m=i.call(this,a,...c);return m&&typeof m.then=="function"?m.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.input_tokens,C["gen_ai.usage.output_tokens"]=g.usage.output_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),h.end(0,C),g},g=>{throw h.end(g?.status||500,{"error.message":g?.message}),g}):(h.end(0),m)}catch(m){throw h.end(500,{"error.message":m?.message}),m}}):i.call(this,a,...c)})},_i=e=>{k("@anthropic-ai/sdk",t=>{Ci(t,e)})}});var mo={};R(mo,{instrumentGoogleGenAI:()=>zi});var ho,ht,wi,Ei,zi,yo=_(()=>{"use strict";T();A();x();ho=e=>{let t={},n=e?.usageMetadata;n&&(n.promptTokenCount!==void 0&&(t["gen_ai.usage.input_tokens"]=n.promptTokenCount),n.candidatesTokenCount!==void 0&&(t["gen_ai.usage.output_tokens"]=n.candidatesTokenCount),n.totalTokenCount!==void 0&&(t["gen_ai.usage.total_tokens"]=n.totalTokenCount));let r=e?.candidates?.[0]?.finishReason;return r&&(t["gen_ai.response.finish_reason"]=r),t},ht=e=>{let t=e?.response||e;return ho(t)},wi=(e,t)=>{let n=e?.GenerativeModel;if(n?.prototype){let s=n.prototype;y(s,"generateContent","senzor.google-genai.generateContent",i=>function(a){let c=this.model||this.modelName||"unknown",p=S(`Gemini generateContent ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"generateContent","gen_ai.request.model":c,"gen_ai.request.temperature":this.generationConfig?.temperature,"gen_ai.request.max_tokens":this.generationConfig?.maxOutputTokens,"gen_ai.request.top_p":this.generationConfig?.topP,library:"google-genai"},t);return p?b(p,()=>{try{let u=i.call(this,a);return u&&typeof u.then=="function"?u.then(d=>(p.end(0,ht(d)),d),d=>{throw p.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"GoogleGenAIError"}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):i.call(this,a)}),typeof s.generateContentStream=="function"&&y(s,"generateContentStream","senzor.google-genai.generateContentStream",i=>function(a){let c=this.model||this.modelName||"unknown",p=S(`Gemini generateContentStream ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"generateContentStream","gen_ai.request.model":c,library:"google-genai"},t);return p?b(p,()=>{try{let u=i.call(this,a);return u&&typeof u.then=="function"?u.then(d=>(d?.response&&typeof d.response.then=="function"?d.response.then(f=>p.end(0,ho(f)),()=>p.end(0)):p.end(0),d),d=>{throw p.end(d?.status||500,{"error.message":d?.message}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):i.call(this,a)}),typeof s.countTokens=="function"&&y(s,"countTokens","senzor.google-genai.countTokens",i=>function(a){let c=this.model||this.modelName||"unknown",p=S(`Gemini countTokens ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"countTokens","gen_ai.request.model":c,library:"google-genai"},t);return p?b(p,()=>{try{let u=i.call(this,a);return u&&typeof u.then=="function"?u.then(d=>(p.end(0,{"gen_ai.usage.total_tokens":d?.totalTokens}),d),d=>{throw p.end(500,{"error.message":d?.message}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):i.call(this,a)}),typeof s.embedContent=="function"&&y(s,"embedContent","senzor.google-genai.embedContent",i=>function(a){let c=this.model||this.modelName||"unknown",p=S(`Gemini embedContent ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"embedContent","gen_ai.request.model":c,library:"google-genai"},t);return p?b(p,()=>{try{let u=i.call(this,a);return u&&typeof u.then=="function"?u.then(d=>(p.end(0),d),d=>{throw p.end(500,{"error.message":d?.message}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):i.call(this,a)})}let r=e?.ChatSession;if(r?.prototype){let s=r.prototype;for(let i of["sendMessage","sendMessageStream"])typeof s[i]=="function"&&y(s,i,`senzor.google-genai.chat.${i}`,o=>function(...c){let p=this.model||this._model||"unknown",u=i==="sendMessageStream",d=S(`Gemini chat.${i} ${p}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":u?"chat.stream":"chat","gen_ai.request.model":p,library:"google-genai"},t);return d?b(d,()=>{try{let f=o.apply(this,c);return f&&typeof f.then=="function"?f.then(l=>(d.end(0,ht(l)),l),l=>{throw d.end(500,{"error.message":l?.message}),l}):(d.end(0),f)}catch(f){throw d.end(500,{"error.message":f?.message}),f}}):o.apply(this,c)})}},Ei=(e,t)=>{let n=e?.GenerativeModel;if(!n?.prototype)return;let r=n.prototype;for(let s of["generateContent","generateContentStream"])typeof r[s]=="function"&&y(r,s,`senzor.vertexai.${s}`,i=>function(a){let c=this.model||this.modelName||"unknown",p=S(`VertexAI ${s} ${c}`,"http",{"gen_ai.system":"vertex_ai","gen_ai.operation.name":s,"gen_ai.request.model":c,library:"vertex-ai"},t);return p?b(p,()=>{try{let u=i.call(this,a);return u&&typeof u.then=="function"?u.then(d=>(p.end(0,ht(d)),d),d=>{throw p.end(500,{"error.message":d?.message}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):i.call(this,a)})},zi=e=>{k("@google/generative-ai",t=>{wi(t,e)}),k("@google-cloud/vertexai",t=>{Ei(t,e)})}});var go={};R(go,{instrumentAzureOpenAI:()=>Ti});var Ri,Ai,Ti,So=_(()=>{"use strict";T();A();x();Ri=[{name:"getChatCompletions",operation:"chat",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens),e?.choices?.[0]?.finishReason&&(t["gen_ai.response.finish_reason"]=e.choices[0].finishReason),e?.model&&(t["gen_ai.response.model"]=e.model),t}},{name:"getCompletions",operation:"completions",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens),e?.choices?.[0]?.finishReason&&(t["gen_ai.response.finish_reason"]=e.choices[0].finishReason),t}},{name:"getEmbeddings",operation:"embeddings",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens),t}},{name:"getImages",operation:"images",extractUsage:()=>({})},{name:"getAudioTranscription",operation:"audio.transcribe",extractUsage:()=>({})},{name:"getAudioTranslation",operation:"audio.translate",extractUsage:()=>({})}],Ai=(e,t)=>{let n=e?.OpenAIClient;if(!n?.prototype)return;let r=n.prototype;for(let s of Ri)typeof r[s.name]=="function"&&y(r,s.name,`senzor.azure-openai.${s.name}`,i=>function(a,...c){let p=S(`Azure OpenAI ${s.operation} ${a}`,"http",{"gen_ai.system":"azure_openai","gen_ai.operation.name":s.operation,"gen_ai.request.model":a,"cloud.provider":"azure",library:"azure-openai"},t);return p?b(p,()=>{try{let u=i.call(this,a,...c);return u&&typeof u.then=="function"?u.then(d=>(p.end(0,s.extractUsage(d)),d),d=>{throw p.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"AzureOpenAIError"}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):i.call(this,a,...c)})},Ti=e=>{k("@azure/openai",t=>{Ai(t,e)})}});var bo={};R(bo,{instrumentCohere:()=>Oi});var xi,mt,Oi,ko=_(()=>{"use strict";T();A();x();xi=[{name:"chat",operation:"chat",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),e?.meta?.tokens&&(t["gen_ai.usage.input_tokens"]=t["gen_ai.usage.input_tokens"]||e.meta.tokens.inputTokens,t["gen_ai.usage.output_tokens"]=t["gen_ai.usage.output_tokens"]||e.meta.tokens.outputTokens),(e?.finishReason||e?.finish_reason)&&(t["gen_ai.response.finish_reason"]=e.finishReason||e.finish_reason),t}},{name:"chatStream",operation:"chat.stream",getModel:e=>e[0]?.model,extractUsage:()=>({})},{name:"generate",operation:"generate",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),t}},{name:"embed",operation:"embed",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens),t}},{name:"rerank",operation:"rerank",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.searchUnits),t["cohere.results_count"]=e?.results?.length,t}},{name:"classify",operation:"classify",getModel:e=>e[0]?.model,extractUsage:()=>({})},{name:"summarize",operation:"summarize",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),t}},{name:"tokenize",operation:"tokenize",getModel:e=>e[0]?.model,extractUsage:e=>({"cohere.token_count":e?.tokens?.length})},{name:"detokenize",operation:"detokenize",getModel:e=>e[0]?.model,extractUsage:()=>({})}],mt=(e,t,n)=>{if(e)for(let r of xi)typeof e[r.name]=="function"&&y(e,r.name,`senzor.cohere.${t}.${r.name}`,s=>function(...o){let a=r.getModel(o),c=a?`Cohere ${r.operation} ${a}`:`Cohere ${r.operation}`,p=S(c,"http",{"gen_ai.system":"cohere","gen_ai.operation.name":r.operation,"gen_ai.request.model":a,library:"cohere"},n);return p?b(p,()=>{try{let u=s.apply(this,o);return u&&typeof u.then=="function"?u.then(d=>(p.end(0,r.extractUsage(d)),d),d=>{throw p.end(d?.statusCode||d?.status||500,{"error.message":d?.message,"error.type":d?.name||"CohereError"}),d}):(p.end(0),u)}catch(u){throw p.end(500,{"error.message":u?.message}),u}}):s.apply(this,o)})},Oi=e=>{k("cohere-ai",t=>{t?.CohereClient?.prototype&&mt(t.CohereClient.prototype,"client",e),t?.CohereClientV2?.prototype&&mt(t.CohereClientV2.prototype,"clientV2",e),t?.default?.prototype&&mt(t.default.prototype,"default",e)})}});var Co={};R(Co,{instrumentMistral:()=>Ii});var De,ke,Mi,Ii,_o=_(()=>{"use strict";T();A();x();De=e=>{let t={};e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens??e.usage.prompt_tokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens??e.usage.completion_tokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens??e.usage.total_tokens),e?.model&&(t["gen_ai.response.model"]=e.model);let n=e?.choices?.[0]?.finishReason??e?.choices?.[0]?.finish_reason;return n&&(t["gen_ai.response.finish_reason"]=n),t},ke=(e,t,n,r,s,i,o)=>{!e||typeof e[t]!="function"||y(e,t,i,a=>function(...p){let u=r(p),d=u?`Mistral ${n} ${u}`:`Mistral ${n}`,f=S(d,"http",{"gen_ai.system":"mistral","gen_ai.operation.name":n,"gen_ai.request.model":u,library:"mistral"},o);return f?b(f,()=>{try{let l=a.apply(this,p);return l&&typeof l.then=="function"?l.then(h=>(f.end(0,s(h)),h),h=>{throw f.end(h?.statusCode||h?.status||500,{"error.message":h?.message,"error.type":h?.name||"MistralError"}),h}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):a.apply(this,p)})},Mi=(e,t)=>{let n=e?.Mistral||e?.MistralClient||e?.default;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.mistral.client.${i}`,o=>function(c,...p){let d=(p[0]?.body||p[0])?.model,f=c?.replace(/^\/?(v1\/)?/,"").split("/")[0]||"api",l=d?`Mistral ${f} ${d}`:`Mistral ${f}`,h=S(l,"http",{"gen_ai.system":"mistral","gen_ai.operation.name":f,"gen_ai.request.model":d,"http.request.method":i.toUpperCase(),"url.path":c,library:"mistral"},t);return h?b(h,()=>{try{let m=o.call(this,c,...p);return m&&typeof m.then=="function"?m.then(g=>(h.end(0,De(g)),g),g=>{throw h.end(g?.status||500,{"error.message":g?.message}),g}):(h.end(0),m)}catch(m){throw h.end(500,{"error.message":m?.message}),m}}):o.call(this,c,...p)});try{let i=new n({apiKey:"__senzor_probe__"});if(i.chat){let o=Object.getPrototypeOf(i.chat);o&&(ke(o,"complete","chat",a=>a[0]?.model,De,"senzor.mistral.chat.complete",t),ke(o,"stream","chat.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.chat.stream",t))}if(i.embeddings){let o=Object.getPrototypeOf(i.embeddings);o&&ke(o,"create","embeddings",a=>a[0]?.model,De,"senzor.mistral.embeddings.create",t)}if(i.fim){let o=Object.getPrototypeOf(i.fim);o&&(ke(o,"complete","fim",a=>a[0]?.model,De,"senzor.mistral.fim.complete",t),ke(o,"stream","fim.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.fim.stream",t))}}catch{}},Ii=e=>{k("@mistralai/mistralai",t=>{Mi(t,e)})}});var Eo={};R(Eo,{instrumentFirebase:()=>$i});var D,$,B,wo,vi,Pi,qi,Ni,$i,zo=_(()=>{"use strict";T();A();x();D=(e,t,n,r,s)=>{!e||typeof e[t]!="function"||y(e,t,r,i=>function(...a){let{name:c,meta:p}=n(this,a),u=S(c,"db",p,s);return u?b(u,()=>{try{let d=i.apply(this,a);return d&&typeof d.then=="function"?d.then(f=>{let l={};return f?.exists!==void 0&&(l["firestore.exists"]=f.exists),f?.size!==void 0&&(l["db.response.row_count"]=f.size),u.end(0,l),f},f=>{throw u.end(f?.code||500,{"error.message":f?.message,"error.type":f?.name||"FirestoreError","db.error.code":f?.code}),f}):(u.end(0),d)}catch(d){throw u.end(500,{"error.message":d?.message}),d}}):i.apply(this,a)})},$=e=>{try{return e?.path||e?._path?.toString()||"unknown"}catch{return"unknown"}},B=e=>{try{return e?.parent?.id?e.parent.id:e?.id?e.id:e?._query?._path?e._query._path.toString().split("/").pop()||"unknown":$(e).split("/").filter(Boolean).slice(-2,-1)[0]||"unknown"}catch{return"unknown"}},wo=(e,t)=>{let n=e?.DocumentReference;if(n?.prototype){let a=n.prototype;D(a,"get",c=>({name:`Firestore GET ${$(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"GET","db.collection.name":B(c),"firestore.path":$(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.get",t),D(a,"set",c=>({name:`Firestore SET ${$(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"SET","db.collection.name":B(c),"firestore.path":$(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.set",t),D(a,"update",c=>({name:`Firestore UPDATE ${$(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"UPDATE","db.collection.name":B(c),"firestore.path":$(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.update",t),D(a,"delete",c=>({name:`Firestore DELETE ${$(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"DELETE","db.collection.name":B(c),"firestore.path":$(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.delete",t),typeof a.create=="function"&&D(a,"create",c=>({name:`Firestore CREATE ${$(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"CREATE","db.collection.name":B(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.create",t)}let r=e?.CollectionReference;r?.prototype&&(D(r.prototype,"add",a=>({name:`Firestore ADD ${$(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"ADD","db.collection.name":B(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.colRef.add",t),typeof r.prototype.listDocuments=="function"&&D(r.prototype,"listDocuments",a=>({name:`Firestore LIST ${$(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"LIST","db.collection.name":B(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.colRef.listDocuments",t));let s=e?.Query;s?.prototype&&D(s.prototype,"get",a=>({name:`Firestore QUERY ${B(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"QUERY","db.collection.name":B(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.query.get",t);let i=e?.Transaction;if(i?.prototype)for(let a of["get","set","update","delete","create"])typeof i.prototype[a]=="function"&&a==="get"&&D(i.prototype,"get",(c,p)=>({name:`Firestore TX GET ${$(p[0])}`,meta:{"db.system.name":"firestore","db.operation.name":"TX_GET","firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.transaction.get",t);let o=e?.WriteBatch;o?.prototype&&typeof o.prototype.commit=="function"&&D(o.prototype,"commit",()=>({name:"Firestore BATCH COMMIT",meta:{"db.system.name":"firestore","db.operation.name":"BATCH_COMMIT","firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.writeBatch.commit",t)},vi=["createUser","getUser","getUserByEmail","getUserByPhoneNumber","listUsers","deleteUser","deleteUsers","updateUser","verifyIdToken","verifySessionCookie","createSessionCookie","revokeRefreshTokens","setCustomUserClaims","generateEmailVerificationLink","generatePasswordResetLink","generateSignInWithEmailLink"],Pi=(e,t)=>{let n=e?.Auth;if(n?.prototype)for(let r of vi)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.auth.${r}`,s=>function(...o){let a=S(`Firebase Auth ${r}`,"function",{"firebase.service":"auth","firebase.operation":r,library:"firebase-admin"},t);return a?b(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(p=>(a.end(0),p),p=>{throw a.end(500,{"error.message":p?.message,"error.type":p?.code||p?.name||"AuthError"}),p}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},qi=["send","sendEach","sendEachForMulticast","sendMulticast","sendToDevice","sendToTopic","sendToCondition","subscribeToTopic","unsubscribeFromTopic"],Ni=(e,t)=>{let n=e?.Messaging;if(n?.prototype)for(let r of qi)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.messaging.${r}`,s=>function(...o){let a=S(`Firebase FCM ${r}`,"messaging",{"firebase.service":"messaging","firebase.operation":r,"messaging.system":"fcm",library:"firebase-admin"},t);return a?b(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(p=>{let u={};return p?.successCount!==void 0&&(u["firebase.fcm.success_count"]=p.successCount,u["firebase.fcm.failure_count"]=p.failureCount),a.end(0,u),p},p=>{throw a.end(500,{"error.message":p?.message}),p}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},$i=e=>{k("firebase-admin/firestore",t=>{wo(t,e)}),k("@google-cloud/firestore",t=>{wo(t,e)}),k("firebase-admin/auth",t=>{Pi(t,e)}),k("firebase-admin/messaging",t=>{Ni(t,e)}),k("firebase-admin",t=>{try{let n=t?.firestore}catch{}})}});Ce();var _e=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.runtimeMetricsQueue=[];this.taskQueue=[];this.taskErrorQueue=[];this.taskLogQueue=[];this.timer=null;this.timerStarted=!1;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`}ensureTimer(){if(!this.timerStarted){this.timerStarted=!0;try{typeof setInterval<"u"&&(this.timer=setInterval(()=>{this.flush()},this.config.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}catch{}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()}addRuntimeMetrics(t){this.enqueue(this.runtimeMetricsQueue,t)}enqueue(t,n){this.ensureTimer(),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.runtimeMetricsQueue.length>0&&(t.runtimeMetrics=this.runtimeMetricsQueue,this.runtimeMetricsQueue=[]),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),t.runtimeMetrics&&this.prependWithLimit(this.runtimeMetricsQueue,t.runtimeMetrics)}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||(t.runtimeMetrics?.length??0)>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,n){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.flushTimeoutMs??5e3);typeof s.unref=="function"&&s.unref();try{let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[K]:"true"},body:JSON.stringify(n),keepalive:!0,signal:r.signal});if(!i.ok)throw new Error(`Senzor ingest failed with status ${i.status}`)}finally{clearTimeout(s)}}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(o=>{throw this.restoreApmPayload(t),o})),this.hasTaskPayload(n)&&r.push(this.postJson(this.taskEndpoint,n).catch(o=>{throw this.restoreTaskPayload(n),o})),!r.length)continue;let i=(await Promise.allSettled(r)).filter(o=>o.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=${i.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)}};N();var kt=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",W=()=>kt;var I=e=>{if(kt)return process.env[e]};var je={name:"@senzops/apm-node",version:"1.3.1",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"},"./lambda-handler":{types:"./dist/lambda-handler.d.ts",require:"./dist/lambda-handler.js",import:"./dist/lambda-handler.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 Qe={name:je.name,version:je.version};G();Ke();H();x();var Ho={1:"minorCount",2:"majorCount",4:"incrementalCount",8:"weakCallbackCount"},Ve=class{constructor(){this.stats={totalDurationMs:0,totalCount:0,majorCount:0,minorCount:0,incrementalCount:0,weakCallbackCount:0};this.observer=null}start(){try{let{PerformanceObserver:t}=M("perf_hooks");this.observer=new t(n=>{for(let r of n.getEntries()){this.stats.totalDurationMs+=r.duration,this.stats.totalCount++;let s=Ho[r.detail?.kind??r.kind];s&&this.stats[s]++}}),this.observer.observe({type:"gc",buffered:!0})}catch{}}take(){let t={...this.stats};return this.stats={totalDurationMs:0,totalCount:0,majorCount:0,minorCount:0,incrementalCount:0,weakCallbackCount:0},t}stop(){try{this.observer?.disconnect()}catch{}this.observer=null}},Ye=class{constructor(){this.lastCheck=0;this.lagMs=0;this.timer=null;this.monitoringHistogram=null}start(){this.lastCheck=performance.now(),this.scheduleSample();try{let{monitorEventLoopDelay:t}=M("perf_hooks");this.monitoringHistogram=t({resolution:20}),this.monitoringHistogram.enable()}catch{}}scheduleSample(){this.timer=setTimeout(()=>{let t=performance.now(),n=t-this.lastCheck;this.lagMs=Math.max(0,n-100),this.lastCheck=t,this.scheduleSample()},100),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()}take(){let t={lagMs:Math.round(this.lagMs*100)/100};if(this.monitoringHistogram)try{t.lagP50Ms=Math.round(this.monitoringHistogram.percentile(50)/1e6*100)/100,t.lagP99Ms=Math.round(this.monitoringHistogram.percentile(99)/1e6*100)/100,this.monitoringHistogram.reset()}catch{}return t}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null);try{this.monitoringHistogram?.disable()}catch{}}},Je=class{constructor(){this.elu1=null;this.getELU=null}start(){try{let{performance:t}=M("perf_hooks");typeof t.eventLoopUtilization=="function"&&(this.getELU=()=>t.eventLoopUtilization(),this.elu1=this.getELU())}catch{}}take(){if(!(!this.getELU||!this.elu1))try{let t=this.getELU(),{performance:n}=M("perf_hooks"),r=n.eventLoopUtilization(this.elu1,t);return this.elu1=t,Math.round(r.utilization*1e4)/100}catch{return}}},ze=class{constructor(t){this.gcObserver=new Ve;this.lagMeter=new Ye;this.eluMeter=new Je;this.timer=null;this.started=!1;this.interval=t.interval||15e3,this.onMetrics=t.onMetrics}start(){if(!(!W()||this.started)){this.started=!0,this.gcObserver.start(),this.lagMeter.start(),this.eluMeter.start();try{this.lastCpu=process.cpuUsage()}catch{}this.timer=setInterval(()=>{try{this.collect()}catch{}},this.interval),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()}}collect(){let t=process.memoryUsage(),n=this.gcObserver.take(),r=this.lagMeter.take(),s=this.eluMeter.take(),i=0,o=0;try{if(this.lastCpu){let u=process.cpuUsage(this.lastCpu);i=u.user,o=u.system}this.lastCpu=process.cpuUsage()}catch{}let a=0,c=0;try{a=process._getActiveHandles?.()?.length??0,c=process._getActiveRequests?.()?.length??0}catch{}let p={eventLoop:{lagMs:r.lagMs,lagP50Ms:r.lagP50Ms,lagP99Ms:r.lagP99Ms,utilizationPercent:s},gc:n,memory:{heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers||0,rssBytes:t.rss,heapUsedPercent:t.heapTotal>0?Math.round(t.heapUsed/t.heapTotal*1e4)/100:0},process:{activeHandles:a,activeRequests:c,cpuUserUs:i,cpuSystemUs:o,uptimeSeconds:Math.floor(process.uptime())}};this.onMetrics({timestamp:new Date().toISOString(),metrics:p})}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.gcObserver.stop(),this.lagMeter.stop(),this.started=!1}};var Li=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})},yt=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1;this.runtimeMetricsCollector=null}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 _e({...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}=(tt(),z(et));r(t,this.options||void 0)}}catch{}if(W()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(tt(),z(et));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(Bt(),z(Ht));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(Zt(),z(Gt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(en(),z(Xt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(nn(),z(tn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(an(),z(sn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(fn(),z(dn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(hn(),z(ln));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(gn(),z(yn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(bn(),z(Sn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(wn(),z(_n));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=(An(),z(Rn));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("grpc")){let{instrumentGrpc:r}=(In(),z(Mn));r(this,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("graphql")){let{instrumentGraphQL:r}=($n(),z(Nn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dns")){let{instrumentDns:r}=(Un(),z(Ln));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("net")){let{instrumentNet:r}=(Dn(),z(Fn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("kafka")){let{instrumentKafka:r}=(Gn(),z(Kn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("amqplib")){let{instrumentAmqplib:r}=(tr(),z(er));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("socketio")){let{instrumentSocketIO:r}=(or(),z(rr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("nestjs")){let{instrumentNestJS:r}=(ir(),z(ar));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("hapi")){let{instrumentHapi:r}=(fr(),z(dr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pino")){let{instrumentPino:r}=(mr(),z(hr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("winston")){let{instrumentWinston:r}=(br(),z(Sr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bunyan")){let{instrumentBunyan:r}=(_r(),z(Cr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("aws-sdk")){let{instrumentAwsSdk:r}=(Rr(),z(zr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("knex")){let{instrumentKnex:r}=(Or(),z(xr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("tedious")){let{instrumentTedious:r}=(Ir(),z(Mr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cassandra")){let{instrumentCassandra:r}=(Nr(),z(qr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("memcached")){let{instrumentMemcached:r}=(Ur(),z(Lr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("generic-pool")){let{instrumentGenericPool:r}=(Hr(),z(Dr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("restify")){let{instrumentRestify:r}=(Wr(),z(Br));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("connect")){let{instrumentConnect:r}=(Kr(),z(Qr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dataloader")){let{instrumentDataloader:r}=(Vr(),z(Zr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("lru-memoizer")){let{instrumentLruMemoizer:r}=(eo(),z(Xr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fs")){let{instrumentFs:r}=(oo(),z(ro));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("openai")){let{instrumentOpenAI:r}=(co(),z(io));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("anthropic")){let{instrumentAnthropic:r}=(lo(),z(fo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("google-genai")){let{instrumentGoogleGenAI:r}=(yo(),z(mo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("azure-openai")){let{instrumentAzureOpenAI:r}=(So(),z(go));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cohere")){let{instrumentCohere:r}=(ko(),z(bo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mistral")){let{instrumentMistral:r}=(_o(),z(Co));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("firebase")){let{instrumentFirebase:r}=(zo(),z(Eo));r(this.options||void 0)}}catch{}if(this.options?.runtimeMetrics!==!1&&this.transport)try{this.runtimeMetricsCollector=new ze({interval:this.options?.runtimeMetricsInterval??15e3,onMetrics:r=>{this.transport?.addRuntimeMetrics(r)}}),this.runtimeMetricsCollector.start()}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(s=>{console[s]=(...i)=>{if(n[s].apply(console,i),!(r||!this.transport)){r=!0;try{let o="",a={};i.forEach(d=>{if(typeof d=="string")o+=(o?" ":"")+d;else if(d instanceof Error)o+=(o?" ":"")+d.message,a.errorStack=d.stack,a.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(Li(d));a={...a,...J(f,this.options||void 0)}}catch{a.unparseableObject=!0}else o+=(o?" ":"")+String(d)}),!o&&Object.keys(a).length>0&&(o="Object Log");let c=E.current(),p=c?.contextType==="task"?"task":"apm",u={message:o||"Empty log",level:s==="log"?"info":s,attributes:a,timestamp:new Date().toISOString()};c&&(p==="task"?u.runId=c.id:u.traceId=c.id),this.transport.addLog(u,p)}catch{}finally{r=!1}}}})}setupGlobalErrorHandlers(){if(!W()||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 s=process.memoryUsage();return{rss:s.rss,heapTotal:s.heapTotal,heapUsed:s.heapUsed,external:s.external,arrayBuffers:s.arrayBuffers}}catch{return{}}},r=(s,i={})=>{try{let o;if(s instanceof Error)o=s;else if(typeof s=="string")o=new Error(s);else try{o=new Error(JSON.stringify(s))}catch{o=new Error("Non-serializable rejection reason")}let a={...i,runtime:{name:"node",version:process.version},process:t(),memory:n(),sdk:{name:Qe.name,version:Qe.version}};this.captureError(o,a)}catch(o){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",o)}catch{}}};process.on("uncaughtExceptionMonitor",s=>r(s,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",s=>r(s,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",s=>r(s,{type:"unhandledRejection",severity:"error"})),process.on("warning",s=>r(s,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(s,i,o)=>r(o||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:s,severity:"warning"})),process.on("rejectionHandled",s=>{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=E.current();if(r?.contextType==="apm")return Object.assign(r.data,t),n();let s,i;if(t.headers){let p=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},u=p("traceparent"),d=j(u);if(d)s=d.traceId,i=d.parentSpanId;else{let f=p("x-senzor-trace-id"),l=p("x-senzor-parent-span-id");s=Array.isArray(f)?f[0]:f,i=Array.isArray(l)?l[0]:l}}let o=s||Ee(),a=he(),c={id:o,contextType:"apm",startTime:performance.now(),rootSpanId:a,activeSpanId:a,data:{...t,parentTraceId:s,parentSpanId:i,rootSpanId:a},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return E.run(c,n)}endTrace(t,n={}){let r=E.current();if(!r||r.contextType!=="apm"||!this.transport||r.state.ended)return;r.state.ended=!0;let s=performance.now()-r.startTime,i={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,rootSpanId:r.rootSpanId,...r.data,...n,status:t,duration:s,spans:r.spans,droppedSpans:r.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(i)}startTask(t,n,r,s){if(!this.transport)return s();let i=E.current(),o=i?.contextType==="apm"?i.id:void 0,a=W()&&process.memoryUsage?process.memoryUsage().heapUsed:0,c=W()&&process.cpuUsage?process.cpuUsage():void 0,p={id:Ee(),contextType:"task",startTime:performance.now(),rootSpanId:he(),startMemory:a,startCpu:c,data:{taskName:t,taskType:n,triggerTraceId:o,...r},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return p.activeSpanId=p.rootSpanId,E.run(p,s)}endTask(t,n={}){let r=E.current();if(!r||r.contextType!=="task"||!this.transport||r.state.ended)return;r.state.ended=!0;let s;if(W()&&process.memoryUsage&&r.startMemory!==void 0&&process.cpuUsage&&r.startCpu){let o=process.memoryUsage().heapUsed,a=process.cpuUsage(r.startCpu);s={memoryDeltaBytes:o-r.startMemory,cpuUserUs:a.user,cpuSystemUs:a.system}}let i={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:s,status:t,duration:performance.now()-r.startTime,spans:r.spans,timestamp:new Date().toISOString()};this.transport.addTask(i)}wrapTask(t,n,r={},s){return(async(...i)=>this.startTask(t,n,r,async()=>{try{let o=await s(...i);return this.endTask("success"),o}catch(o){throw this.captureError(o,{taskName:t}),this.endTask("failed"),o}}))}captureError(t,n={}){if(!this.transport)return;let r;t instanceof Error?r=t:r=new Error(String(t));let s=E.current(),i={errorClass:r.name||"Error",message:r.message,stackTrace:r.stack,context:J(n,this.options||void 0),timestamp:new Date().toISOString()};s?.contextType==="task"?this.transport.addError({...i,runId:s.id},"task"):this.transport.addError({...i,traceId:s?.id},"apm")}track(t){this.transport?.addTrace({traceId:Ee(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=S(t,n,{},this.options||void 0);return r?{end:(s,i)=>r.end(i,s)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},gt=new yt;var Ro=e=>e==="1"||e==="true"||e==="yes",de=e=>{if(!e)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},To=I("SENZOR_API_KEY")||I("SENZOR_APM_API_KEY")||I("SENZOR_SERVICE_API_KEY"),Ui=I("SENZOR_ENDPOINT")||I("SENZOR_APM_ENDPOINT"),St=!!I("AWS_LAMBDA_FUNCTION_NAME"),Ao={apiKey:To||"",endpoint:Ui,debug:Ro(I("SENZOR_DEBUG")),autoLogs:I("SENZOR_AUTO_LOGS")==="false"?!1:void 0,batchSize:de(I("SENZOR_BATCH_SIZE"))??(St?10:void 0),flushInterval:de(I("SENZOR_FLUSH_INTERVAL"))??(St?0:void 0),flushTimeoutMs:de(I("SENZOR_FLUSH_TIMEOUT_MS")),maxQueueSize:de(I("SENZOR_MAX_QUEUE_SIZE")),maxSpansPerTrace:de(I("SENZOR_MAX_SPANS_PER_TRACE")),captureHeaders:Ro(I("SENZOR_CAPTURE_HEADERS")),captureDbStatement:I("SENZOR_CAPTURE_DB_STATEMENT")==="false"?!1:void 0,frameworkSpans:I("SENZOR_FRAMEWORK_SPANS")==="false"?!1:void 0,captureMiddlewareSpans:I("SENZOR_CAPTURE_MIDDLEWARE_SPANS")==="false"?!1:void 0,captureRouterSpans:I("SENZOR_CAPTURE_ROUTER_SPANS")==="false"?!1:void 0,captureLifecycleHookSpans:I("SENZOR_CAPTURE_LIFECYCLE_HOOK_SPANS")==="false"?!1:void 0,runtimeMetrics:I("SENZOR_RUNTIME_METRICS")==="false"||St?!1:void 0,runtimeMetricsInterval:de(I("SENZOR_RUNTIME_METRICS_INTERVAL"))};To?gt.init(Ao):gt.preload(Ao);
2
2
  //# sourceMappingURL=register.mjs.map