@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
@@ -0,0 +1,2 @@
1
+ var Ge=Object.defineProperty;var qo=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Lo=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 A=(e,t)=>{for(var n in t)Ge(e,n,{get:t[n],enumerable:!0})},$o=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of No(t))!Lo.call(e,s)&&s!==n&&Ge(e,s,{get:()=>t[s],enumerable:!(r=qo(t,s))||r.enumerable});return e};var R=e=>$o(Ge({},"__esModule",{value:!0}),e);var K,we=_(()=>{"use strict";K="x-senzor-sdk-internal"});var Re,At,Ke,he,E,N=_(()=>{"use strict";Re=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}},At=()=>{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},Ke=class{constructor(){this.resolved=!1;this.inner=At()||new Re,this.resolved=!(this.inner instanceof Re)}ensureResolved(){if(this.resolved)return;let t=At();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()}},he=new Ke,E={run:(e,t)=>he.run(e,t),withActiveSpan:(e,t)=>{let n=he.getStore();return n?he.run({...n,activeSpanId:e,data:n.data,spans:n.spans},t):t()},current:()=>he.getStore(),addSpan:e=>{let t=he.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 Fo,Q,$,Z=_(()=>{"use strict";Fo=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Q=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(Fo);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}},$=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var Tt,Ae,ye,Ye=_(()=>{"use strict";Tt=()=>{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)})},Ae=()=>Tt().replace(/-/g,""),ye=()=>Tt().replace(/-/g,"").slice(0,16)});var Do,Xe,Ho,jo,Bo,Wo,J,Qo,Go,Je,X,Ot,v,q,H=_(()=>{"use strict";Do=64,Xe=2048,Ho=4,jo=20,Bo=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Wo=e=>({maxAttributes:e?.maxAttributes??Do,maxAttributeLength:e?.maxAttributeLength??Xe}),J=(e,t=Xe)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Qo=e=>Bo.test(e),Go=(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 J(e,t)},Je=(e,t,n,r)=>{if(Qo(e))return"[REDACTED]";let s=Go(t,n.maxAttributeLength);if(s!==void 0||t===void 0)return s;if(t instanceof Error)return{name:J(t.name,n.maxAttributeLength),message:J(t.message,n.maxAttributeLength),stack:t.stack?J(t.stack,n.maxAttributeLength):void 0};if(r>=Ho)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,jo).map(i=>Je(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]=Je(a,c,n,r+1),o++}return i}return J(String(t),n.maxAttributeLength)},X=(e={},t)=>{let n=Wo(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]=Je(o,a,r,0),i++}return s},Ot=(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 X(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 J(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??Xe)},q=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var b,S,O=_(()=>{"use strict";N();H();Ye();b=(e,t,n={},r)=>{let s=E.current();if(!s)return null;let i=ye(),o=s.activeSpanId,a=performance.now()-s.startTime,c=performance.now(),u=!1;return{spanId:i,parentSpanId:o,trace:s,end:(p,d={})=>{if(u)return;u=!0;let f=X({...n,...d,parentSpanId:o},r);E.addSpanToTrace(s,{spanId:i,parentSpanId:o,name:e,type:t,startTime:a,duration:performance.now()-c,status:p,meta:f})}}},S=(e,t)=>e?E.withActiveSpan(e.spanId,t):t()});var U,xt,ee=_(()=>{"use strict";U=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],xt=(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:U(t)});var Zo,Vo,Mt,Yo,Jo,Xo,V,It,es,ts,Te,rt=_(()=>{"use strict";Zo=/^(?:(?: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)$/,Vo=/^(?:[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,Mt=e=>Zo.test(e)?4:Vo.test(e)?6:0,Yo=e=>e.startsWith("::ffff:")?e.slice(7):e,Jo=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return Mt(n)===4?n:e},Xo=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},V=e=>{if(!e)return null;let t=e.trim();return t?(t=Xo(t),t=Jo(t),t=Yo(t),Mt(t)!==0?t:null):null},It=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")),es=e=>{let t=e.split(",");for(let n of t){let r=n.match(/for=["[]?([^\]",;>\s]+)/i);if(r){let s=V(r[1]);if(s&&!It(s))return s}}return null},ts=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=V(n);if(r&&!It(r))return r}for(let n of t){let r=V(n);if(r)return r}return null},Te=e=>{let t=e.headers;{let n=V(t["cf-connecting-ip"]);if(n)return n}{let n=V(t["true-client-ip"]);if(n)return n}{let n=V(t["x-real-ip"]);if(n)return n}{let n=t.forwarded;if(n){let r=es(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=ts(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=V(n);if(r)return r}return null}});var vt,Pt,y,z=_(()=>{"use strict";vt=Symbol.for("senzor.patch.keys"),Pt=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[vt];if(i?.has(n))return!1;let o=s[Pt]||s,a=r(s),c=new Set(i||[]);c.add(n);try{Object.defineProperty(a,vt,{value:c,enumerable:!1}),Object.defineProperty(a,Pt,{value:o,enumerable:!1})}catch{return!1}try{return e[t]=a,!0}catch{return!1}}});var st={};A(st,{instrumentFetch:()=>as,instrumentHttp:()=>is});var ns,qt,rs,$t,Ut,ot,te,os,ss,Nt,Lt,as,is,at=_(()=>{"use strict";N();ee();H();rt();we();Z();z();O();ns=e=>!!e?.debug,qt=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),rs=(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}}},$t=e=>String(rs(e,K)||"").toLowerCase()==="true",Ut=(e,t,n)=>{if($t(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}},ot=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}:{}},te=(e,t,n)=>{let r=Object.keys(e).find(s=>s.toLowerCase()===t.toLowerCase());e[r||t]=n},os=(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}qt(n[1])?(r=1,s={...n[1],headers:ot(n[1].headers)},n[1]=s):(r=1,s={headers:{}},n.splice(1,0,s))}else qt(n[0])?(r=0,s={...n[0],headers:ot(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||""}`,u=i?i.toString():`${o}//${a}${c}`,p=String(s.method||"GET").toUpperCase();return{args:n,options:s,url:u,method:p,hostname:String(a).replace(/:\d+$/,""),path:c}},ss=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return xt(e,n)}catch{return U(n)}},Nt=(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],u=a[1];if(!c||!u||E.current()?.contextType==="apm")return s.call(this,o,...a);let p=c.originalUrl||c.url||"/",d=String(p).split("?")[0]||"/",f=c.headers||{};return $t(f)?s.call(this,o,...a):n.startTrace({method:c.method||"GET",path:p,route:U(d),ip:Te(c),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:c.httpVersion,headers:r?.captureHeaders?Ot(f,r):void 0}},()=>{let l=E.current(),m=!1,h=g=>{m||!l||(m=!0,setImmediate(()=>{l.state.ended||E.run(l,()=>{n.endTrace(u.statusCode||0,{route:ss(c,u,d),statusMessage:u.statusMessage,meta:{...l.data.meta,endReason:g}})})}))};u.once("finish",()=>h("finish")),u.once("close",()=>h("close")),u.once("error",g=>{n.captureError(g,{instrumentation:`${t}.server`}),h("error")});try{return s.call(this,o,...a)}catch(g){throw n.captureError(g,{instrumentation:`${t}.server`}),h("error"),g}})})},Lt=(e,t,n,r)=>{let s=t==="https:"?"senzor.https":"senzor.http",i=o=>function(...c){let u=os(c,t);if(Ut(u.url,n,u.options.headers))return o.apply(this,c);let p=E.current();if(!p)return o.apply(this,c);let d=b(`${u.method} ${u.hostname}`,"http",{url:u.url,method:u.method,library:t==="https:"?"https":"http","http.request.method":u.method,"url.full":u.url,"url.path":u.path,"server.address":u.hostname},r);d&&(te(u.options.headers,"traceparent",$(p.id,d.spanId)),te(u.options.headers,"x-senzor-trace-id",p.id),te(u.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=o.apply(this,u.args);if(!d||!l||typeof l.once!="function")return l;let m=!1,h=(g,C={})=>{m||(m=!0,d.end(g,C))};return l.once("response",g=>{let C=g?.statusCode||0,w=()=>h(C,{"http.response.status_code":C});g.once("end",w),g.once("close",w),g.once("error",x=>h(500,{error:x.message,"error.type":x.name}))}),l.once("timeout",()=>h(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",g=>h(500,{error:g.message,"error.type":g.name})),l};return ns(r)&&console.log(`[Senzor] Injecting trace headers to ${u.url}`),S(d,f)};y(e,"request",`${s}.request`,i),y(e,"get",`${s}.get`,i)},as=(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(Ut(o,e,a))return n.call(this,s,i);let c=E.current();if(!c)return n.call(this,s,i);let u="unknown",p="/";try{let h=new URL(o);u=h.hostname,p=`${h.pathname}${h.search}`}catch{}let d=String(i?.method||s?.method||"GET").toUpperCase(),f=b(`${d} ${u}`,"http",{url:o,method:d,library:"fetch","http.request.method":d,"url.full":o,"url.path":p,"server.address":u},t);if(!f)return n.call(this,s,i);let l={...i||{}},m=typeof Headers<"u"?new Headers(a||void 0):ot(a);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",$(c.id,f.spanId)),m.set("x-senzor-trace-id",c.id),m.set("x-senzor-parent-span-id",f.spanId)):(te(m,"traceparent",$(c.id,f.spanId)),te(m,"x-senzor-trace-id",c.id),te(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,S(f,async()=>{try{let h=await n.call(this,s,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}})})},is=(e,t,n)=>{let r,s;try{r=M("http")}catch{return}try{s=M("https")}catch{}r?.Server?.prototype&&Nt(r.Server.prototype,"http",e,n),s?.Server?.prototype&&Nt(s.Server.prototype,"https",e,n),Lt(r,"http:",t,n),s&&Lt(s,"https:",t,n)}});function cs(){let e=ne;return e[Oe]||Object.defineProperty(e,Oe,{value:new Map,enumerable:!1}),e[Oe]}function us(e,t){let n=ne[Oe];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 ps(){let e=ne;if(e[Ft])return;let t=e._load;e._load=function(r,s,i){let o=t.apply(this,arguments);return us(r,o)},Object.defineProperty(e,Ft,{value:!0,enumerable:!1})}function ds(e,t){try{let n=re.resolve(e),r=re.cache?.[n];if(r?.exports){let s=t(r.exports);s!==void 0&&(r.exports=s)}}catch{}}function fs(e,t){try{let n=re(e);n&&t(n)}catch{}}function ls(e,t){let n=0,r=5,s=setInterval(()=>{n++;try{let i=re(e);i&&(t(i),clearInterval(s))}catch{}n>=r&&clearInterval(s)},200);typeof s.unref=="function"&&s.unref()}var ne,re,Ft,Oe,k,T=_(()=>{"use strict";try{ne=M("module"),re=ne.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}Ft=Symbol.for("senzor.require.patched"),Oe=Symbol.for("senzor.require.hooks");k=(e,t)=>{if(!ne||!re)return;let n=cs();n.has(e)||n.set(e,[]),n.get(e).push(t),ps(),ds(e,t),fs(e,t),ls(e,t)}});var ms,hs,oe,ys,gs,bs,xe,se,Me=_(()=>{"use strict";N();O();ms=new Set([void 0,null,"route","router"]),hs=(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)),oe=(e,t=0)=>{let n=e.response;return n?.statusCode||n?.status||n?.raw?.statusCode||n?.status_code||t},ys=e=>!!(e&&typeof e.then=="function"),gs=(e,t)=>e.parentSpanId?E.withActiveSpan(e.parentSpanId,t):t(),bs=(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{}},xe=(e,t,n,r,s,i={})=>{if(!hs(r.type,s)||!E.current())return e.apply(t,n);let o=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},s);if(!o)return e.apply(t,n);let a=!1,c=[],u=(f=oe(r),l={})=>{if(!a){a=!0;for(let m of c)try{m()}catch{}o.end(f,l)}},p=r.response;if(i.responseEndsSpan!==!1&&p?.once){let f=()=>u(oe(r),{completion:"response.finish"}),l=()=>u(oe(r),{completion:"response.close"});p.once("finish",f),p.once("close",l),c.push(()=>{try{p.removeListener?.("finish",f)}catch{}try{p.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(...m){let h=m[0],g=!ms.has(h);return u(g?500:oe(r),{completion:"callback",error:g?String(h?.message||h):void 0,"error.type":g?h?.name||typeof h:void 0}),gs(o,()=>f.apply(this,m))}}return S(o,()=>{try{let f=e.apply(t,n);return ys(f)?f.then(l=>(u(oe(r),{completion:"promise.resolve"}),l),l=>{throw u(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&i.responseEndsSpan===!1&&u(oe(r),{completion:"sync.return"}),f)}catch(f){throw u(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},se=(e,t,n,r={})=>{if(typeof e!="function")return e;let s=(o,a)=>xe(e,o,a,t(o,a),n,r),i;switch(e.length){case 4:i=function(a,c,u,p){return s(this,[a,c,u,p])};break;case 3:i=function(a,c,u){return s(this,[a,c,u])};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 bs(e,i),i}});var Gt={};A(Gt,{instrumentExpress:()=>_s});var Dt,Ss,ct,it,Ht,ks,jt,Bt,Ie,Cs,Wt,Qt,_s,Kt=_(()=>{"use strict";ee();T();z();Me();Dt=Symbol.for("senzor.express.layer.patched"),Ss=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"]),ct=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ct).filter(Boolean).join(",");if(typeof e=="number")return String(e)},it=e=>{for(let t of e){if(typeof t=="function")return;let n=ct(t);if(n)return n}},Ht=(e,t,n)=>{if(t?.route?.path){let s=ct(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?U(String(r).split("?")[0]):void 0},ks=(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"),jt=(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},Bt=(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[Dt]||typeof e.handle!="function"||(Object.defineProperty(e,Dt,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",s=>{let i=ks(e,s,r),o=s.name||e.name||(i==="request_handler"?"handler":i);if(s.length===4){let c=function(p,d,f,l){let m=Ht(d,e,t);return xe(s,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||o}`,route:m,method:jt(e,d),layerPath:t,handlerName:o,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 Bt(s,c),c}let a=function(u,p,d){let f=Ht(u,e,t),l=jt(e,u),m=f||t||o,h=i==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${i} ${m}`;return xe(s,this,[u,p,d],{framework:"express",type:i,name:h,route:f,method:l,layerPath:t,handlerName:o,request:u,response:p,attributes:{"express.type":i,"express.layer.name":e.name,"http.route":f}},n,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Bt(s,a),a}))},Cs=(e,t,n)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let r of Ss)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 u of c)Ie(u,t,n,"request_handler");return a})}},Wt=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Qt=(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=it(i),c=this?.stack||[],u=c[c.length-1];return Ie(u,a,t,"router"),Cs(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 u=o;u<c.length;u++)Ie(c[u],it(i),t);return a}),y(e.application,"use","senzor.express.application.use",r=>function(...i){let a=Wt(this)?.stack?.length||0,c=r.apply(this,i),p=Wt(this)?.stack||[];for(let d=a;d<p.length;d++)Ie(p[d],it(i),t);return c})},_s=e=>{k("express",t=>{Qt(t,e),t?.default&&Qt(t.default,e)})}});var Xt={};A(Xt,{instrumentFastify:()=>Ts,instrumentFastifyInstance:()=>Os});var Zt,Vt,ws,Es,pt,Yt,Rs,As,Jt,zs,ut,Ts,Os,en=_(()=>{"use strict";T();z();Me();Zt=Symbol.for("senzor.fastify.factory.patched"),Vt=Symbol.for("senzor.fastify.instance.patched"),ws=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Es=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],pt=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,Yt=(e,t,n,r)=>typeof t!="function"?t:se(t,(s,i)=>{let o=i[0],a=i[1],c=pt(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}),Rs=(e,t,n)=>typeof e!="function"?e:se(e,(r,s)=>{let i=s[0],o=s[1],a=pt(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}),As=(e,t)=>Array.isArray(e)?e.map(t):t(e),Jt=(e,t)=>(!e||e[Vt]||(Object.defineProperty(e,Vt,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(s,i){return ws.has(s)?n.call(this,s,Yt(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=Rs(i.handler,t,o));for(let a of Es)i[a]&&(i[a]=As(i[a],c=>Yt(a,c,t,o)));return n.call(this,i)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(s){return n.call(this,se(s,(i,o)=>{let a=o[1],c=o[2],u=pt(a);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${u||a?.url||""}`.trim(),route:u,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),zs=(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{}},ut=(e,t)=>{if(typeof e!="function"||e[Zt])return e;let n=function(...i){let o=e.apply(this,i);return Jt(o,t)};zs(e,n),Object.defineProperty(n,Zt,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},Ts=e=>{k("fastify",t=>typeof t=="function"?ut(t,e):(t?.fastify&&(t.fastify=ut(t.fastify,e)),t?.default&&(t.default=ut(t.default,e)),t))},Os=(e,t)=>Jt(e,t)});var on={};A(on,{instrumentKoa:()=>Is});var xs,rn,tn,dt,Ms,nn,Is,sn=_(()=>{"use strict";ee();T();z();Me();xs=["all","del","delete","get","head","options","patch","post","put"],rn=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(rn).filter(Boolean).join(",")},tn=e=>{for(let t of e){if(typeof t=="function")return;let n=rn(t);if(n)return n}},dt=(e,t,n,r="middleware",s)=>typeof e!="function"?e:se(e,(i,o)=>{let a=o[0],c=a?._matchedRoute||a?.matched?.[0]?.path||n||U(a?.path||a?.request?.path||"/"),u=s||a?.method||a?.request?.method,p=e.name||r;return{framework:"koa",type:r,name:r==="route_handler"?`koa.request_handler ${u||""} ${c}`.trim():`koa.${r} ${c||p}`,route:c,method:u,layerPath:n,handlerName:p,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}),Ms=(e,t)=>{let n=e?.prototype||e?.default?.prototype;n&&y(n,"use","senzor.koa.application.use",r=>function(i){return r.call(this,dt(i,t,void 0,"middleware"))})},nn=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",s=>function(...o){let a=tn(o),c=o.map(u=>typeof u=="function"?dt(u,t,a,"router"):u);return s.apply(this,c)});for(let s of xs)y(r,s,`senzor.koa.router.${s}`,i=>function(...a){let c=tn(a),u=a.map(p=>typeof p=="function"?dt(p,t,c,"route_handler",s.toUpperCase()):p);return i.apply(this,u)})}},Is=e=>{k("koa",t=>{Ms(t,e)}),k("@koa/router",t=>{nn(t,e)}),k("koa-router",t=>{nn(t,e)})}});var an={};A(an,{instrumentUndici:()=>Ns});var vs,ft,Ps,ve,qs,Ns,cn=_(()=>{"use strict";ee();we();Z();T();z();O();vs=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,ft=(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},Ps=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:"/"}}},ve=(e,t,n,r)=>{y(e,t,n,s=>function(o,a,c){if(vs(a?.headers))return s.apply(this,arguments);let u=Ps(o?.origin?o.origin:o),p=String(a?.method||"GET").toUpperCase(),d=b(`${p} ${u.hostname}`,"http",{url:u.url,method:p,route:U(u.path),library:"undici","http.request.method":p,"url.full":u.url,"url.path":u.path,"server.address":u.hostname},r);if(!d)return s.apply(this,arguments);let f={...a||{}};f.headers=ft(f.headers,"traceparent",$(d.trace.id,d.spanId)),f.headers=ft(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=ft(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof c=="function"?function(h,g){return d.end(h?500:g?.statusCode||0,{error:h?.message,"error.type":h?.name,"http.response.status_code":g?.statusCode}),c.apply(this,arguments)}:c;return S(d,()=>{try{let m=s.call(this,o,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}})})},qs=(e,t)=>{ve(e,"request","senzor.undici.request",t),ve(e,"stream","senzor.undici.stream",t),ve(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((n,r)=>{ve(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},Ns=e=>{k("undici",t=>qs(t,e))}});var dn={};A(dn,{instrumentMongo:()=>Ds});var Ls,un,$s,Us,pn,Fs,Ds,fn=_(()=>{"use strict";T();z();O();Ls=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",un=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,$s=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Us=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...i){let o=Ls(this),a=b(`MongoDB ${t}`,"db",{collection:o,operation:t,"db.system.name":"mongodb","db.collection.name":o,"db.namespace":un(this)?`${un(this)}.${o}`:o,"db.operation.name":t,library:"mongodb"},n);return a?S(a,()=>{try{let c=r.apply(this,i);return c&&typeof c.then=="function"?c.then(u=>(a.end(0,{matchedCount:u?.matchedCount,modifiedCount:u?.modifiedCount,deletedCount:u?.deletedCount,insertedCount:u?.insertedCount}),u),u=>{throw a.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(a.end(0),c)}catch(c){throw a.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):r.apply(this,i)})},pn=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,s=>function(...o){let a=$s(this),c=b(`MongoDB ${n}`,"db",{collection:a,operation:n,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":n,library:"mongodb"},r);return c?S(c,()=>{try{let u=s.apply(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):s.apply(this,o)})},Fs=(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=>Us(r,o,t));let s=e?.FindCursor||e?.default?.FindCursor,i=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(o=>pn(s?.prototype,o,"find",t)),["toArray","next","forEach"].forEach(o=>pn(i?.prototype,o,"aggregate",t))},Ds=e=>{k("mongodb",t=>Fs(t,e))}});var yn={};A(yn,{instrumentMongoose:()=>js});var mn,hn,Pe,ln,Hs,js,gn=_(()=>{"use strict";T();z();O();mn=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",hn=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",Pe=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...i){let o=String(this?.op||this?._op||t).toUpperCase(),a=hn(this),c=b(`Mongoose ${o}`,"db",{collection:a,model:mn(this),operation:o,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":o,library:"mongoose"},n);return c?S(c,()=>{try{let u=r.apply(this,i);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):r.apply(this,i)})},ln=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...s){let i=hn(this),o=b("Mongoose SAVE","db",{collection:i,model:mn(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":i,"db.operation.name":"SAVE",library:"mongoose"},t);return o?S(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)})},Hs=(e,t)=>{Pe(e?.Query?.prototype,"query",t),Pe(e?.Aggregate?.prototype,"aggregate",t),ln(e?.Model?.prototype,t),e?.default&&(Pe(e.default?.Query?.prototype,"query",t),Pe(e.default?.Aggregate?.prototype,"aggregate",t),ln(e.default?.Model?.prototype,t))},js=e=>{k("mongoose",t=>Hs(t,e))}});var bn={};A(bn,{instrumentPg:()=>Qs});var Bs,qe,Ws,Qs,Sn=_(()=>{"use strict";H();T();z();O();Bs=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},qe=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...i){let o=Bs(i),a=q(o)||"QUERY",c=b(`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 u=i.findIndex(p=>typeof p=="function");if(u>=0){let p=i[u];i[u]=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}),p.apply(this,arguments)}}return S(c,()=>{try{let p=r.apply(this,i);return p&&typeof p.then=="function"?p.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}):(u<0&&p&&typeof p.once=="function"?(p.once("end",()=>c.end(0)),p.once("error",d=>c.end(500,{error:d.message,"error.type":d.name}))):u<0&&c.end(0),p)}catch(p){throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}})})},Ws=(e,t)=>{e&&(qe(e.Client?.prototype,"client",t),qe(e.Pool?.prototype,"pool",t),e.default&&(qe(e.default.Client?.prototype,"default.client",t),qe(e.default.Pool?.prototype,"default.pool",t)))},Qs=e=>{k("pg",t=>Ws(t,e))}});var Cn={};A(Cn,{instrumentMysql:()=>Vs});var Gs,ae,Ks,Zs,kn,Vs,_n=_(()=>{"use strict";H();T();z();O();Gs=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},ae=(e,t,n,r)=>{y(e,t,`senzor.${n}.${t}`,s=>function(...o){let a=Gs(o),c=q(a)||t.toUpperCase(),u=b(`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(!u)return s.apply(this,o);let p=o.findIndex(d=>typeof d=="function");if(p>=0){let d=o[p];o[p]=function(l,m){return u.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(m)?m.length:void 0}),d.apply(this,arguments)}}return S(u,()=>{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 u.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw u.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(p<0&&d&&typeof d.once=="function"?(d.once("end",()=>u.end(0)),d.once("error",f=>u.end(500,{error:f.message,"error.type":f.name}))):p<0&&u.end(0),d)}catch(d){throw u.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},Ks=(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=>{ae(r,"query",t,n),ae(r,"execute",t,n)})},Zs=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,s=>function(...o){let a=s.apply(this,o);return ae(a,"query",t,n),ae(a,"execute",t,n),ae(Object.getPrototypeOf(a),"query",t,n),ae(Object.getPrototypeOf(a),"execute",t,n),a})})},kn=(e,t,n)=>{Ks(e,t,n),Zs(e,t,n)},Vs=e=>{k("mysql",t=>kn(t,"mysql",e)),k("mysql2",t=>kn(t,"mysql2",e))}});var wn={};A(wn,{instrumentRedis:()=>ta});var Ys,ie,Js,Xs,ea,ta,En=_(()=>{"use strict";T();z();O();Ys=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",ie=(e,t,n)=>{y(e,"sendCommand",`senzor.redis.${t}.sendCommand`,r=>function(i,...o){let a=Ys(i),c=b(`Redis ${a}`,"db",{command:a,operation:a,"db.system.name":"redis","db.operation.name":a,library:t},n);return c?S(c,()=>{try{let u=r.call(this,i,...o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):r.apply(this,arguments)})},Js=(e,t,n)=>(ie(e,t,n),ie(Object.getPrototypeOf(e),t,n),e),Xs=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...i){let o=r.apply(this,i);return Js(o,"redis",t)})})},ea=(e,t)=>{ie(e?.prototype,"ioredis",t),ie(e?.Redis?.prototype,"ioredis",t),ie(e?.Cluster?.prototype,"ioredis-cluster",t),ie(e?.default?.prototype,"ioredis",t)},ta=e=>{k("redis",t=>Xs(t,e)),k("ioredis",t=>ea(t,e))}});var zn={};A(zn,{instrumentBullMQ:()=>na});function An(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,s=r.processJob;typeof s!="function"||s[Rn]||(r.processJob=async function(i){let o=i.timestamp?Date.now()-i.timestamp:0,a=(i.attemptsMade||0)+1,c=i.opts?.attempts??1,u=a>=c,p=i.name==="__default__"?i.queueName:`${i.queueName}:${i.name}`;return t.startTask(p,"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"&&u&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:i.queueName,jobId:i.id,isDeadLetter:u}),t.endTask("failed"),d}})},Object.defineProperty(r.processJob,Rn,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var Rn,na,Tn=_(()=>{"use strict";T();N();Rn=Symbol.for("senzor.bullmq.patched");na=(e,t)=>{k("bullmq",n=>{An(n,e,t),n?.default&&An(n.default,e,t)})}});var Mn={};A(Mn,{instrumentNodeCron:()=>oa});function ra(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function xn(e,t,n){let r=e.schedule;if(typeof r!="function"||r[On])return;let s=r,i=function(o,a,c){if(typeof a!="function")return s.call(this,o,a,c);try{let u=ra(c),p=u?.name??`cron: ${o}`,d=t.wrapTask(p,"cron",{expression:o,metadata:u},a);return s.call(this,o,d,c)}catch(u){return n&&console.error("[Senzor] cron wrap failed",u),s.call(this,o,a,c)}};Object.defineProperty(i,On,{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 On,oa,In=_(()=>{"use strict";T();On=Symbol.for("senzor.cron.patched");oa=(e,t)=>{k("node-cron",n=>{n&&(xn(n,e,t),n.default&&xn(n.default,e,t))})}});var Nn={};A(Nn,{instrumentGrpc:()=>ca});var Le,F,ge,vn,Pn,qn,Ne,sa,aa,ia,ca,Ln=_(()=>{"use strict";N();T();z();O();Z();Le={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"},F=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,ge=e=>{let t=e.replace(/^\//,"").split("/");return{service:t[0]||"unknown",method:t[1]||"unknown"}},vn="traceparent",Pn="x-senzor-trace-id",qn="x-senzor-parent-span-id",Ne=(e,t,n)=>{try{e&&typeof e.set=="function"&&(e.set(vn,$(t,n)),e.set(Pn,t),e.set(qn,n))}catch{}},sa=e=>{try{if(!e||typeof e.get!="function")return{};let t=e.get(vn),n=Array.isArray(t)?t[0]:t;if(n){let i=Q(String(n));if(i)return i}let r=e.get(Pn),s=e.get(qn);return{traceId:Array.isArray(r)?r[0]:r||void 0,parentSpanId:Array.isArray(s)?s[0]:s||void 0}}catch{return{}}},aa=(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:u}=ge(i),p=b(`gRPC ${c}/${u}`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"network.transport":"tcp"},t);if(!p)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&&Ne(o[d],a.id,p.spanId),f>=0){let l=o[f];o[f]=function(h,g){if(h){let C=h.code??2;p.end(F(C),{"rpc.grpc.status_code":C,"rpc.grpc.status_text":Le[C]||"UNKNOWN","error.message":h.details||h.message,"error.type":h.name||"GrpcError"})}else p.end(0,{"rpc.grpc.status_code":0,"rpc.grpc.status_text":"OK"});return l.call(this,h,g)}}return S(p,()=>{try{let l=r.call(this,i,...o);if(f<0&&l&&typeof l.on=="function"){let m=!1;l.on("status",h=>{if(m)return;m=!0;let g=h?.code??0;p.end(F(g),{"rpc.grpc.status_code":g,"rpc.grpc.status_text":Le[g]||"UNKNOWN"})}),l.on("error",h=>{if(m)return;m=!0;let g=h?.code??2;p.end(F(g),{"rpc.grpc.status_code":g,"error.message":h?.details||h?.message,"error.type":h?.name||"GrpcError"})})}return l}catch(l){throw p.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:u}=ge(i),p=b(`gRPC ${c}/${u} (client-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"client_stream","network.transport":"tcp"},t);if(!p)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"){Ne(o[d],a.id,p.spanId);break}for(let d=o.length-1;d>=0;d--)if(typeof o[d]=="function"){let f=o[d];o[d]=function(m,h){if(m){let g=m.code??2;p.end(F(g),{"rpc.grpc.status_code":g,"error.message":m.details||m.message})}else p.end(0,{"rpc.grpc.status_code":0});return f.call(this,m,h)};break}return S(p,()=>{try{return r.call(this,i,...o)}catch(d){throw p.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:u}=ge(i),p=b(`gRPC ${c}/${u} (server-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"server_stream","network.transport":"tcp"},t);if(!p)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"){Ne(o[d],a.id,p.spanId);break}return S(p,()=>{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 m=l?.code??0;p.end(F(m),{"rpc.grpc.status_code":m,"rpc.grpc.status_text":Le[m]||"UNKNOWN"})}),d.on("error",l=>{f||(f=!0,p.end(F(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw p.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:u}=ge(i),p=b(`gRPC ${c}/${u} (bidi-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"bidi_stream","network.transport":"tcp"},t);if(!p)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"){Ne(o[d],a.id,p.spanId);break}return S(p,()=>{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 m=l?.code??0;p.end(F(m),{"rpc.grpc.status_code":m})}),d.on("error",l=>{f||(f=!0,p.end(F(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw p.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}))},ia=(e,t,n)=>{let r=e?.Server?.prototype;r&&y(r,"register","senzor.grpc.server.register",s=>function(o,a,c,u,p){if(typeof a!="function")return s.call(this,o,a,c,u,p);let d=function(f,l){let{service:m,method:h}=ge(o),g=f?.metadata,C=sa(g),w=b(`gRPC ${m}/${h}`,"http",{"rpc.system":"grpc","rpc.service":m,"rpc.method":h,"rpc.grpc.full_method":o,"rpc.grpc.call_type":p||"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 x=function(P,me,G,Y){if(P){let Qe=P.code??2;w.end(F(Qe),{"rpc.grpc.status_code":Qe,"rpc.grpc.status_text":Le[Qe]||"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,me,G,Y)};return S(w,()=>{try{return a.call(this,f,x)}catch(P){throw w.end(500,{"rpc.grpc.status_code":13,"error.message":P?.message,"error.type":P?.name||"Error"}),P}})}return S(w,()=>{try{let x=a.call(this,f);if(f&&typeof f.on=="function"){let P=!1,me=(G,Y)=>{P||(P=!0,w.end(G,Y))};f.on("error",G=>{let Y=G?.code??2;me(F(Y),{"rpc.grpc.status_code":Y,"error.message":G?.details||G?.message})}),f.on("end",()=>{me(0,{"rpc.grpc.status_code":0})}),f.on("cancelled",()=>{me(F(1),{"rpc.grpc.status_code":1,"rpc.grpc.status_text":"CANCELLED"})})}return x}catch(x){throw w.end(500,{"rpc.grpc.status_code":13,"error.message":x?.message,"error.type":x?.name||"Error"}),x}})};return s.call(this,o,d,c,u,p)})},ca=(e,t)=>{k("@grpc/grpc-js",n=>{aa(n,t),ia(n,e,t)})}});var Dn={};A(Dn,{instrumentGraphQL:()=>pa});var $n,$e,Un,Fn,ue,ce,ua,pa,Hn=_(()=>{"use strict";T();z();O();$n=4096,$e=e=>!e||typeof e!="string"?"":e.length<=$n?e:e.slice(0,$n)+"...[truncated]",Un=(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"}},Fn=e=>e?typeof e=="string"?e:e.loc?.source?.body?e.loc.source.body:e.source?.body?e.source.body:"":"",ue=e=>e&&Array.isArray(e.errors)&&e.errors.length>0,ce=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},ua=(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=b(`GraphQL ${o||"query"}`,"custom",{"graphql.operation.name":o||"anonymous","graphql.source":i?$e(i):void 0},t);return c?S(c,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(p=>(ue(p)?c.end(500,{"graphql.error_count":p.errors.length,"error.message":ce(p.errors)}):c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"GraphQLError"}),p}):(ue(u)?c.end(500,{"graphql.error_count":u.errors.length,"error.message":ce(u.errors)}):c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}}):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=Un(i,o),c=Fn(i),u=b(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":$e(c)},t);return u?S(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(ue(d)?u.end(500,{"graphql.error_count":d.errors.length,"error.message":ce(d.errors)}):u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message,"error.type":d?.name||"GraphQLError"}),d}):(ue(p)?u.end(500,{"graphql.error_count":p.errors.length,"error.message":ce(p.errors)}):u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}}):n.apply(this,s)}),y(e,"parse","senzor.graphql.parse",n=>function(s,...i){let o=typeof s=="string"?s:s?.body||"",a=b("GraphQL parse","custom",{"graphql.operation":"parse","graphql.source":$e(o)},t);return a?S(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=b("GraphQL validate","custom",{"graphql.operation":"validate"},t);return a?S(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":ce(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)}))},pa=e=>{k("graphql",t=>ua(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=Un(i,o),c=Fn(i),u=b(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":$e(c)},e);return u?S(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(ue(d)?u.end(500,{"graphql.error_count":d.errors.length,"error.message":ce(d.errors)}):u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(ue(p)?u.end(500,{"graphql.error_count":p.errors.length}):u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):n.apply(this,s)})})}});var jn={};A(jn,{instrumentDns:()=>la});var da,fa,la,Bn=_(()=>{"use strict";z();O();da=(e,t,n)=>{y(e,t,`senzor.dns.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=b(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);if(!a)return r.apply(this,i);let c=i.findIndex((u,p)=>typeof u=="function"&&p===i.length-1);if(c>=0){let u=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 u.call(this,d,...f)}}return S(a,()=>{try{return r.apply(this,i)}catch(u){throw a.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}})})},fa=(e,t,n)=>{y(e,t,`senzor.dns.promises.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=b(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);return a?S(a,async()=>{try{let c=await r.apply(this,i),u={};return t==="lookup"&&c?(u["network.peer.address"]=c.address,u["dns.address_family"]=c.family===6?"IPv6":"IPv4"):Array.isArray(c)&&(u["dns.result_count"]=c.length),a.end(0,u),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)})},la=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"&&da(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"&&fa(r,i,e)}}});var Wn={};A(Wn,{instrumentNet:()=>ga});var ma,ha,ya,ga,Qn=_(()=>{"use strict";z();O();ma=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}},ha=(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}=ma(i),u=c?`TCP connect ${o}`:`TCP connect ${o}:${a}`,p=b(u,"custom",{"net.peer.name":o,"net.peer.port":c?void 0:a,"net.transport":c?"unix":"tcp","network.transport":c?"unix":"tcp"},t);return p?S(p,()=>{let d=r.apply(this,i),f=!1,l=(m,h={})=>{f||(f=!0,p.end(m,h))};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",m=>{l(500,{"error.message":m?.message,"error.type":m?.code||m?.name||"NetError","net.error_code":m?.code})}),d.once("timeout",()=>{l(504,{"error.message":"Connection timed out","error.type":"TimeoutError"})}),d.once("close",m=>{m?l(500,{"error.message":"Connection closed with error"}):l(0)}),d}):r.apply(this,i)})},ya=(e,t)=>{},ga=e=>{let t;try{t=M("net")}catch{return}t&&(ha(t,e),ya(t,e))}});var Jn={};A(Jn,{instrumentKafka:()=>Ca});var Zn,Vn,Yn,Gn,ba,Sa,ka,Kn,Ca,Xn=_(()=>{"use strict";N();T();z();O();Z();Zn="traceparent",Vn="x-senzor-trace-id",Yn="x-senzor-parent-span-id",Gn=(e,t,n)=>{let r=e?{...e}:{};return r[Zn]=Buffer.from($(t,n)),r[Vn]=Buffer.from(t),r[Yn]=Buffer.from(n),r},ba=e=>{if(!e)return{};try{let t=e[Zn];if(t){let s=Buffer.isBuffer(t)?t.toString():String(t),i=Q(s);if(i)return i}let n=e[Vn],r=e[Yn];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{}}},Sa=(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=b(`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(u=>({...u,headers:Gn(u.headers,i.id,c.spanId)}))}),S(c,()=>{let u=n.call(this,s);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{"messaging.kafka.partitions":Array.isArray(p)?p.map(d=>d.partition).join(","):void 0}),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"KafkaError"}),p}):(c.end(0),u)})):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(p=>p.topic).join(","),c=o.reduce((p,d)=>p+(d.messages?.length||0),0),u=b(`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 u?(o.length>0&&(s={...s,topicMessages:o.map(p=>({...p,messages:(p.messages||[]).map(d=>({...d,headers:Gn(d.headers,i.id,u.spanId)}))}))}),S(u,()=>{let p=n.call(this,s);return p&&typeof p.then=="function"?p.then(d=>(u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message,"error.type":d?.name||"KafkaError"}),d}):(u.end(0),p)})):n.call(this,s)})},ka=(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:u,message:p}=a,d=ba(p?.headers),f=b(`Kafka receive ${c}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":c,"messaging.operation.name":"receive","messaging.kafka.partition":u,"messaging.kafka.message.offset":p?.offset,"messaging.kafka.message.key":p?.key?.toString(),...d.traceId?{"messaging.parent_trace_id":d.traceId}:{}},t);return f?S(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,u=c?.topic||"unknown",p=c?.messages?.length||0,d=b(`Kafka receiveBatch ${u}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":u,"messaging.operation.name":"receive","messaging.kafka.partition":c?.partition,"messaging.batch.message_count":p,"messaging.kafka.first_offset":c?.messages?.[0]?.offset,"messaging.kafka.last_offset":c?.messages?.[p-1]?.offset},t);return d?S(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)})},Kn=(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&&Sa(o,t),o}),y(n.prototype,"consumer","senzor.kafka.consumer",r=>function(...i){let o=r.apply(this,i);return o&&ka(o,t),o}))},Ca=e=>{k("kafkajs",t=>{Kn(t,e),t?.default?.Kafka&&Kn(t.default,e)})}});var sr={};A(sr,{instrumentAmqplib:()=>Ea});var nr,rr,or,er,_a,pe,wa,tr,Ea,ar=_(()=>{"use strict";N();T();z();O();Z();nr="traceparent",rr="x-senzor-trace-id",or="x-senzor-parent-span-id",er=(e,t,n)=>{let r=e?{...e}:{},s=r.headers?{...r.headers}:{};return s[nr]=$(t,n),s[rr]=t,s[or]=n,r.headers=s,r},_a=e=>{let t=e?.properties?.headers;if(!t)return{};try{let n=t[nr];if(n){let i=Buffer.isBuffer(n)?n.toString():String(n),o=Q(i);if(o)return o}let r=t[rr],s=t[or];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{}}},pe=(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 u=s||i||"default",p=b(`RabbitMQ publish ${u}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":u,"messaging.operation.name":"publish","messaging.rabbitmq.exchange":s||"(default)","messaging.rabbitmq.routing_key":i,"messaging.message.body_size":o?.length||0},t);if(!p)return n.call(this,s,i,o,a);let d=er(a,c.id,p.spanId);return S(p,()=>{try{let f=n.call(this,s,i,o,d);return p.end(0,{"messaging.rabbitmq.backpressure":f===!1}),f}catch(f){throw p.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=b(`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 u=er(o,a.id,c.spanId);return S(c,()=>{try{let p=n.call(this,s,i,u);return c.end(0,{"messaging.rabbitmq.backpressure":p===!1}),p}catch(p){throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"AmqpError"}),p}})}),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 u=_a(c),p=c.fields?.exchange||"",d=c.fields?.routingKey||s,f=p||d||s,l=b(`RabbitMQ receive ${f}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":f,"messaging.operation.name":"receive","messaging.rabbitmq.exchange":p||"(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,...u.traceId?{"messaging.parent_trace_id":u.traceId}:{}},t);return l?S(l,()=>{try{let m=i(c);return m&&typeof m.then=="function"?m.then(h=>(l.end(0),h),h=>{throw l.end(500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}):(l.end(0),m)}catch(m){throw l.end(500,{"error.message":m?.message,"error.type":m?.name||"Error"}),m}}):i(c)};return n.call(this,s,a,o)}))},wa=(e,t)=>{try{let n=M("amqplib/lib/channel_model");n?.Channel?.prototype&&pe(n.Channel.prototype,t),n?.ConfirmChannel?.prototype&&pe(n.ConfirmChannel.prototype,t)}catch{}},tr=(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(...u){let p=a.apply(this,u);return p&&typeof p.then=="function"?p.then(d=>(d&&pe(d,t),d)):(p&&pe(p,t),p)}),y(o,"createConfirmChannel","senzor.amqplib.createConfirmChannel",a=>function(...u){let p=a.apply(this,u);return p&&typeof p.then=="function"?p.then(d=>(d&&pe(d,t),d)):(p&&pe(p,t),p)}),o)):i})},Ea=e=>{k("amqplib",t=>{wa(t,e),tr(t,e)}),k("amqplib/callback_api",t=>{tr(t,e)})}});var cr={};A(cr,{instrumentSocketIO:()=>Ta});var Ra,ir,be,lt,Aa,za,Ta,ur=_(()=>{"use strict";N();T();z();O();Ra=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener","error","ping","pong","connection"]),ir=e=>typeof e!="string"?!1:!Ra.has(e),be=(e,t,n,r)=>{y(e,"emit",t,s=>function(o,...a){if(!ir(o))return s.call(this,o,...a);if(!E.current())return s.call(this,o,...a);let u=this.nsp?.name||this.name||"/",p=b(`Socket.IO ${n} emit ${o}`,"messaging",{"messaging.system":"socket.io","messaging.destination.name":o,"messaging.operation.name":"send","messaging.socketio.namespace":u,"messaging.socketio.side":n,"messaging.socketio.event":o},r);if(!p)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(...h){return p.end(0,{"messaging.socketio.acknowledged":!0}),l.apply(this,h)}}return S(p,()=>{try{let l=s.call(this,o,...a);return f||p.end(0),l}catch(l){throw p.end(500,{"error.message":l?.message,"error.type":l?.name||"SocketIOError"}),l}})})},lt=(e,t,n,r)=>{y(e,"on",t,s=>function(o,a){if(!ir(o)||typeof a!="function")return s.call(this,o,a);let c=this.nsp?.name||this.name||"/",u=function(...p){let d=b(`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?S(d,()=>{try{let f=a.apply(this,p);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,p)};return u.__senzorOriginal=a,s.call(this,o,u)})},Aa=(e,t)=>{let n=e?.Socket;n?.prototype&&(be(n.prototype,"senzor.socketio.server.socket.emit","server",t),lt(n.prototype,"senzor.socketio.server.socket.on","server",t));let r=e?.Namespace;r?.prototype&&be(r.prototype,"senzor.socketio.server.namespace.emit","server",t)},za=(e,t)=>{let n=e?.Socket||e?.io?.Socket;n?.prototype&&(be(n.prototype,"senzor.socketio.client.emit","client",t),lt(n.prototype,"senzor.socketio.client.on","client",t)),e?.Manager?.prototype},Ta=e=>{k("socket.io",t=>{if(Aa(t,e),!t.Socket)try{let n=M("socket.io/dist/socket");n?.Socket?.prototype&&(be(n.Socket.prototype,"senzor.socketio.server.socket.emit","server",e),lt(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&&be(n.Namespace.prototype,"senzor.socketio.server.namespace.emit","server",e)}catch{}}),k("socket.io-client",t=>{za(t,e)})}});var dr={};A(dr,{instrumentNestJS:()=>Ma});var pr,Oa,xa,Ma,fr=_(()=>{"use strict";T();z();O();pr=e=>e&&e.constructor?.name||"UnknownController",Oa=(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,u,...p){let d=r.call(this,i,o,a,c,u,...p);if(typeof d!="function")return d;let f=pr(i);return function(m,h,g){let C=m?.route?.path||m?.url?.split("?")[0]||"/",w=b(`NestJS ${f}.${a}`,"function",{"nestjs.controller":f,"nestjs.method":a,"nestjs.module":c,"nestjs.type":"request_handler","http.route":C},t);return w?S(w,()=>{try{let x=d.call(this,m,h,g);return x&&typeof x.then=="function"?x.then(P=>(w.end(0),P),P=>{throw w.end(500,{"error.message":P?.message,"error.type":P?.name||"Error"}),P}):(w.end(0),x)}catch(x){throw w.end(500,{"error.message":x?.message,"error.type":x?.name||"Error"}),x}}):d.call(this,m,h,g)}})},xa=(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,...u){let p=o?.methodName||"unknown",d=o?.path||"/",f=o?.requestMethod,l=a?.metatype?.name||a?.name||"UnknownController",m=r.call(this,i,o,a,c,...u);return t?.debug&&console.log(`[Senzor] NestJS route registered: ${l}.${p} \u2192 ${d}`),m})},Ma=e=>{k("@nestjs/core",t=>{Oa(t,e),xa(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,...u){let p=n.call(this,s,i,o,a,c,...u);if(typeof p!="function")return p;let d=pr(s);return function(l,m,h){let g=l?.route?.path||l?.url?.split("?")[0]||"/",C=b(`NestJS ${d}.${o}`,"function",{"nestjs.controller":d,"nestjs.method":o,"nestjs.module":a,"nestjs.type":"request_handler","http.route":g},e);return C?S(C,()=>{try{let w=p.call(this,l,m,h);return w&&typeof w.then=="function"?w.then(x=>(C.end(0),x),x=>{throw C.end(500,{"error.message":x?.message}),x}):(C.end(0),w)}catch(w){throw C.end(500,{"error.message":w?.message}),w}}):p.call(this,l,m,h)}})})}});var yr={};A(yr,{instrumentHapi:()=>Pa});var Ia,va,mt,lr,mr,hr,Pa,gr=_(()=>{"use strict";T();z();O();Ia={0:"GET",1:"HEAD",2:"POST",3:"PUT",4:"DELETE",5:"OPTIONS",6:"PATCH"},va=e=>typeof e=="string"?e.toUpperCase():typeof e=="number"&&Ia[e]||"UNKNOWN",mt=(e,t,n,r)=>typeof e!="function"?e:function(i,o){let a=va(n),c=t||i?.route?.path||i?.path||"/",u=b(`Hapi ${a} ${c}`,"function",{"hapi.type":"route_handler","hapi.route":c,"hapi.method":a,"http.route":c,framework:"hapi"},r);return u?S(u,()=>{try{let p=e.call(this,i,o);return p&&typeof p.then=="function"?p.then(d=>{let f=d?.statusCode||i?.response?.statusCode||200;return u.end(f>=400?f:0,{"http.response.status_code":f}),d},d=>{let f=d?.output?.statusCode||500;throw u.end(f,{"error.message":d?.message,"error.type":d?.name||"Error","http.response.status_code":f}),d}):(u.end(0),p)}catch(p){let d=p?.output?.statusCode||500;throw u.end(d,{"error.message":p?.message,"error.type":p?.name||"Error","http.response.status_code":d}),p}}):e.call(this,i,o)},lr=(e,t)=>{if(!e)return e;let n=e.method||"GET",r=e.path||"/",s={...e};return typeof s.handler=="function"?s.handler=mt(s.handler,r,n,t):s.options&&typeof s.options.handler=="function"?(s.options={...s.options},s.options.handler=mt(s.options.handler,r,n,t)):s.config&&typeof s.config.handler=="function"&&(s.config={...s.config},s.config.handler=mt(s.config.handler,r,n,t)),s},mr=(e,t)=>{e&&y(e,"route","senzor.hapi.server.route",n=>function(s){if(Array.isArray(s)){let o=s.map(a=>lr(a,t));return n.call(this,o)}let i=lr(s,t);return n.call(this,i)})},hr=(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,u=function(p,d){let f=b(`Hapi ext ${a}`,"function",{"hapi.type":"lifecycle_hook","hapi.hook":a,framework:"hapi"},t);return f?S(f,()=>{try{let l=c.call(this,p,d);return l&&typeof l.then=="function"?l.then(m=>(f.end(0),m),m=>{throw f.end(500,{"error.message":m?.message}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):c.call(this,p,d)};return n.call(this,s,u,o)}return n.call(this,s,i,o)})},Pa=e=>{k("@hapi/hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(mr(n.prototype,e),e?.frameworkSpans!==!1&&hr(n.prototype,e))}),k("hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(mr(n.prototype,e),e?.frameworkSpans!==!1&&hr(n.prototype,e))})}});var Sr={};A(Sr,{instrumentPino:()=>Na});var br,qa,Na,kr=_(()=>{"use strict";N();T();z();br=()=>{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},qa=(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(p,d,f){let l=br();return l&&p&&typeof p=="object"&&Object.assign(p,l),c.call(this,p,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}`,u=>function(...d){let f=br();if(!f)return u.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 u.apply(this,d)});typeof i.child=="function"&&y(i,"child","senzor.pino.child",c=>function(p,...d){return c.call(this,p,...d)}),i.__senzorPatched=!0}}catch{}},Na=e=>{k("pino",t=>{qa(t,e)})}});var wr={};A(wr,{instrumentWinston:()=>$a});var Cr,_r,La,$a,Er=_(()=>{"use strict";N();T();z();Cr=()=>{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},_r=(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=Cr();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=Cr();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)}))},La=(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&&(_r({Logger:{prototype:o}},t),o.__senzorPatched=!0),i.__senzorPatched=!0}return i})},$a=e=>{k("winston",t=>{_r(t,e),La(t,e)})}});var Ar={};A(Ar,{instrumentBunyan:()=>Fa});var Ua,Rr,Fa,zr=_(()=>{"use strict";N();T();z();Ua=()=>{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},Rr=(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=Ua();a&&(i.traceId=a.traceId,a.spanId&&(i.spanId=a.spanId),i.senzor_context=a.senzor_context)}return r.call(this,i,o)})},Fa=e=>{k("bunyan",t=>{Rr(t,e),t?.default?.prototype?._emit&&Rr(t.default,e)})}});var xr={};A(xr,{instrumentAwsSdk:()=>Za});var Tr,Da,Or,Ha,ja,Ba,Wa,Qa,Ga,ht,Ka,Za,Mr=_(()=>{"use strict";T();z();O();Tr={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"},Da={anthropic:"anthropic",amazon:"aws_bedrock",meta:"meta",cohere:"cohere",mistral:"mistral",ai21:"ai21",stability:"stability"},Or=e=>{if(!e)return"aws_bedrock";let t=e.split(".")[0]?.toLowerCase();return Da[t]||"aws_bedrock"},Ha=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;s&&(n["gen_ai.system"]=Or(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},ja=e=>e==="InvokeModel"||e==="InvokeModelWithResponseStream"||e==="Converse"||e==="ConverseStream",Ba=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;return s&&(n["gen_ai.system"]=Or(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},Wa=e=>{let t=e?.constructor?.name;if(t&&Tr[t])return Tr[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"},Qa=e=>{let t=e?.constructor?.name;return t?t.endsWith("Command")?t.slice(0,-7):t:"UnknownCommand"},Ga=async e=>{try{let t=e?.config?.region;return typeof t=="function"?await t():t||void 0}catch{return}},ht=(e,t)=>{e&&y(e,"send","senzor.aws-sdk.client.send",n=>function(s,...i){let o=Wa(this),a=Qa(s),c=`AWS ${o} ${a}`,u=b(c,"http",{"rpc.system":"aws-api","rpc.service":o,"rpc.method":a,"cloud.provider":"aws","aws.service":o,"aws.operation":a},t);return u?(Ga(this).then(p=>{p&&u&&(u.__awsRegion=p)}).catch(()=>{}),S(u,()=>{try{let p=n.call(this,s,...i);return p&&typeof p.then=="function"?p.then(d=>{let f=d?.$metadata?.httpStatusCode,m={"aws.request_id":d?.$metadata?.requestId,"aws.region":u.__awsRegion,"http.response.status_code":f};if(ja(a)){let h=a,g=h==="Converse"||h==="ConverseStream"?Ba(s,d):Ha(s,d);Object.assign(m,g)}return u.end(f&&f>=400?f:0,m),d},d=>{let f=d?.$metadata?.httpStatusCode||500,l=d?.$metadata?.requestId;throw u.end(f,{"error.message":d?.message,"error.type":d?.name||d?.code||"AwsError","aws.request_id":l,"aws.region":u.__awsRegion,"http.response.status_code":f}),d}):(u.end(0),p)}catch(p){throw u.end(p?.$metadata?.httpStatusCode||500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}})):n.call(this,s,...i)})},Ka=["@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"],Za=e=>{k("@smithy/smithy-client",t=>{let n=t?.Client;n?.prototype&&ht(n.prototype,e)}),k("@aws-sdk/smithy-client",t=>{let n=t?.Client;n?.prototype&&ht(n.prototype,e)});for(let t of Ka)k(t,n=>{for(let r of Object.keys(n))r.endsWith("Client")&&n[r]?.prototype?.send&&ht(n[r].prototype,e)})}});var Pr={};A(Pr,{instrumentKnex:()=>Ja});var Va,Ir,Ya,Ue,vr,Ja,qr=_(()=>{"use strict";H();T();z();O();Va={pg:"postgresql","pg-native":"postgresql",mysql:"mysql",mysql2:"mysql",sqlite3:"sqlite","better-sqlite3":"sqlite",mssql:"mssql",oracledb:"oracle",oracle:"oracle",redshift:"redshift",cockroachdb:"cockroachdb"},Ir=e=>{let t=e?.config?.client||e?.dialect||e?.driverName||"unknown",n=typeof t=="string"?t.toLowerCase():"unknown";return Va[n]||n},Ya=e=>e&&e.match(/(?:FROM|INTO|UPDATE|JOIN)\s+[`"[\]]?(\w+)[`"\]]?/i)?.[1]||void 0,Ue=(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",u=q(a)||c.toUpperCase(),p=Ir(this),d=Ya(a),f=b(`Knex ${u}`,"db",{"db.system.name":p,"db.operation.name":u,"db.query.text":v(a,t),"db.collection.name":d,"knex.method":c,library:"knex"},t);return f?S(f,()=>{try{let l=r.call(this,i,o);return l&&typeof l.then=="function"?l.then(m=>{let h=Array.isArray(m)?m.length:m?.rowCount??m?.affectedRows;return f.end(0,{"db.response.row_count":h}),m},m=>{throw f.end(500,{"error.message":m?.message,"error.type":m?.name||"Error","db.error.code":m?.code}),m}):(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 u=o?.sql,p=q(u)||"STREAM",d=Ir(this),f=b(`Knex STREAM ${p}`,"db",{"db.system.name":d,"db.operation.name":`STREAM_${p}`,"db.query.text":v(u,t),"knex.method":"stream",library:"knex"},t);return f?S(f,()=>{try{let l=r.call(this,i,o,a,c);return l&&typeof l.then=="function"?l.then(m=>(f.end(0),m),m=>{throw f.end(500,{"error.message":m?.message}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):r.call(this,i,o,a,c)}))},vr=(e,t)=>{typeof e=="function"&&e.Client?.prototype&&Ue(e,t)},Ja=e=>{k("knex",t=>{vr(t,e),Ue(t,e),t?.default&&(vr(t.default,e),Ue(t.default,e))}),k("knex/lib/client",t=>{t?.prototype&&Ue({Client:t},e)})}});var Nr={};A(Nr,{instrumentTedious:()=>ti});var de,Xa,Se,ei,ti,Lr=_(()=>{"use strict";H();T();z();O();de=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},Xa=(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",u=de(this),p=b(`MSSQL ${c}`,"db",{...u,"db.operation.name":c,"db.query.text":v(a,t),"tedious.method":"execSql",library:"tedious"},t);return p?S(p,()=>(Se(o,p),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",u=de(this),p=b(`MSSQL BATCH ${c}`,"db",{...u,"db.operation.name":`BATCH_${c}`,"db.query.text":v(a,t),"tedious.method":"execSqlBatch",library:"tedious"},t);return p?S(p,()=>(Se(o,p),s.call(this,o))):s.call(this,o)}),y(r,"callProcedure","senzor.tedious.connection.callProcedure",s=>function(o){let a=o?.sqlTextOrProcedure||"unknown",c=de(this),u=b(`MSSQL CALL ${a}`,"db",{...c,"db.operation.name":"CALL","db.query.text":a,"db.collection.name":a,"tedious.method":"callProcedure",library:"tedious"},t);return u?S(u,()=>(Se(o,u),s.call(this,o))):s.call(this,o)}),y(r,"execBulkLoad","senzor.tedious.connection.execBulkLoad",s=>function(o,...a){let c=o?.table||"unknown",u=de(this),p=b(`MSSQL BULK INSERT ${c}`,"db",{...u,"db.operation.name":"BULK_INSERT","db.collection.name":c,"tedious.method":"execBulkLoad",library:"tedious"},t);return p?S(p,()=>{if(o&&typeof o.callback=="function"){let d=o.callback;o.callback=function(f,l){return f?p.end(500,{"error.message":f.message,"error.type":f.name||"Error"}):p.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,m){return l?p.end(500,{"error.message":l.message}):p.end(0,{"db.response.row_count":m}),f.apply(this,arguments)}}else p.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=de(this),u=b("MSSQL PREPARE","db",{...c,"db.operation.name":"PREPARE","db.query.text":v(a,t),"tedious.method":"prepare",library:"tedious"},t);return u?S(u,()=>(Se(o,u),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,u=q(c)||"EXECUTE",p=de(this),d=b(`MSSQL EXECUTE ${u}`,"db",{...p,"db.operation.name":`EXECUTE_${u}`,"db.query.text":v(c,t),"tedious.method":"execute",library:"tedious"},t);return d?S(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}))})}}},ei=(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=b(`MSSQL ${a}`,"db",{"db.system.name":"mssql","db.operation.name":a,"db.query.text":v(o,t),library:"mssql"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{"db.response.row_count":p?.recordset?.length??p?.rowsAffected?.[0]}),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"Error","db.error.code":p?.code}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)}),y(r,"execute","senzor.mssql.request.execute",s=>function(o){let a=b(`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?S(a,()=>{try{let c=s.call(this,o);return c&&typeof c.then=="function"?c.then(u=>(a.end(0),u),u=>{throw a.end(500,{"error.message":u?.message}),u}):(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=b(`MSSQL BATCH ${a}`,"db",{"db.system.name":"mssql","db.operation.name":`BATCH_${a}`,"db.query.text":v(o,t),library:"mssql"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)})},ti=e=>{k("tedious",t=>{Xa(t,e)}),k("mssql",t=>{ei(t,e)})}});var Fr={};A(Fr,{instrumentCassandra:()=>oi});var ni,$r,Fe,Ur,ri,oi,Dr=_(()=>{"use strict";H();T();z();O();ni={0:"any",1:"one",2:"two",3:"three",4:"quorum",5:"all",6:"localQuorum",7:"eachQuorum",8:"serial",9:"localSerial",10:"localOne"},$r=e=>{if(typeof e=="string")return e;if(typeof e=="number")return ni[e]},Fe=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},Ur=e=>e&&e.match(/(?:FROM|INTO|UPDATE)\s+(?:(\w+)\.)?(\w+)/i)?.[2]||void 0,ri=(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",u=Fe(this),p=Ur(o),d=a.find(C=>C&&typeof C=="object"&&!Array.isArray(C)&&typeof C!="function"),f=$r(d?.consistency),l=d?.fetchSize,m=b(`Cassandra ${c}`,"db",{...u,"db.operation.name":c,"db.query.text":v(o,t),"db.collection.name":p,"db.cassandra.consistency":f,"db.cassandra.page_size":l,library:"cassandra-driver"},t);if(!m)return s.call(this,o,...a);let h=a.length-1;if(h>=0&&typeof a[h]=="function"){let C=a[h];return a[h]=function(w,x){return w?m.end(500,{"error.message":w.message,"error.type":w.name||"Error","db.error.code":w.code}):m.end(0,{"db.response.row_count":x?.rowLength??x?.rows?.length,"db.cassandra.coordinator.id":x?.info?.queriedHost}),C.call(this,w,x)},S(m,()=>s.call(this,o,...a))}return S(m,()=>{try{let C=s.call(this,o,...a);return C&&typeof C.then=="function"?C.then(w=>(m.end(0,{"db.response.row_count":w?.rowLength??w?.rows?.length,"db.cassandra.coordinator.id":w?.info?.queriedHost}),w),w=>{throw m.end(500,{"error.message":w?.message,"error.type":w?.name||"Error","db.error.code":w?.code}),w}):(m.end(0),C)}catch(C){throw m.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,u=Fe(this),p=a.find(h=>h&&typeof h=="object"&&!Array.isArray(h)&&typeof h!="function"),d=$r(p?.consistency),f=b(`Cassandra BATCH (${c} queries)`,"db",{...u,"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 h=a[l];return a[l]=function(g,C){return g?f.end(500,{"error.message":g.message}):f.end(0),h.call(this,g,C)},S(f,()=>s.call(this,o,...a))}return S(f,()=>{try{let h=s.call(this,o,...a);return h&&typeof h.then=="function"?h.then(g=>(f.end(0),g),g=>{throw f.end(500,{"error.message":g?.message}),g}):(f.end(0),h)}catch(h){throw f.end(500,{"error.message":h?.message}),h}})}),y(r,"eachRow","senzor.cassandra.client.eachRow",s=>function(o,...a){let c=q(o)||"SELECT",u=Fe(this),p=Ur(o),d=b(`Cassandra EACHROW ${c}`,"db",{...u,"db.operation.name":`EACHROW_${c}`,"db.query.text":v(o,t),"db.collection.name":p,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 m=a[l];a[l]=function(h,g){return h?d.end(500,{"error.message":h.message}):d.end(0,{"db.response.row_count":f}),m.call(this,h,g)};for(let h=l-1;h>=0;h--)if(typeof a[h]=="function"){let g=a[h];a[h]=function(C,w){return f++,g.call(this,C,w)};break}break}return S(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",u=Fe(this),p=b(`Cassandra STREAM ${c}`,"db",{...u,"db.operation.name":`STREAM_${c}`,"db.query.text":v(o,t),library:"cassandra-driver"},t);return p?S(p,()=>{let d=s.call(this,o,...a);if(d&&typeof d.on=="function"){let f=0;d.on("data",()=>{f++}),d.on("end",()=>{p.end(0,{"db.response.row_count":f})}),d.on("error",l=>{p.end(500,{"error.message":l?.message})})}else p.end(0);return d}):s.call(this,o,...a)})},oi=e=>{k("cassandra-driver",t=>{ri(t,e)})}});var jr={};A(jr,{instrumentMemcached:()=>fi});var si,ai,ii,ci,ui,pi,di,fe,Hr,fi,Br=_(()=>{"use strict";T();z();O();si=["set","add","replace","append","prepend"],ai=["get","gets","del","delete","touch"],ii=["incr","decr"],ci=["cas"],ui=["getMulti"],pi=["stats","version","items","flush"],di=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}},fe=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.memcached.${t}`,s=>function(...o){let a=t.toUpperCase(),c=di(this),u=n(o),p=b(`Memcached ${a}`,"db",{"db.system.name":"memcached","db.operation.name":a,"server.address":c,library:"memcached",...u},r);if(!p)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,...m){return l?p.end(500,{"error.message":typeof l=="string"?l:l?.message,"error.type":l?.name||"MemcachedError"}):p.end(0),f.call(this,l,...m)}}else p.end(0);return S(p,()=>{try{return s.apply(this,o)}catch(f){throw p.end(500,{"error.message":f?.message}),f}})})},Hr=(e,t)=>{let n=e?.prototype;if(n){for(let r of si)fe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ai)fe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ii)fe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ci)fe(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ui)fe(n,r,s=>({"db.memcached.key_count":Array.isArray(s[0])?s[0].length:void 0}),t);for(let r of pi)fe(n,r,()=>({}),t)}},fi=e=>{k("memcached",t=>{Hr(t,e),t?.default?.prototype&&Hr(t.default,e)})}});var Qr={};A(Qr,{instrumentGenericPool:()=>li});var ke,yt,Wr,li,Gr=_(()=>{"use strict";T();z();O();ke=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},yt=(e,t)=>{e&&(y(e,"acquire","senzor.generic-pool.pool.acquire",n=>function(...s){let i=ke(this),o=b("Pool acquire","custom",{...i,"pool.operation":"acquire",library:"generic-pool"},t);return o?S(o,()=>{try{let a=n.apply(this,s);return a&&typeof a.then=="function"?a.then(c=>{let u=ke(this);return o.end(0,{"pool.size_after":u["pool.size"],"pool.available_after":u["pool.available"],"pool.pending_after":u["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=ke(this),o=b("Pool release","custom",{...i,"pool.operation":"release",library:"generic-pool"},t);return o?S(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=ke(this),o=b("Pool destroy","custom",{...i,"pool.operation":"destroy",library:"generic-pool"},t);return o?S(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=ke(this),i=b("Pool drain","custom",{...s,"pool.operation":"drain",library:"generic-pool"},t);return i?S(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)}))},Wr=(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&&(yt(a,t),a.__senzorPatched=!0),o.__senzorPatched=!0}return o})},li=e=>{k("generic-pool",t=>{Wr(t,e),t?.Pool?.prototype&&yt(t.Pool.prototype,e),t?.default&&(Wr(t.default,e),t.default.Pool?.prototype&&yt(t.default.Pool.prototype,e))})}});var Kr={};A(Kr,{instrumentRestify:()=>gi});var mi,hi,De,yi,gi,Zr=_(()=>{"use strict";T();z();O();mi=["get","post","put","del","patch","head","opts"],hi={get:"GET",post:"POST",put:"PUT",del:"DELETE",patch:"PATCH",head:"HEAD",opts:"OPTIONS"},De=(e,t,n,r,s)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let i=function(a,c,u){let p=hi[t]||t.toUpperCase(),d=n||a?.route?.path||a?.getPath?.()||a?.url?.split("?")[0]||"/",f=r==="middleware"?`Restify middleware ${e.name||"anonymous"}`:`Restify ${p} ${d}`,l=b(f,"function",{"restify.type":r,"http.route":d,"http.method":p,framework:"restify"},s);return l?S(l,()=>{let m=function(...h){if(h.length>0&&h[0]instanceof Error){let C=h[0];l.end(C?.statusCode||500,{"error.message":C.message,"error.type":C.name||"Error"})}else l.end(0);return u?.(...h)};try{let h=e.call(this,a,c,m);return h&&typeof h.then=="function"?h.then(g=>g,g=>{throw l.end(g?.statusCode||500,{"error.message":g?.message,"error.type":g?.name||"Error"}),g}):h}catch(h){throw l.end(h?.statusCode||500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}}):e.call(this,a,c,u)};return i.__senzorWrapped=!0,i},yi=(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 mi)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]=De(o[c],r,a,"route_handler",t):Array.isArray(o[c])&&(o[c]=o[c].map(u=>typeof u=="function"?De(u,r,a,"route_handler",t):u));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]=De(i[o],"use","*","middleware",t):Array.isArray(i[o])&&(i[o]=i[o].map(a=>typeof a=="function"?De(a,"use","*","middleware",t):a));return r.apply(this,i)})}},gi=e=>{k("restify",t=>{yi(t,e)})}});var Yr={};A(Yr,{instrumentConnect:()=>Si});var bi,Vr,Si,Jr=_(()=>{"use strict";T();z();O();bi=(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,u,p){let d=b(`Connect error ${r}`,"function",{"connect.type":"error_middleware","connect.name":r,"connect.route":t,framework:"connect"},n);return d?S(d,()=>{let f=function(...l){let m=l.length>0&&l[0]instanceof Error;return d.end(m?500:0,m?{"error.message":l[0].message}:{}),p?.(...l)};try{let l=e.call(this,a,c,u,f);return l&&typeof l.then=="function"?l.catch(m=>{throw d.end(500,{"error.message":m?.message}),m}):l}catch(l){throw d.end(500,{"error.message":l?.message}),l}}):e.call(this,a,c,u,p)}:i=function(a,c,u){let p=b(`Connect ${r}`,"function",{"connect.type":"middleware","connect.name":r,"connect.route":t,"http.route":t!=="/"?t:void 0,framework:"connect"},n);return p?S(p,()=>{let d=function(...f){let l=f.length>0&&f[0]instanceof Error;return p.end(l?500:0,l?{"error.message":f[0].message}:{}),u?.(...f)};try{let f=e.call(this,a,c,d);return f&&typeof f.then=="function"?f.catch(l=>{throw p.end(500,{"error.message":l?.message}),l}):f}catch(f){throw p.end(500,{"error.message":f?.message}),f}}):e.call(this,a,c,u)},Object.defineProperty(i,"length",{value:e.length}),i.__senzorWrapped=!0,i},Vr=(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]=bi(i[c],o,t));return r.apply(this,i)})},Si=e=>{k("connect",t=>{Vr(t,e),t?.default&&Vr(t.default,e)})}});var eo={};A(eo,{instrumentDataloader:()=>ki});var Xr,ki,to=_(()=>{"use strict";T();z();O();Xr=(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=b(`${a} load`,"function",{"dataloader.operation":"load","dataloader.name":a,library:"dataloader"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):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,u=b(`${a} loadMany`,"function",{"dataloader.operation":"loadMany","dataloader.name":a,"dataloader.key_count":c,library:"dataloader"},t);return u?S(u,()=>{try{let p=s.call(this,o);return p&&typeof p.then=="function"?p.then(d=>{let f=Array.isArray(d)?d.filter(l=>l instanceof Error).length:0;return u.end(f>0?207:0,{"dataloader.key_count":c,"dataloader.error_count":f}),d},d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):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,u=b(`${a} batch dispatch`,"function",{"dataloader.operation":"batch","dataloader.name":a,"dataloader.batch_size":c,library:"dataloader"},t);return u?S(u,()=>{try{let p=s.apply(this,o);return u.end(0,{"dataloader.batch_size":c}),p}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):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",u=b(`${c} prime`,"function",{"dataloader.operation":"prime","dataloader.name":c,library:"dataloader"},t);if(!u)return s.call(this,o,a);try{let p=s.call(this,o,a);return u.end(0),p}catch(p){throw u.end(500,{"error.message":p?.message}),p}}),typeof n.clearAll=="function"&&y(n,"clearAll","senzor.dataloader.clearAll",s=>function(){let o=this.name||this._name||"DataLoader",a=b(`${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}})},ki=e=>{k("dataloader",t=>{Xr(t,e),t?.default?.prototype&&Xr(t.default,e)})}});var oo={};A(oo,{instrumentLruMemoizer:()=>Ci});var no,ro,Ci,so=_(()=>{"use strict";T();O();no=(e,t,n)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let r=t||"memoized",s=function(...o){let a=b(`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 p=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),p.call(this,d,...f)},S(a,()=>{try{return e.apply(this,o)}catch(d){throw a.end(500,{"error.message":d?.message}),d}})}return S(a,()=>{try{let p=e.apply(this,o);return p&&typeof p.then=="function"?p.then(d=>(a.end(0),d),d=>{throw a.end(500,{"error.message":d?.message}),d}):(a.end(0),p)}catch(p){throw a.end(500,{"error.message":p?.message}),p}})};for(let i of Object.keys(e))try{s[i]=e[i]}catch{}return s.__senzorWrapped=!0,s},ro=(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 no(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 no(a,o,t)}}return n},Ci=e=>{k("lru-memoizer",t=>{if(typeof t=="function")return ro(t,e);typeof t?.default=="function"&&(t.default=ro(t.default,e))})}});var co={};A(co,{instrumentFs:()=>_i});var ao,io,je,He,gt,bt,_i,uo=_(()=>{"use strict";T();z();O();ao=["readFile","writeFile","appendFile","stat","lstat","access","readdir","mkdir","rmdir","unlink","chmod","chown","realpath","mkdtemp","truncate","readlink","exists"],io=["rename","copyFile","link","symlink"],je=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},He=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.${t}`,s=>function(...o){let a=t.toUpperCase(),c=je(o[0]),u={"fs.operation":t,"fs.path":c,library:"fs"};n===2&&o[1]&&(u["fs.destination"]=je(o[1]));let p=b(`FS ${a}`,"custom",u,r);if(!p)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,...m){return l?p.end(500,{"error.message":l.message,"error.type":l.name||"Error","error.code":l.code}):p.end(0),f.call(this,l,...m)}}return S(p,()=>{try{let f=s.apply(this,o);return d<0&&p.end(0),f}catch(f){throw p.end(500,{"error.message":f?.message,"error.code":f?.code}),f}})})},gt=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.promises.${t}`,s=>function(...o){let a=t.toUpperCase(),c=je(o[0]),u={"fs.operation":t,"fs.path":c,"fs.api":"promises",library:"fs"};n===2&&o[1]&&(u["fs.destination"]=je(o[1]));let p=b(`FS ${a}`,"custom",u,r);return p?S(p,()=>{try{let d=s.apply(this,o);return d&&typeof d.then=="function"?d.then(f=>(p.end(0),f),f=>{throw p.end(500,{"error.message":f?.message,"error.code":f?.code}),f}):(p.end(0),d)}catch(d){throw p.end(500,{"error.message":d?.message}),d}}):s.apply(this,o)})},bt=(e,t)=>{if(!e)return;for(let r of ao)He(e,r,1,t);for(let r of io)He(e,r,2,t);He(e,"open",1,t),He(e,"close",1,t);let n=e.promises;if(n){for(let r of ao)r!=="exists"&&gt(n,r,1,t);for(let r of io)gt(n,r,2,t);gt(n,"open",1,t)}},_i=e=>{try{let t=M("fs");bt(t,e)}catch{}k("fs",t=>{bt(t,e)}),k("node:fs",t=>{bt(t,e)})}});var lo={};A(lo,{instrumentOpenAI:()=>Ri});var wi,po,fo,Ei,Ri,mo=_(()=>{"use strict";T();z();O();wi={"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"},po=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"").replace(/\/[a-f0-9-]{20,}(\/|$)/g,"/");for(let[n,r]of Object.entries(wi))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},fo=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},Ei=(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,u){let p=po(c),d=fo(u?.body),f=i.toUpperCase(),l=d?`OpenAI ${p} ${d}`:`OpenAI ${p}`,m=b(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":p,"gen_ai.request.model":d,"gen_ai.request.max_tokens":u?.body?.max_tokens,"gen_ai.request.temperature":u?.body?.temperature,"http.request.method":f,"url.path":c,library:"openai"},t);return m?S(m,()=>{try{let h=o.call(this,c,u);return h&&typeof h.then=="function"?h.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),m.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw m.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}):(m.end(0),h)}catch(h){let g=h?.status||500;throw m.end(g,{"error.message":h?.message,"error.type":h?.name||"Error","http.response.status_code":g}),h}}):o.call(this,c,u)});typeof r._request=="function"&&y(r,"_request","senzor.openai.client._request",i=>function(a,...c){let u=a?.path||"",p=a?.method||"POST",d=po(u),f=fo(a?.body),l=f?`OpenAI ${d} ${f}`:`OpenAI ${d}`,m=b(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":p,"url.path":u,library:"openai"},t);return m?S(m,()=>{try{let h=i.call(this,a,...c);return h&&typeof h.then=="function"?h.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),m.end(0,C),g},g=>{throw m.end(g?.status||500,{"error.message":g?.message,"error.type":g?.name||"OpenAIError"}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):i.call(this,a,...c)})},Ri=e=>{k("openai",t=>{Ei(t,e)})}});var go={};A(go,{instrumentAnthropic:()=>Ti});var Ai,ho,yo,zi,Ti,bo=_(()=>{"use strict";T();z();O();Ai={messages:"messages","messages/batches":"messages.batches",completions:"completions"},ho=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"");for(let[n,r]of Object.entries(Ai))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},yo=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},zi=(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,u){let p=ho(c),d=yo(u?.body),f=i.toUpperCase(),l=d?`Anthropic ${p} ${d}`:`Anthropic ${p}`,m=b(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":p,"gen_ai.request.model":d,"gen_ai.request.max_tokens":u?.body?.max_tokens,"gen_ai.request.temperature":u?.body?.temperature,"gen_ai.request.top_p":u?.body?.top_p,"http.request.method":f,"url.path":c,library:"anthropic"},t);return m?S(m,()=>{try{let h=o.call(this,c,u);return h&&typeof h.then=="function"?h.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),m.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw m.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}):(m.end(0),h)}catch(h){throw m.end(h?.status||500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}}):o.call(this,c,u)});typeof r._request=="function"&&y(r,"_request","senzor.anthropic.client._request",i=>function(a,...c){let u=a?.path||"",p=a?.method||"POST",d=ho(u),f=yo(a?.body),l=f?`Anthropic ${d} ${f}`:`Anthropic ${d}`,m=b(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":p,"url.path":u,library:"anthropic"},t);return m?S(m,()=>{try{let h=i.call(this,a,...c);return h&&typeof h.then=="function"?h.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),m.end(0,C),g},g=>{throw m.end(g?.status||500,{"error.message":g?.message}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):i.call(this,a,...c)})},Ti=e=>{k("@anthropic-ai/sdk",t=>{zi(t,e)})}});var ko={};A(ko,{instrumentGoogleGenAI:()=>Mi});var So,St,Oi,xi,Mi,Co=_(()=>{"use strict";T();z();O();So=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},St=e=>{let t=e?.response||e;return So(t)},Oi=(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",u=b(`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 u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,St(d)),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"GoogleGenAIError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):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",u=b(`Gemini generateContentStream ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"generateContentStream","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(d?.response&&typeof d.response.then=="function"?d.response.then(f=>u.end(0,So(f)),()=>u.end(0)):u.end(0),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):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",u=b(`Gemini countTokens ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"countTokens","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,{"gen_ai.usage.total_tokens":d?.totalTokens}),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):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",u=b(`Gemini embedContent ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"embedContent","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):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 u=this.model||this._model||"unknown",p=i==="sendMessageStream",d=b(`Gemini chat.${i} ${u}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":p?"chat.stream":"chat","gen_ai.request.model":u,library:"google-genai"},t);return d?S(d,()=>{try{let f=o.apply(this,c);return f&&typeof f.then=="function"?f.then(l=>(d.end(0,St(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)})}},xi=(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",u=b(`VertexAI ${s} ${c}`,"http",{"gen_ai.system":"vertex_ai","gen_ai.operation.name":s,"gen_ai.request.model":c,library:"vertex-ai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,St(d)),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)})},Mi=e=>{k("@google/generative-ai",t=>{Oi(t,e)}),k("@google-cloud/vertexai",t=>{xi(t,e)})}});var _o={};A(_o,{instrumentAzureOpenAI:()=>Pi});var Ii,vi,Pi,wo=_(()=>{"use strict";T();z();O();Ii=[{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:()=>({})}],vi=(e,t)=>{let n=e?.OpenAIClient;if(!n?.prototype)return;let r=n.prototype;for(let s of Ii)typeof r[s.name]=="function"&&y(r,s.name,`senzor.azure-openai.${s.name}`,i=>function(a,...c){let u=b(`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 u?S(u,()=>{try{let p=i.call(this,a,...c);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,s.extractUsage(d)),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"AzureOpenAIError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a,...c)})},Pi=e=>{k("@azure/openai",t=>{vi(t,e)})}});var Eo={};A(Eo,{instrumentCohere:()=>Ni});var qi,kt,Ni,Ro=_(()=>{"use strict";T();z();O();qi=[{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:()=>({})}],kt=(e,t,n)=>{if(e)for(let r of qi)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}`,u=b(c,"http",{"gen_ai.system":"cohere","gen_ai.operation.name":r.operation,"gen_ai.request.model":a,library:"cohere"},n);return u?S(u,()=>{try{let p=s.apply(this,o);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,r.extractUsage(d)),d),d=>{throw u.end(d?.statusCode||d?.status||500,{"error.message":d?.message,"error.type":d?.name||"CohereError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):s.apply(this,o)})},Ni=e=>{k("cohere-ai",t=>{t?.CohereClient?.prototype&&kt(t.CohereClient.prototype,"client",e),t?.CohereClientV2?.prototype&&kt(t.CohereClientV2.prototype,"clientV2",e),t?.default?.prototype&&kt(t.default.prototype,"default",e)})}});var Ao={};A(Ao,{instrumentMistral:()=>$i});var Be,Ce,Li,$i,zo=_(()=>{"use strict";T();z();O();Be=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},Ce=(e,t,n,r,s,i,o)=>{!e||typeof e[t]!="function"||y(e,t,i,a=>function(...u){let p=r(u),d=p?`Mistral ${n} ${p}`:`Mistral ${n}`,f=b(d,"http",{"gen_ai.system":"mistral","gen_ai.operation.name":n,"gen_ai.request.model":p,library:"mistral"},o);return f?S(f,()=>{try{let l=a.apply(this,u);return l&&typeof l.then=="function"?l.then(m=>(f.end(0,s(m)),m),m=>{throw f.end(m?.statusCode||m?.status||500,{"error.message":m?.message,"error.type":m?.name||"MistralError"}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):a.apply(this,u)})},Li=(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,...u){let d=(u[0]?.body||u[0])?.model,f=c?.replace(/^\/?(v1\/)?/,"").split("/")[0]||"api",l=d?`Mistral ${f} ${d}`:`Mistral ${f}`,m=b(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 m?S(m,()=>{try{let h=o.call(this,c,...u);return h&&typeof h.then=="function"?h.then(g=>(m.end(0,Be(g)),g),g=>{throw m.end(g?.status||500,{"error.message":g?.message}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):o.call(this,c,...u)});try{let i=new n({apiKey:"__senzor_probe__"});if(i.chat){let o=Object.getPrototypeOf(i.chat);o&&(Ce(o,"complete","chat",a=>a[0]?.model,Be,"senzor.mistral.chat.complete",t),Ce(o,"stream","chat.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.chat.stream",t))}if(i.embeddings){let o=Object.getPrototypeOf(i.embeddings);o&&Ce(o,"create","embeddings",a=>a[0]?.model,Be,"senzor.mistral.embeddings.create",t)}if(i.fim){let o=Object.getPrototypeOf(i.fim);o&&(Ce(o,"complete","fim",a=>a[0]?.model,Be,"senzor.mistral.fim.complete",t),Ce(o,"stream","fim.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.fim.stream",t))}}catch{}},$i=e=>{k("@mistralai/mistralai",t=>{Li(t,e)})}});var Oo={};A(Oo,{instrumentFirebase:()=>ji});var D,L,j,To,Ui,Fi,Di,Hi,ji,xo=_(()=>{"use strict";T();z();O();D=(e,t,n,r,s)=>{!e||typeof e[t]!="function"||y(e,t,r,i=>function(...a){let{name:c,meta:u}=n(this,a),p=b(c,"db",u,s);return p?S(p,()=>{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),p.end(0,l),f},f=>{throw p.end(f?.code||500,{"error.message":f?.message,"error.type":f?.name||"FirestoreError","db.error.code":f?.code}),f}):(p.end(0),d)}catch(d){throw p.end(500,{"error.message":d?.message}),d}}):i.apply(this,a)})},L=e=>{try{return e?.path||e?._path?.toString()||"unknown"}catch{return"unknown"}},j=e=>{try{return e?.parent?.id?e.parent.id:e?.id?e.id:e?._query?._path?e._query._path.toString().split("/").pop()||"unknown":L(e).split("/").filter(Boolean).slice(-2,-1)[0]||"unknown"}catch{return"unknown"}},To=(e,t)=>{let n=e?.DocumentReference;if(n?.prototype){let a=n.prototype;D(a,"get",c=>({name:`Firestore GET ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"GET","db.collection.name":j(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.get",t),D(a,"set",c=>({name:`Firestore SET ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"SET","db.collection.name":j(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.set",t),D(a,"update",c=>({name:`Firestore UPDATE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"UPDATE","db.collection.name":j(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.update",t),D(a,"delete",c=>({name:`Firestore DELETE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"DELETE","db.collection.name":j(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.delete",t),typeof a.create=="function"&&D(a,"create",c=>({name:`Firestore CREATE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"CREATE","db.collection.name":j(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 ${L(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"ADD","db.collection.name":j(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 ${L(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"LIST","db.collection.name":j(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 ${j(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"QUERY","db.collection.name":j(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,u)=>({name:`Firestore TX GET ${L(u[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)},Ui=["createUser","getUser","getUserByEmail","getUserByPhoneNumber","listUsers","deleteUser","deleteUsers","updateUser","verifyIdToken","verifySessionCookie","createSessionCookie","revokeRefreshTokens","setCustomUserClaims","generateEmailVerificationLink","generatePasswordResetLink","generateSignInWithEmailLink"],Fi=(e,t)=>{let n=e?.Auth;if(n?.prototype)for(let r of Ui)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.auth.${r}`,s=>function(...o){let a=b(`Firebase Auth ${r}`,"function",{"firebase.service":"auth","firebase.operation":r,library:"firebase-admin"},t);return a?S(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(u=>(a.end(0),u),u=>{throw a.end(500,{"error.message":u?.message,"error.type":u?.code||u?.name||"AuthError"}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},Di=["send","sendEach","sendEachForMulticast","sendMulticast","sendToDevice","sendToTopic","sendToCondition","subscribeToTopic","unsubscribeFromTopic"],Hi=(e,t)=>{let n=e?.Messaging;if(n?.prototype)for(let r of Di)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.messaging.${r}`,s=>function(...o){let a=b(`Firebase FCM ${r}`,"messaging",{"firebase.service":"messaging","firebase.operation":r,"messaging.system":"fcm",library:"firebase-admin"},t);return a?S(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(u=>{let p={};return u?.successCount!==void 0&&(p["firebase.fcm.success_count"]=u.successCount,p["firebase.fcm.failure_count"]=u.failureCount),a.end(0,p),u},u=>{throw a.end(500,{"error.message":u?.message}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},ji=e=>{k("firebase-admin/firestore",t=>{To(t,e)}),k("@google-cloud/firestore",t=>{To(t,e)}),k("firebase-admin/auth",t=>{Fi(t,e)}),k("firebase-admin/messaging",t=>{Hi(t,e)}),k("firebase-admin",t=>{try{let n=t?.firestore}catch{}})}});we();var Ee=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 zt=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",W=()=>zt;var I=e=>{if(zt)return process.env[e]};var Ze={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 Ve={name:Ze.name,version:Ze.version};Z();Ye();H();O();var Ko={1:"minorCount",2:"majorCount",4:"incrementalCount",8:"weakCallbackCount"},et=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=Ko[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}},tt=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{}}},nt=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 et;this.lagMeter=new tt;this.eluMeter=new nt;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 p=process.cpuUsage(this.lastCpu);i=p.user,o=p.system}this.lastCpu=process.cpuUsage()}catch{}let a=0,c=0;try{a=process._getActiveHandles?.()?.length??0,c=process._getActiveRequests?.()?.length??0}catch{}let u={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:u})}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.gcObserver.stop(),this.lagMeter.stop(),this.started=!1}};var Bi=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})},Ct=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 Ee({...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}=(at(),R(st));r(t,this.options||void 0)}}catch{}if(W()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(at(),R(st));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(Kt(),R(Gt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(en(),R(Xt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(sn(),R(on));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(cn(),R(an));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(fn(),R(dn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(gn(),R(yn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(Sn(),R(bn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(_n(),R(Cn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(En(),R(wn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(Tn(),R(zn));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=(In(),R(Mn));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("grpc")){let{instrumentGrpc:r}=(Ln(),R(Nn));r(this,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("graphql")){let{instrumentGraphQL:r}=(Hn(),R(Dn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dns")){let{instrumentDns:r}=(Bn(),R(jn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("net")){let{instrumentNet:r}=(Qn(),R(Wn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("kafka")){let{instrumentKafka:r}=(Xn(),R(Jn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("amqplib")){let{instrumentAmqplib:r}=(ar(),R(sr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("socketio")){let{instrumentSocketIO:r}=(ur(),R(cr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("nestjs")){let{instrumentNestJS:r}=(fr(),R(dr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("hapi")){let{instrumentHapi:r}=(gr(),R(yr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pino")){let{instrumentPino:r}=(kr(),R(Sr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("winston")){let{instrumentWinston:r}=(Er(),R(wr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bunyan")){let{instrumentBunyan:r}=(zr(),R(Ar));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("aws-sdk")){let{instrumentAwsSdk:r}=(Mr(),R(xr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("knex")){let{instrumentKnex:r}=(qr(),R(Pr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("tedious")){let{instrumentTedious:r}=(Lr(),R(Nr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cassandra")){let{instrumentCassandra:r}=(Dr(),R(Fr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("memcached")){let{instrumentMemcached:r}=(Br(),R(jr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("generic-pool")){let{instrumentGenericPool:r}=(Gr(),R(Qr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("restify")){let{instrumentRestify:r}=(Zr(),R(Kr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("connect")){let{instrumentConnect:r}=(Jr(),R(Yr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dataloader")){let{instrumentDataloader:r}=(to(),R(eo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("lru-memoizer")){let{instrumentLruMemoizer:r}=(so(),R(oo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fs")){let{instrumentFs:r}=(uo(),R(co));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("openai")){let{instrumentOpenAI:r}=(mo(),R(lo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("anthropic")){let{instrumentAnthropic:r}=(bo(),R(go));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("google-genai")){let{instrumentGoogleGenAI:r}=(Co(),R(ko));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("azure-openai")){let{instrumentAzureOpenAI:r}=(wo(),R(_o));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cohere")){let{instrumentCohere:r}=(Ro(),R(Eo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mistral")){let{instrumentMistral:r}=(zo(),R(Ao));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("firebase")){let{instrumentFirebase:r}=(xo(),R(Oo));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(Bi(d));a={...a,...X(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(),u=c?.contextType==="task"?"task":"apm",p={message:o||"Empty log",level:s==="log"?"info":s,attributes:a,timestamp:new Date().toISOString()};c&&(u==="task"?p.runId=c.id:p.traceId=c.id),this.transport.addLog(p,u)}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:Ve.name,version:Ve.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 u=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},p=u("traceparent"),d=Q(p);if(d)s=d.traceId,i=d.parentSpanId;else{let f=u("x-senzor-trace-id"),l=u("x-senzor-parent-span-id");s=Array.isArray(f)?f[0]:f,i=Array.isArray(l)?l[0]:l}}let o=s||Ae(),a=ye(),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,u={id:Ae(),contextType:"task",startTime:performance.now(),rootSpanId:ye(),startMemory:a,startCpu:c,data:{taskName:t,taskType:n,triggerTraceId:o,...r},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return u.activeSpanId=u.rootSpanId,E.run(u,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:X(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:Ae(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=b(t,n,{},this.options||void 0);return r?{end:(s,i)=>r.end(i,s)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},B=new Ct;ee();rt();var _t=!0,Wi=e=>!e||typeof e!="object"?"generic":e.requestContext?.http?.method?"api-gateway-v2":e.requestContext?.httpMethod||e.httpMethod?"api-gateway-v1":e.requestContext?.elb?"alb":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:sqs"?"sqs":Array.isArray(e.Records)&&e.Records[0]?.EventSource==="aws:sns"?"sns":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:dynamodb"?"dynamodb-streams":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:s3"?"s3":e.source&&e["detail-type"]&&e.detail?"eventbridge":e.source==="aws.events"||e["detail-type"]==="Scheduled Event"?"scheduled":"generic",Qi=(e,t)=>t==="api-gateway-v2"?{method:e.requestContext?.http?.method||"GET",path:e.rawPath||e.requestContext?.http?.path||"/",headers:wt(e.headers)}:t==="api-gateway-v1"?{method:e.httpMethod||e.requestContext?.httpMethod||"GET",path:e.path||e.resource||"/",headers:wt(e.headers)}:t==="alb"?{method:e.httpMethod||"GET",path:e.path||"/",headers:wt(e.headers)}:null,wt=e=>{if(!e||typeof e!="object")return{};let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=String(r);return t},Gi=(e,t,n,r)=>{let s={"faas.trigger":Ki(n),"faas.coldstart":r,"cloud.provider":"aws","cloud.platform":"aws_lambda","firebase.service":void 0,library:"aws-lambda"};t&&(t.functionName&&(s["faas.name"]=t.functionName),t.functionVersion&&(s["faas.version"]=t.functionVersion),t.awsRequestId&&(s["faas.execution"]=t.awsRequestId),t.invokedFunctionArn&&(s["cloud.resource_id"]=t.invokedFunctionArn),t.memoryLimitInMB&&(s["faas.max_memory"]=Number(t.memoryLimitInMB)),t.logGroupName&&(s["aws.log.group.names"]=t.logGroupName),t.logStreamName&&(s["aws.log.stream.names"]=t.logStreamName));let i=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(i&&(s["cloud.region"]=i),t?.invokedFunctionArn){let o=t.invokedFunctionArn.split(":");o.length>=5&&(s["cloud.account.id"]=o[4])}switch(n){case"sqs":if(Array.isArray(e.Records)){s["messaging.system"]="aws_sqs",s["messaging.batch.message_count"]=e.Records.length;let o=e.Records[0]?.eventSourceARN;o&&(s["messaging.source.name"]=o.split(":").pop())}break;case"sns":if(Array.isArray(e.Records)){s["messaging.system"]="aws_sns";let o=e.Records[0]?.Sns?.TopicArn;o&&(s["messaging.source.name"]=o.split(":").pop())}break;case"dynamodb-streams":Array.isArray(e.Records)&&(s["aws.dynamodb.table_names"]=[...new Set(e.Records.map(o=>o.eventSourceARN?.split("/")[1]).filter(Boolean))],s["messaging.batch.message_count"]=e.Records.length);break;case"s3":Array.isArray(e.Records)&&e.Records[0]?.s3&&(s["aws.s3.bucket"]=e.Records[0].s3.bucket?.name,s["aws.s3.key"]=e.Records[0].s3.object?.key);break;case"eventbridge":e.source&&(s["aws.eventbridge.source"]=e.source),e["detail-type"]&&(s["aws.eventbridge.detail_type"]=e["detail-type"]);break}return s},Ki=e=>{switch(e){case"api-gateway-v1":case"api-gateway-v2":case"alb":return"http";case"sqs":case"sns":return"pubsub";case"dynamodb-streams":return"datasource";case"s3":return"datasource";case"eventbridge":case"scheduled":return"timer";default:return"other"}},Zi=(e,t)=>(t==="api-gateway-v1"||t==="api-gateway-v2"||t==="alb")&&e&&typeof e=="object"&&typeof e.statusCode=="number"?e.statusCode:200,Vi=(()=>{let e=!1;return t=>{if(e)return;e=!0;let n=process.env.AWS_LAMBDA_RUNTIME_API;if(!n)return;let r="senzor-apm",s=`http://${n}/2020-01-01/extension/register`;(async()=>{try{let i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","Lambda-Extension-Name":r},body:JSON.stringify({events:["SHUTDOWN"]})});if(!i.ok)return;let o=i.headers.get("Lambda-Extension-Identifier");if(!o)return;let a=`http://${n}/2020-01-01/extension/event/next`;(async()=>{try{let u=await fetch(a,{method:"GET",headers:{"Lambda-Extension-Identifier":o}});u.ok&&(await u.json()).eventType==="SHUTDOWN"&&await t()}catch{}})()}catch{}})()}})(),Mo=e=>(Vi(()=>B.flush()),async(t,n)=>{let r=_t;_t&&(_t=!1);let s=Wi(t),i=Gi(t,n,s,r),o=Qi(t,s),a=o?.method||s.toUpperCase(),c=o?.path||`/${n?.functionName||"lambda"}`,u=o?U(o.path):n?.functionName||"lambda",p=o?.headers||{};return B.startTrace({method:a,path:c,route:u,ip:o?Te({headers:p}):void 0,userAgent:p["user-agent"],headers:p,...i},async()=>{let d=500;try{let f=await e(t,n);return d=Zi(f,s),f}catch(f){throw B.captureError(f,{"faas.name":n?.functionName,"faas.execution":n?.awsRequestId,trigger:s}),f}finally{B.endTrace(d,{route:u,...i}),await B.flush()}})});import*as vo from"path";var Rt=e=>e==="1"||e==="true"||e==="yes",le=e=>{if(!e)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},Po=I("SENZOR_API_KEY")||I("SENZOR_APM_API_KEY")||I("SENZOR_SERVICE_API_KEY"),Yi=I("SENZOR_ENDPOINT")||I("SENZOR_APM_ENDPOINT"),Et=!!I("AWS_LAMBDA_FUNCTION_NAME"),Io={apiKey:Po||"",endpoint:Yi,debug:Rt(I("SENZOR_DEBUG")),autoLogs:I("SENZOR_AUTO_LOGS")==="false"?!1:void 0,batchSize:le(I("SENZOR_BATCH_SIZE"))??(Et?10:void 0),flushInterval:le(I("SENZOR_FLUSH_INTERVAL"))??(Et?0:void 0),flushTimeoutMs:le(I("SENZOR_FLUSH_TIMEOUT_MS")),maxQueueSize:le(I("SENZOR_MAX_QUEUE_SIZE")),maxSpansPerTrace:le(I("SENZOR_MAX_SPANS_PER_TRACE")),captureHeaders:Rt(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"||Et?!1:void 0,runtimeMetricsInterval:le(I("SENZOR_RUNTIME_METRICS_INTERVAL"))};Po?B.init(Io):B.preload(Io);var Ji=e=>{let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n=t>=0?e.substring(t+1):e,r=t>=0?e.substring(0,t+1):"",s=n.indexOf(".");if(s<0)return{modulePath:e,fnPath:["handler"]};let i=n.substring(0,s),o=n.substring(s+1).split(".");return{modulePath:r+i,fnPath:o}},Xi=(e,t)=>{let n=e;for(let r of t){if(n==null||typeof n!="object")return null;n=n[r]}if(n==null&&e?.default){n=e.default;for(let r of t){if(n==null||typeof n!="object")return null;n=n[r]}}return typeof n=="function"?n:null},ec=e=>{let t=process.env.LAMBDA_TASK_ROOT||process.cwd(),n=vo.resolve(t,e);try{return M(n)}catch{}let r=[".js",".cjs",".mjs"];for(let s of r)try{return M(n+s)}catch{}try{return M(e)}catch{}return null},We=I("SENZOR_LAMBDA_HANDLER"),_e;if(!We)_e=async()=>{let e='Senzor Lambda Layer: SENZOR_LAMBDA_HANDLER environment variable is not set. Set it to your original handler (e.g., "index.handler") and set the Lambda function handler to "@senzops/apm-node/dist/lambda-handler.handler".';return console.error(`[Senzor] ${e}`),{statusCode:500,body:JSON.stringify({error:e})}};else{let{modulePath:e,fnPath:t}=Ji(We),n=ec(e);if(n){let r=Xi(n,t);if(r)_e=Mo(r),Rt(I("SENZOR_DEBUG"))&&console.log(`[Senzor] Lambda handler wrapped: ${We} \u2192 module="${e}", export="${t.join(".")}"`);else{let s=`Senzor Lambda Layer: Module "${e}" loaded successfully but export "${t.join(".")}" is not a function. Available exports: ${Object.keys(n).join(", ")}`;console.error(`[Senzor] ${s}`),_e=async()=>({statusCode:500,body:JSON.stringify({error:s})})}}else{let r=`Senzor Lambda Layer: Could not load handler module "${e}" (from SENZOR_LAMBDA_HANDLER="${We}"). Verify the module path exists relative to your Lambda function code.`;console.error(`[Senzor] ${r}`),_e=async()=>({statusCode:500,body:JSON.stringify({error:r})})}}var zd=_e;export{zd as handler};
2
+ //# sourceMappingURL=lambda-handler.mjs.map