@senzops/apm-node 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,56 +1,48 @@
1
1
  # **@senzops/apm-node**
2
2
 
3
- The official Node.js middleware for **Senzor APM**.
3
+ The official Node.js SDK for **Senzor APM**.
4
4
 
5
- Zero-overhead, asynchronous, and robust monitoring for your Express/Next.js APIs.
5
+ A lightweight, zero-dependency, and universal APM client for modern JavaScript runtimes.
6
+
7
+ ## **✨ Features**
8
+
9
+ * **Universal Support:** Works in Node.js (18+), Edge, and Serverless environments.
10
+ * **Auto-Instrumentation:** Automatically captures HTTP calls (Axios/Fetch), MongoDB queries, and Postgres queries.
11
+ * **Framework Agnostic:** Built-in wrappers for Express, Next.js, Fastify, and Nuxt (Nitro).
12
+ * **Distributed Tracing:** Captures full waterfall execution graphs (Spans).
13
+ * **Zero Overhead:** Uses async_hooks and non-blocking transports.
6
14
 
7
15
  ## **📦 Installation**
8
16
  ```sh
9
- npm install @senzops/apm-node
17
+ npm install @senzops/apm-node
18
+ # or
19
+ yarn add @senzops/apm-node
10
20
  ```
21
+ ## **🚀 Quick Start (Express.js)**
11
22
 
12
- ## **🚀 Usage**
13
-
14
- ### **Express.js**
15
-
16
- Add Senzor as the **first** middleware in your app to ensure accurate timing.
23
+ Add Senzor as the **first middleware** in your app.
17
24
  ```js
18
25
  const express = require('express');
19
- const senzor = require('@senzops/apm-node');
26
+ const Senzor = require('@senzops/apm-node');
20
27
 
21
28
  const app = express();
22
29
 
23
- // 1\. Initialize
24
- senzor.init({
25
- apiKey: "sz_apm_...", // Get this from your Senzor Dashboard
26
- // Optional config
27
- // debug: true,
30
+ // 1. Initialize
31
+ Senzor.init({
32
+ apiKey: "sz_apm_...", // Get from Senzor Dashboard
28
33
  });
29
34
 
30
- // 2\. Attach Request Handler
31
- app.use(senzor.requestHandler());
35
+ // 2. Attach Request Handler
36
+ app.use(Senzor.requestHandler());
32
37
 
33
38
  // ... your routes ...
34
- app.get('/users/:id', (req, res) => {
35
- res.json({ id: req.params.id });
39
+ app.get('/', async (req, res) => {
40
+ // Database calls here are automatically traced\!
41
+ res.json({ hello: 'world' });
36
42
  });
37
43
 
38
44
  app.listen(3000);
39
45
  ```
46
+ ## **📚 Documentation**
40
47
 
41
- ## **⚙️ Configuration**
42
-
43
- | Option | Type | Description |
44
- | :------------ | :------ | :------------------------------------------------------------ |
45
- | apiKey | string | **Required.** Your Service API Key. |
46
- | batchSize | number | Max requests to buffer before sending (Default: 100). |
47
- | flushInterval | number | Max time (ms) to wait before sending buffer (Default: 10000). |
48
- | debug | boolean | Enable console logs for debugging connection issues. |
49
-
50
- ## **🛡 Performance**
51
-
52
- Senzor APM is designed to be **Production Safe**:
53
-
54
- 1. **Non-Blocking:** Data transmission happens asynchronously outside the request-response cycle.
55
- 2. **Fail-Open:** If Senzor ingestion is down, your API will continue to function normally without error.
56
- 3. **Lightweight:** Uses native Node.js timers and buffers. No heavy dependencies.
48
+ For detailed usage with **Next.js**, **NestJS**, **Fastify**, or **Manual Instrumentation**, please read our [**Detailed Wiki**](./wiki.md).
package/dist/index.d.mts CHANGED
@@ -9,7 +9,13 @@ interface SenzorOptions {
9
9
  declare const Senzor: {
10
10
  init: (options: SenzorOptions) => void;
11
11
  flush: () => Promise<void>;
12
+ track: (data: any) => void;
13
+ startSpan: (name: string, type?: "db" | "http" | "function" | "custom") => {
14
+ end: (meta?: any, status?: number) => void;
15
+ };
16
+ captureException: (error: unknown) => void;
12
17
  requestHandler: () => (req: any, res: any, next: () => void) => void;
18
+ errorHandler: () => (err: any, req: any, res: any, next: (err?: any) => void) => void;
13
19
  wrapNextRoute: (handler: Function) => (req: Request | any, context?: any) => Promise<any>;
14
20
  wrapNextPages: (handler: Function) => (req: any, res: any) => Promise<any>;
15
21
  wrapH3: (handler: (event: any) => any) => (event: any) => Promise<any>;
package/dist/index.d.ts CHANGED
@@ -9,7 +9,13 @@ interface SenzorOptions {
9
9
  declare const Senzor: {
10
10
  init: (options: SenzorOptions) => void;
11
11
  flush: () => Promise<void>;
12
+ track: (data: any) => void;
13
+ startSpan: (name: string, type?: "db" | "http" | "function" | "custom") => {
14
+ end: (meta?: any, status?: number) => void;
15
+ };
16
+ captureException: (error: unknown) => void;
12
17
  requestHandler: () => (req: any, res: any, next: () => void) => void;
18
+ errorHandler: () => (err: any, req: any, res: any, next: (err?: any) => void) => void;
13
19
  wrapNextRoute: (handler: Function) => (req: Request | any, context?: any) => Promise<any>;
14
20
  wrapNextPages: (handler: Function) => (req: any, res: any) => Promise<any>;
15
21
  wrapH3: (handler: (event: any) => any) => (event: any) => Promise<any>;
@@ -1,2 +1,2 @@
1
- "use strict";(()=>{var j=Object.create;var k=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty;var T=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var X=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of J(t))!V.call(e,o)&&o!==r&&k(e,o,{get:()=>t[o],enumerable:!(n=B(t,o))||n.enumerable});return e};var E=(e,t,r)=>(r=e!=null?j(Q(e)):{},X(t||!e||!e.__esModule?k(r,"default",{value:e,enumerable:!0}):r,e));var z=class{constructor(t){this.config=t;this.queue=[];this.timer=null;typeof setInterval<"u"&&(this.timer=setInterval(()=>this.flush(),t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}add(t){this.queue.push(t),this.queue.length>=(this.config.batchSize||100)&&this.flush()}async flush(){if(this.queue.length===0)return;let t=[...this.queue];this.queue=[];try{await fetch(this.config.endpoint||"https://api.senzor.dev/api/ingest/apm",{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey},body:JSON.stringify(t),keepalive:!0}),this.config.debug&&console.log(`[Senzor] Flushed ${t.length} traces`)}catch(r){this.config.debug&&console.error("[Senzor] Ingestion Error:",r)}}};var M=T("async_hooks"),F=new M.AsyncLocalStorage,l={run:(e,t)=>F.run(e,t),current:()=>F.getStore(),addSpan:e=>{let t=F.getStore();t?t.spans.push(e):console.warn("[Senzor] Lost context for span:",e.name)}};var I=T("crypto");var v=E(T("http")),O=E(T("https")),x=T("url");var C=(e,t,r)=>{if(!e[t])return;let n=e[t];e[t]=r(n)},N=(e,t=!1)=>{if(!globalThis.fetch)return;let r="";try{r=new x.URL(e).hostname}catch{}let n=globalThis.fetch;globalThis.fetch=async(o,a)=>{let i="";if(typeof o=="string"?i=o:o instanceof x.URL?i=o.toString():o&&o.url&&(i=o.url),r&&i.includes(r))return n(o,a);let c=l.current();if(!c)return n(o,a);let s=(a?.method||"GET").toUpperCase(),f=performance.now()-c.startTime,w=performance.now(),d="unknown";try{d=new x.URL(i).hostname}catch{}t&&console.log(`[Senzor] Tracking Fetch: ${s} ${d}`);try{let p=await n(o,a),h=performance.now()-w;return l.addSpan({name:`${s} ${d}`,type:"http",startTime:f,duration:h,status:p.status,meta:{url:i,method:s,library:"fetch"}}),p}catch(p){let h=performance.now()-w;throw l.addSpan({name:`${s} ${d}`,type:"http",startTime:f,duration:h,status:500,meta:{error:p.message,url:i,library:"fetch"}}),p}}},R=(e,t=!1)=>{let r="";try{r=new x.URL(e).hostname}catch{}let n=o=>function(...a){let i={},c="";if(typeof a[0]=="string"||a[0]instanceof x.URL)c=a[0].toString(),typeof a[1]=="object"&&a[1]!==null&&(i=a[1]);else{i=a[0]||{};let u=i.protocol||(i.port===443?"https:":"http:"),g=i.hostname||i.host||"localhost",b=i.path||"/";c=`${u}//${g}${b}`}if(r&&(c.includes(r)||i.hostname&&i.hostname.includes(r)))return o.apply(this,a);let s=l.current();if(!s)return o.apply(this,a);let f=(i.method||"GET").toUpperCase(),w=performance.now()-s.startTime,d=performance.now(),p="unknown";try{p=new x.URL(c).hostname}catch{p=i.hostname||"unknown"}let h=o.apply(this,a),y=(u,g)=>{let b=performance.now()-d;l.addSpan({name:`${f} ${p}`,type:"http",startTime:w,duration:b,status:g?500:u?.statusCode||0,meta:{url:c,method:f,library:"http"}})};return h.on("response",u=>{u.once("end",()=>y(u)),u.once("error",g=>y(u,g))}),h.on("error",u=>y(null,u)),h};C(v.default,"request",n),C(v.default,"get",n),C(O.default,"request",n),C(O.default,"get",n)};var U=(e=!1)=>{try{let t=T("mongodb"),r=t.Collection,n=t.FindCursor||T("mongodb/lib/cursor/find_cursor").FindCursor,o=t.AggregationCursor||T("mongodb/lib/cursor/aggregation_cursor").AggregationCursor;e&&console.log("[Senzor] Instrumenting MongoDB (Collection + Cursors)...");let a=(s,f,w,d,p,h)=>{let y=performance.now()-d;l.addSpan({name:`MongoDB ${s}`,type:"db",startTime:performance.now()-p-y,duration:y,status:h?500:0,meta:{collection:w,operation:f,error:h?h.message:void 0}}),e&&console.log(`[Senzor] Captured Mongo: ${s} (${y.toFixed(2)}ms)`)};["insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","countDocuments"].forEach(s=>{if(!r.prototype[s])return;let f=r.prototype[s];r.prototype[s]=function(...w){let d=l.current();if(!d)return f.apply(this,w);let p=performance.now(),h=d.startTime,y=this.collectionName;try{let u=f.apply(this,w);return u&&typeof u.then=="function"?u.then(g=>(a(s,s,y,p,h),g),g=>{throw a(s,s,y,p,h,g),g}):u}catch(u){throw a(s,s,y,p,h,u),u}}});let c=(s,f)=>{if(!s||!s.prototype.toArray)return;let w=s.prototype.toArray;s.prototype.toArray=function(...d){let p=l.current();if(!p)return w.apply(this,d);let h=performance.now(),y=p.startTime,u=this.namespace?.collection||"unknown",g=S=>(a(f,f,u,h,y),S),b=S=>{throw a(f,f,u,h,y,S),S};try{let S=w.apply(this,d);return S&&typeof S.then=="function"?S.then(g,b):g(S)}catch(S){b(S)}}};c(n,"find"),c(o,"aggregate")}catch(t){e&&console.warn("[Senzor] MongoDB instrumentation warning:",t.message)}};var H=()=>{try{let e=T("pg"),t=e.Client.prototype.query;e.Client.prototype.query=function(...r){let n=l.current();if(!n)return t.apply(this,r);let o=performance.now()-n.startTime,a=performance.now(),i=typeof r[0]=="string"?r[0]:r[0].text,c=t.apply(this,r);return c&&typeof c.then=="function"?c.then(s=>{let f=performance.now()-a;return l.addSpan({name:"Postgres Query",type:"db",startTime:o,duration:f,meta:{query:i}}),s}):c}}catch{}};var P=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;if(this.transport=new z({...t,endpoint:r}),!this.isInstrumented){try{R(r,n)}catch{}try{N(r,n)}catch{}try{U(n)}catch{}try{H()}catch{}this.isInstrumented=!0,n&&console.log("[Senzor] Auto-instrumentation enabled (HTTP, Fetch, Mongo)")}}startTrace(t,r){if(!this.transport)return r();let n={id:(0,I.randomUUID)(),startTime:performance.now(),data:t,spans:[]};return l.run(n,r)}endTrace(t,r={}){let n=l.current();if(!n||!this.transport)return;let o=performance.now()-n.startTime,a={traceId:n.id,...n.data,...r,status:t,duration:o,spans:n.spans,timestamp:new Date().toISOString()};this.transport.add(a)}track(t){this.transport?.add({traceId:(0,I.randomUUID)(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,r="custom"){let n=l.current();if(!n)return{end:()=>{}};let o=performance.now()-n.startTime,a=performance.now();return{end:(i,c)=>{l.addSpan({name:t,type:r,startTime:o,duration:performance.now()-a,status:c,meta:i})}}}async flush(){this.transport&&await this.transport.flush()}},m=new P;var D=()=>(e,t,r)=>{m.startTrace({method:e.method,path:e.originalUrl||e.url,ip:e.ip||e.socket?.remoteAddress,userAgent:e.headers["user-agent"]},()=>{t.once("finish",()=>{try{let n="UNKNOWN";e.route&&e.route.path?n=(e.baseUrl||"")+e.route.path:t.statusCode===404?n="Not Found":n=e.path||"Wildcard",m.endTrace(t.statusCode,{route:n})}catch{}}),r()})};var A=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],$=(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:A(t);var K=e=>t=>{let r=t.node.req,n=r.originalUrl||r.url||"/";return m.startTrace({method:r.method||"GET",path:n,ip:r.headers["x-forwarded-for"]||r.socket?.remoteAddress,userAgent:r.headers["user-agent"]},async()=>{try{let o=await e(t),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),o&&o.statusCode&&(a=o.statusCode),m.endTrace(a,{route:$(t,n)}),o}catch(o){let a=o.statusCode||o.status||500;throw m.endTrace(a,{route:$(t,n)}),o}})};var G=e=>async(t,r)=>{let n=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",a=t.headers.get?t.headers.get("user-agent"):void 0,i=t.headers.get?t.headers.get("x-forwarded-for"):void 0;return m.startTrace({method:o,path:n.pathname,userAgent:a,ip:i},async()=>{try{let c=await e(t,r),s=c?.status||200;return m.endTrace(s,{route:A(n.pathname)}),c}catch(c){throw m.endTrace(500,{route:A(n.pathname)}),c}})},L=e=>async(t,r)=>{let n=t.url?t.url.split("?")[0]:"/";return m.startTrace({method:t.method||"GET",path:n,userAgent:t.headers["user-agent"],ip:t.headers["x-forwarded-for"]||t.socket?.remoteAddress},async()=>{let o=()=>{m.endTrace(r.statusCode||200,{route:A(n)})};r.once("finish",o),r.once("close",o);try{return await e(t,r)}catch(a){throw a}})};var W=(e,t,r)=>{t&&t.apiKey&&m.init(t),e.addHook("onRequest",(n,o,a)=>{n.senzorStart=performance.now(),a()}),e.addHook("onResponse",(n,o,a)=>{let i=performance.now()-(n.senzorStart||performance.now()),c=n.routeOptions?.url||n.routerPath;m.track({method:n.method,route:c||"UNKNOWN",path:n.raw.url||n.url,status:o.statusCode,duration:i,ip:n.ip,userAgent:n.headers["user-agent"]}),a()}),r()};var Y={init:e=>m.init(e),flush:()=>m.flush(),requestHandler:D,wrapNextRoute:G,wrapNextPages:L,wrapH3:K,fastifyPlugin:W},Ot=Y;})();
1
+ "use strict";(()=>{var J=Object.create;var N=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty;var T=(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 Y=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of X(t))!V.call(e,o)&&o!==n&&N(e,o,{get:()=>t[o],enumerable:!(r=Q(t,o))||r.enumerable});return e};var P=(e,t,n)=>(n=e!=null?J(Z(e)):{},Y(t||!e||!e.__esModule?N(n,"default",{value:e,enumerable:!0}):n,e));var E=class{constructor(t){this.config=t;this.queue=[];this.timer=null;typeof setInterval<"u"&&(this.timer=setInterval(()=>this.flush(),t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}add(t){this.queue.push(t),this.queue.length>=(this.config.batchSize||100)&&this.flush()}async flush(){if(this.queue.length===0)return;let t=[...this.queue];this.queue=[];try{await fetch(this.config.endpoint||"https://api.senzor.dev/api/ingest/apm",{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey},body:JSON.stringify(t),keepalive:!0}),this.config.debug&&console.log(`[Senzor] Flushed ${t.length} traces`)}catch(n){this.config.debug&&console.error("[Senzor] Ingestion Error:",n)}}};var H=T("async_hooks"),z=new H.AsyncLocalStorage,l={run:(e,t)=>z.run(e,t),current:()=>z.getStore(),addSpan:e=>{let t=z.getStore();t&&t.spans.push(e)},setError:e=>{let t=z.getStore();t&&(t.error={name:e.name,message:e.message,stack:e.stack})}};var C=T("crypto");var F=P(T("http")),O=P(T("https")),A=T("url");var v=T("crypto"),I=(e,t,n)=>{if(!e[t])return;let r=e[t];e[t]=n(r)},$=(e,t=!1)=>{if(!globalThis.fetch)return;let n="";try{n=new A.URL(e).hostname}catch{}let r=globalThis.fetch;globalThis.fetch=async(o,a)=>{let i="";if(typeof o=="string"?i=o:o instanceof A.URL?i=o.toString():o&&o.url&&(i=o.url),n&&i.includes(n))return r(o,a);let u=l.current();if(!u)return r(o,a);let s=(a?.method||"GET").toUpperCase(),d=performance.now()-u.startTime,S=performance.now(),g=(0,v.randomUUID)(),y="unknown";try{y=new A.URL(i).hostname}catch{}t&&console.log(`[Senzor] Fetch: ${s} ${y}`);let p={...a};p.headers||(p.headers={}),p.headers instanceof Headers?(p.headers.set("x-senzor-trace-id",u.id),p.headers.set("x-senzor-parent-span-id",g)):Array.isArray(p.headers)?(p.headers.push(["x-senzor-trace-id",u.id]),p.headers.push(["x-senzor-parent-span-id",g])):(p.headers["x-senzor-trace-id"]=u.id,p.headers["x-senzor-parent-span-id"]=g);try{let h=await r(o,p),m=performance.now()-S;return l.addSpan({spanId:g,name:`${s} ${y}`,type:"http",startTime:d,duration:m,status:h.status,meta:{url:i,method:s,library:"fetch"}}),h}catch(h){let m=performance.now()-S;throw l.addSpan({spanId:g,name:`${s} ${y}`,type:"http",startTime:d,duration:m,status:500,meta:{error:h.message,url:i,library:"fetch"}}),h}}},U=(e,t=!1)=>{let n="";try{n=new A.URL(e).hostname}catch{}let r=o=>function(...a){let i={},u="";if(typeof a[0]=="string"||a[0]instanceof A.URL)u=a[0].toString(),typeof a[1]=="object"&&a[1]!==null&&(i=a[1]);else{i=a[0]||{};let f=i.protocol||(i.port===443?"https:":"http:"),x=i.hostname||i.host||"localhost",w=i.path||"/";u=`${f}//${x}${w}`}if(n&&(u.includes(n)||i.hostname&&i.hostname.includes(n)))return o.apply(this,a);let s=l.current();if(!s)return o.apply(this,a);let d=(i.method||"GET").toUpperCase(),S=performance.now()-s.startTime,g=performance.now(),y=(0,v.randomUUID)(),p="unknown";try{p=new A.URL(u).hostname}catch{p=i.hostname||"unknown"}i.headers||(i.headers={}),i.headers["x-senzor-trace-id"]=s.id,i.headers["x-senzor-parent-span-id"]=y;let h=o.apply(this,a),m=(f,x)=>{let w=performance.now()-g;l.addSpan({spanId:y,name:`${d} ${p}`,type:"http",startTime:S,duration:w,status:x?500:f?.statusCode||0,meta:{url:u,method:d,library:"http"}})};return h.on("response",f=>{f.once("end",()=>m(f)),f.once("close",()=>m(f)),f.once("error",x=>m(f,x))}),h.on("error",f=>m(null,f)),h};I(F.default,"request",r),I(F.default,"get",r),I(O.default,"request",r),I(O.default,"get",r)};var M=(e=!1)=>{try{let t=T("mongodb"),n=t.Collection,r=t.FindCursor||T("mongodb/lib/cursor/find_cursor").FindCursor,o=t.AggregationCursor||T("mongodb/lib/cursor/aggregation_cursor").AggregationCursor;e&&console.log("[Senzor] Instrumenting MongoDB (Collection + Cursors)...");let a=(s,d,S,g,y,p)=>{let h=performance.now()-g;l.addSpan({name:`MongoDB ${s}`,type:"db",startTime:performance.now()-y-h,duration:h,status:p?500:0,meta:{collection:S,operation:d,error:p?p.message:void 0}}),e&&console.log(`[Senzor] Captured Mongo: ${s} (${h.toFixed(2)}ms)`)};["insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","countDocuments"].forEach(s=>{if(!n.prototype[s])return;let d=n.prototype[s];n.prototype[s]=function(...S){let g=l.current();if(!g)return d.apply(this,S);let y=performance.now(),p=g.startTime,h=this.collectionName;try{let m=d.apply(this,S);return m&&typeof m.then=="function"?m.then(f=>(a(s,s,h,y,p),f),f=>{throw a(s,s,h,y,p,f),f}):m}catch(m){throw a(s,s,h,y,p,m),m}}});let u=(s,d)=>{if(!s||!s.prototype.toArray)return;let S=s.prototype.toArray;s.prototype.toArray=function(...g){let y=l.current();if(!y)return S.apply(this,g);let p=performance.now(),h=y.startTime,m=this.namespace?.collection||"unknown",f=w=>(a(d,d,m,p,h),w),x=w=>{throw a(d,d,m,p,h,w),w};try{let w=S.apply(this,g);return w&&typeof w.then=="function"?w.then(f,x):f(w)}catch(w){x(w)}}};u(r,"find"),u(o,"aggregate")}catch(t){e&&console.warn("[Senzor] MongoDB instrumentation warning:",t.message)}};var D=()=>{try{let e=T("pg"),t=e.Client.prototype.query;e.Client.prototype.query=function(...n){let r=l.current();if(!r)return t.apply(this,n);let o=performance.now()-r.startTime,a=performance.now(),i=typeof n[0]=="string"?n[0]:n[0].text,u=t.apply(this,n);return u&&typeof u.then=="function"?u.then(s=>{let d=performance.now()-a;return l.addSpan({name:"Postgres Query",type:"db",startTime:o,duration:d,meta:{query:i}}),s}):u}}catch{}};var R=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}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;if(this.transport=new E({...t,endpoint:n}),!this.isInstrumented){try{U(n,r)}catch{}try{$(n,r)}catch{}try{M(r)}catch{}try{D()}catch{}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}startTrace(t,n){if(!this.transport)return n();let r,o;t.headers&&(r=t.headers["x-senzor-trace-id"]||t.headers["X-SENZOR-TRACE-ID"],o=t.headers["x-senzor-parent-span-id"]||t.headers["X-SENZOR-PARENT-SPAN-ID"]);let a={id:(0,C.randomUUID)(),startTime:performance.now(),data:{...t,parentTraceId:r,parentSpanId:o},spans:[]};return l.run(a,n)}endTrace(t,n={}){let r=l.current();if(!r||!this.transport)return;let o=performance.now()-r.startTime,a={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,...r.data,...n,status:t,duration:o,spans:r.spans,timestamp:new Date().toISOString(),error:r.error};this.transport.add(a)}captureError(t){t instanceof Error?l.setError(t):typeof t=="string"&&l.setError(new Error(t))}track(t){this.transport?.add({traceId:(0,C.randomUUID)(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=l.current();if(!r)return{end:()=>{}};let o=performance.now()-r.startTime,a=performance.now(),i=(0,C.randomUUID)();return{end:(u,s)=>{let d=performance.now()-a;l.addSpan({spanId:i,name:t,type:n,startTime:o,duration:d,status:s,meta:u})}}}async flush(){this.transport&&await this.transport.flush()}},c=new R;var K=()=>(e,t,n)=>{c.startTrace({method:e.method,path:e.originalUrl||e.url,ip:e.ip||e.socket?.remoteAddress,userAgent:e.headers["user-agent"],headers:e.headers},()=>{t.once("finish",()=>{try{let r="UNKNOWN";e.route&&e.route.path?r=(e.baseUrl||"")+e.route.path:t.statusCode===404?r="Not Found":r=e.path||"Wildcard",c.endTrace(t.statusCode,{route:r})}catch{}}),n()})},G=()=>(e,t,n,r)=>{c.captureError(e),r(e)};var b=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],k=(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:b(t);var L=e=>t=>{let n=t.node.req,r=n.originalUrl||n.url||"/";return c.startTrace({method:n.method||"GET",path:r,ip:n.headers["x-forwarded-for"]||n.socket?.remoteAddress,userAgent:n.headers["user-agent"],headers:n.headers},async()=>{try{let o=await e(t),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),o&&o.statusCode&&(a=o.statusCode),c.endTrace(a,{route:k(t,r)}),o}catch(o){c.captureError(o);let a=o.statusCode||o.status||500;throw c.endTrace(a,{route:k(t,r)}),o}})};var W=e=>async(t,n)=>{let r=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",a={},i,u;return typeof t.headers.get=="function"?(i=t.headers.get("user-agent"),u=t.headers.get("x-forwarded-for"),t.headers.forEach((s,d)=>{a[d]=s})):(a=t.headers,i=a["user-agent"],u=a["x-forwarded-for"]),c.startTrace({method:o,path:r.pathname,userAgent:i,ip:u,headers:a},async()=>{try{let s=await e(t,n),d=s?.status||200;return c.endTrace(d,{route:b(r.pathname)}),s}catch(s){throw c.captureError(s),c.endTrace(500,{route:b(r.pathname)}),s}})},j=e=>async(t,n)=>{let r=t.url?t.url.split("?")[0]:"/";return c.startTrace({method:t.method||"GET",path:r,userAgent:t.headers["user-agent"],ip:t.headers["x-forwarded-for"]||t.socket?.remoteAddress,headers:t.headers},async()=>{let o=()=>{c.endTrace(n.statusCode||200,{route:b(r)})};n.once("finish",o),n.once("close",o);try{return await e(t,n)}catch(a){throw c.captureError(a),a}})};var B=(e,t,n)=>{t&&t.apiKey&&c.init(t),e.addHook("onRequest",(r,o,a)=>{c.startTrace({method:r.method,path:r.raw.url||r.url,ip:r.ip,userAgent:r.headers["user-agent"],headers:r.headers},()=>a())}),e.addHook("onError",(r,o,a,i)=>{c.captureError(a),i()}),e.addHook("onResponse",(r,o,a)=>{let i=r.routeOptions?.url||r.routerPath||"UNKNOWN";c.endTrace(o.statusCode,{route:i}),a()}),n()};var _={init:e=>c.init(e),flush:()=>c.flush(),track:c.track.bind(c),startSpan:c.startSpan.bind(c),captureException:c.captureError.bind(c),requestHandler:K,errorHandler:G,wrapNextRoute:W,wrapNextPages:j,wrapH3:L,fastifyPlugin:B},vt=_;})();
2
2
  //# sourceMappingURL=index.global.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/transport.ts","../src/core/context.ts","../src/core/client.ts","../src/instrumentation/http.ts","../src/instrumentation/mongo.ts","../src/instrumentation/pg.ts","../src/middleware/express.ts","../src/core/normalizer.ts","../src/wrappers/h3.ts","../src/wrappers/next.ts","../src/wrappers/fastify.ts","../src/index.ts"],"sourcesContent":["import { SenzorOptions } from './types';\r\n\r\nexport class Transport {\r\n private queue: any[] = [];\r\n private timer: NodeJS.Timeout | null = null;\r\n\r\n constructor(private config: SenzorOptions) {\r\n if (typeof setInterval !== 'undefined') {\r\n this.timer = setInterval(() => this.flush(), config.flushInterval || 10000);\r\n if (this.timer && typeof this.timer.unref === 'function') {\r\n this.timer.unref(); // Don't block process exit\r\n }\r\n }\r\n }\r\n\r\n public add(trace: any) {\r\n this.queue.push(trace);\r\n if (this.queue.length >= (this.config.batchSize || 100)) {\r\n this.flush();\r\n }\r\n }\r\n\r\n public async flush() {\r\n if (this.queue.length === 0) return;\r\n\r\n const batch = [...this.queue];\r\n this.queue = [];\r\n\r\n try {\r\n // Use global fetch (Node 18+)\r\n await fetch(this.config.endpoint || 'https://api.senzor.dev/api/ingest/apm', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'x-service-api-key': this.config.apiKey,\r\n },\r\n body: JSON.stringify(batch),\r\n keepalive: true,\r\n });\r\n \r\n if (this.config.debug) console.log(`[Senzor] Flushed ${batch.length} traces`);\r\n } catch (err) {\r\n if (this.config.debug) console.error('[Senzor] Ingestion Error:', err);\r\n // Dropping data to prevent memory leaks is preferred in APM\r\n }\r\n }\r\n}","import { AsyncLocalStorage } from 'async_hooks';\r\nimport { ActiveTrace } from './types';\r\n\r\nexport const storage = new AsyncLocalStorage<ActiveTrace>();\r\n\r\nexport const Context = {\r\n run: <T>(trace: ActiveTrace, fn: () => T): T => {\r\n return storage.run(trace, fn);\r\n },\r\n\r\n current: (): ActiveTrace | undefined => {\r\n return storage.getStore();\r\n },\r\n\r\n addSpan: (span: any) => {\r\n const store = storage.getStore();\r\n if (store) {\r\n store.spans.push(span);\r\n } else {\r\n // If we are here, something tried to add a span but lost context\r\n // This is common if users await inside a callback that wasn't bound\r\n // However, usually silent failure is preferred in production APM\r\n console.warn('[Senzor] Lost context for span:', span.name);\r\n }\r\n }\r\n};","import { Transport } from './transport';\r\nimport { Context } from './context';\r\nimport { SenzorOptions, ActiveTrace } from './types';\r\nimport { randomUUID } from 'crypto';\r\nimport { instrumentHttp, instrumentFetch } from '../instrumentation/http'; // Import both\r\nimport { instrumentMongo } from '../instrumentation/mongo';\r\nimport { instrumentPg } from '../instrumentation/pg';\r\n\r\nexport class SenzorClient {\r\n private transport: Transport | null = null;\r\n private options: SenzorOptions | null = null;\r\n private isInstrumented = false;\r\n\r\n public init(options: SenzorOptions) {\r\n if (!options.apiKey) {\r\n console.warn('[Senzor] API Key missing. SDK disabled.');\r\n return;\r\n }\r\n this.options = options;\r\n const endpoint = options.endpoint || 'https://api.senzor.dev/api/ingest/apm';\r\n const debug = options.debug || false;\r\n\r\n this.transport = new Transport({\r\n ...options,\r\n endpoint\r\n });\r\n\r\n // --- ENABLE AUTO INSTRUMENTATION ---\r\n if (!this.isInstrumented) {\r\n try { instrumentHttp(endpoint, debug); } catch (e) { }\r\n try { instrumentFetch(endpoint, debug); } catch (e) { } // NEW: Fetch Support\r\n try { instrumentMongo(debug); } catch (e) { }\r\n try { instrumentPg(); } catch (e) { }\r\n\r\n this.isInstrumented = true;\r\n if (debug) console.log('[Senzor] Auto-instrumentation enabled (HTTP, Fetch, Mongo)');\r\n }\r\n }\r\n\r\n // ... (Rest of file same as before: startTrace, endTrace, track, etc.) ...\r\n public startTrace<T>(data: Partial<ActiveTrace['data']>, next: () => T): T {\r\n if (!this.transport) return next();\r\n const trace: ActiveTrace = { id: randomUUID(), startTime: performance.now(), data: data, spans: [] };\r\n return Context.run(trace, next);\r\n }\r\n\r\n public endTrace(status: number, extraData: any = {}) {\r\n const trace = Context.current();\r\n if (!trace || !this.transport) return;\r\n const duration = performance.now() - trace.startTime;\r\n const payload = { traceId: trace.id, ...trace.data, ...extraData, status, duration, spans: trace.spans, timestamp: new Date().toISOString() };\r\n this.transport.add(payload);\r\n }\r\n\r\n public track(data: any) { this.transport?.add({ traceId: randomUUID(), ...data, spans: [], timestamp: new Date().toISOString() }); }\r\n\r\n public startSpan(name: string, type: 'db' | 'http' | 'function' | 'custom' = 'custom') {\r\n const trace = Context.current();\r\n if (!trace) return { end: () => { } };\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n return { end: (meta?: any, status?: number) => { Context.addSpan({ name, type, startTime, duration: performance.now() - spanStartAbs, status, meta }); } };\r\n }\r\n\r\n public async flush() { if (this.transport) await this.transport.flush(); }\r\n}\r\n\r\nexport const client = new SenzorClient();","import http from 'http';\r\nimport https from 'https';\r\nimport { URL } from 'url';\r\nimport { Context } from '../core/context';\r\n\r\nconst shimmer = (module: any, methodName: string, wrapper: (original: Function) => Function) => {\r\n if (!module[methodName]) return;\r\n const original = module[methodName];\r\n module[methodName] = wrapper(original);\r\n};\r\n\r\n// --- Native Fetch Instrumentation (Node 18+) ---\r\nexport const instrumentFetch = (ingestUrl: string, debug = false) => {\r\n if (!globalThis.fetch) return;\r\n\r\n let ingestHost = '';\r\n try { ingestHost = new URL(ingestUrl).hostname; } catch (e) { }\r\n\r\n const originalFetch = globalThis.fetch;\r\n\r\n // @ts-ignore\r\n globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {\r\n // 1. Extract URL\r\n let urlStr = '';\r\n if (typeof input === 'string') urlStr = input;\r\n else if (input instanceof URL) urlStr = input.toString();\r\n else if (input && input.url) urlStr = input.url; // Request object\r\n\r\n // 2. Infinite Loop Guard\r\n if (ingestHost && urlStr.includes(ingestHost)) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n // 3. Context Check\r\n const trace = Context.current();\r\n if (!trace) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n // 4. Start Span\r\n const method = (init?.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { }\r\n\r\n if (debug) console.log(`[Senzor] Tracking Fetch: ${method} ${hostname}`);\r\n\r\n try {\r\n const response = await originalFetch(input, init);\r\n\r\n // 5. End Span\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: response.status,\r\n meta: { url: urlStr, method, library: 'fetch' }\r\n });\r\n\r\n return response;\r\n } catch (err: any) {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: 500,\r\n meta: { error: err.message, url: urlStr, library: 'fetch' }\r\n });\r\n throw err;\r\n }\r\n };\r\n};\r\n\r\n// --- Standard HTTP/HTTPS Instrumentation ---\r\nexport const instrumentHttp = (ingestUrl: string, debug = false) => {\r\n let ingestHost = '';\r\n try {\r\n ingestHost = new URL(ingestUrl).hostname;\r\n } catch (e) { }\r\n\r\n const requestWrapper = (original: Function) => {\r\n return function (this: any, ...args: any[]) {\r\n let options: any = {};\r\n let urlStr = '';\r\n\r\n if (typeof args[0] === 'string' || args[0] instanceof URL) {\r\n urlStr = args[0].toString();\r\n if (typeof args[1] === 'object' && args[1] !== null) options = args[1];\r\n } else {\r\n options = args[0] || {};\r\n const protocol = options.protocol || (options.port === 443 ? 'https:' : 'http:');\r\n const host = options.hostname || options.host || 'localhost';\r\n const path = options.path || '/';\r\n urlStr = `${protocol}//${host}${path}`;\r\n }\r\n\r\n if (ingestHost && (urlStr.includes(ingestHost) || (options.hostname && options.hostname.includes(ingestHost)))) {\r\n return original.apply(this, args);\r\n }\r\n\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const method = (options.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { hostname = options.hostname || 'unknown'; }\r\n\r\n const req = original.apply(this, args);\r\n\r\n const captureSpan = (res: any, error?: Error) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: error ? 500 : res?.statusCode || 0,\r\n meta: { url: urlStr, method, library: 'http' }\r\n });\r\n };\r\n\r\n req.on('response', (res: any) => {\r\n res.once('end', () => captureSpan(res));\r\n res.once('error', (err: Error) => captureSpan(res, err));\r\n });\r\n\r\n req.on('error', (err: Error) => captureSpan(null, err));\r\n\r\n return req;\r\n };\r\n };\r\n\r\n shimmer(http, 'request', requestWrapper);\r\n shimmer(http, 'get', requestWrapper);\r\n shimmer(https, 'request', requestWrapper);\r\n shimmer(https, 'get', requestWrapper);\r\n};","import { Context } from '../core/context';\r\n\r\nexport const instrumentMongo = (debug = false) => {\r\n try {\r\n const mongodb = require('mongodb');\r\n const Collection = mongodb.Collection;\r\n\r\n // Attempt to get Cursor classes\r\n // Note: The location of these classes varies by driver version, \r\n // checking common locations\r\n const FindCursor = mongodb.FindCursor || require('mongodb/lib/cursor/find_cursor').FindCursor;\r\n const AggregationCursor = mongodb.AggregationCursor || require('mongodb/lib/cursor/aggregation_cursor').AggregationCursor;\r\n\r\n if (debug) console.log('[Senzor] Instrumenting MongoDB (Collection + Cursors)...');\r\n\r\n // --- Helper to Record Span ---\r\n const recordSpan = (name: string, operation: string, collection: string, startAbs: number, traceStart: number, err?: Error) => {\r\n const duration = performance.now() - startAbs;\r\n Context.addSpan({\r\n name: `MongoDB ${name}`,\r\n type: 'db',\r\n startTime: performance.now() - traceStart - duration, // Adjust start time to when op actually started\r\n duration,\r\n status: err ? 500 : 0,\r\n meta: { collection, operation, error: err ? err.message : undefined }\r\n });\r\n if (debug) console.log(`[Senzor] Captured Mongo: ${name} (${duration.toFixed(2)}ms)`);\r\n };\r\n\r\n // --- 1. Instrument Immediate Operations (Insert/Update/Delete) ---\r\n const immediateMethods = ['insertOne', 'insertMany', 'updateOne', 'updateMany', 'deleteOne', 'deleteMany', 'countDocuments'];\r\n\r\n immediateMethods.forEach((method) => {\r\n if (!Collection.prototype[method]) return;\r\n const original = Collection.prototype[method];\r\n\r\n Collection.prototype[method] = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n const collName = this.collectionName;\r\n\r\n try {\r\n const result = original.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(\r\n (res: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart); return res; },\r\n (err: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart, err); throw err; }\r\n );\r\n }\r\n return result;\r\n } catch (err: any) {\r\n recordSpan(method, method, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n }\r\n };\r\n });\r\n\r\n // --- 2. Instrument Cursor Execution (find -> toArray) ---\r\n const patchCursor = (CursorClass: any, label: string) => {\r\n if (!CursorClass || !CursorClass.prototype.toArray) return;\r\n\r\n const originalToArray = CursorClass.prototype.toArray;\r\n\r\n CursorClass.prototype.toArray = function (...args: any[]) {\r\n const trace = Context.current();\r\n // Cursors are often created in context but executed later. \r\n // We check context at execution time.\r\n if (!trace) return originalToArray.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n // Attempt to get collection name from cursor internal state\r\n const collName = this.namespace?.collection || 'unknown';\r\n\r\n const onSuccess = (res: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart);\r\n return res;\r\n };\r\n const onError = (err: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n };\r\n\r\n try {\r\n const result = originalToArray.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(onSuccess, onError);\r\n }\r\n return onSuccess(result);\r\n } catch (e) {\r\n onError(e);\r\n }\r\n };\r\n };\r\n\r\n patchCursor(FindCursor, 'find');\r\n patchCursor(AggregationCursor, 'aggregate');\r\n\r\n } catch (e: any) {\r\n if (debug) console.warn('[Senzor] MongoDB instrumentation warning:', e.message);\r\n }\r\n};","import { Context } from '../core/context';\r\n\r\n// Simple shim for 'pg' library\r\nexport const instrumentPg = () => {\r\n try {\r\n // Try to require pg (it might not be installed by user)\r\n const pg = require('pg');\r\n const originalQuery = pg.Client.prototype.query;\r\n\r\n pg.Client.prototype.query = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return originalQuery.apply(this, args);\r\n\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n\r\n // Extract SQL (first arg usually string or config object)\r\n const sql = typeof args[0] === 'string' ? args[0] : args[0].text;\r\n\r\n // Wrap callback if present, or handle Promise\r\n const result = originalQuery.apply(this, args);\r\n\r\n if (result && typeof result.then === 'function') {\r\n return result.then((res: any) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: 'Postgres Query',\r\n type: 'db',\r\n startTime,\r\n duration,\r\n meta: { query: sql }\r\n });\r\n return res;\r\n });\r\n }\r\n return result;\r\n };\r\n } catch (e) {\r\n // User doesn't use pg, ignore\r\n }\r\n};","import { client } from '../core/client';\r\n\r\nexport const expressMiddleware = () => {\r\n return (req: any, res: any, next: () => void) => {\r\n // We MUST use startTrace to enable Auto-Instrumentation for this request\r\n client.startTrace({\r\n method: req.method,\r\n path: req.originalUrl || req.url,\r\n ip: req.ip || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n }, () => {\r\n\r\n res.once('finish', () => {\r\n try {\r\n let route = 'UNKNOWN';\r\n if (req.route && req.route.path) {\r\n route = (req.baseUrl || '') + req.route.path;\r\n } else if (res.statusCode === 404) {\r\n route = 'Not Found';\r\n } else {\r\n route = req.path || 'Wildcard';\r\n }\r\n\r\n client.endTrace(res.statusCode, { route });\r\n } catch (e) {\r\n // Fail open\r\n }\r\n });\r\n\r\n next();\r\n });\r\n };\r\n};","/**\r\n * Heuristic URL Normalizer\r\n * Converts raw paths with IDs into generic patterns to prevent high cardinality.\r\n * Example: /users/123/orders/abc-def -> /users/:id/orders/:uuid\r\n */\r\nexport const normalizePath = (path: string): string => {\r\n if (!path || path === '/') return '/';\r\n\r\n return path\r\n // Replace UUIDs (long alphanumeric strings)\r\n .replace(\r\n /[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,\r\n ':uuid'\r\n )\r\n // Replace MongoDB ObjectIds (24 hex chars)\r\n .replace(/[0-9a-fA-F]{24}/g, ':objectId')\r\n // Replace pure numeric IDs (e.g., /123)\r\n .replace(/\\/(\\d+)(?=\\/|$)/g, '/:id')\r\n // Remove query strings\r\n .split('?')[0];\r\n};\r\n\r\n/**\r\n * Tries to extract route from Framework internals, falls back to heuristic\r\n */\r\nexport const getRoute = (req: any, fallbackPath: string): string => {\r\n // Express / Connect\r\n if (req.route && req.route.path) {\r\n return (req.baseUrl || '') + req.route.path;\r\n }\r\n\r\n // H3 / Nitro (Nuxt)\r\n if (req.context && req.context.matchedRoute) {\r\n return req.context.matchedRoute.path;\r\n }\r\n\r\n // Fastify\r\n if (req.routerPath) {\r\n return req.routerPath;\r\n }\r\n\r\n // Fallback: Heuristic Normalization\r\n return normalizePath(fallbackPath);\r\n};","import { client } from '../core/client';\r\nimport { getRoute } from '../core/normalizer';\r\n\r\n// Minimal types for H3 to avoid peer-deps\r\ntype EventHandler = (event: any) => any;\r\n\r\nexport const wrapH3 = (handler: EventHandler) => {\r\n return (event: any) => {\r\n const req = event.node.req;\r\n const path = req.originalUrl || req.url || '/';\r\n\r\n // Start Trace Context\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n }, async () => {\r\n try {\r\n const response = await handler(event);\r\n\r\n // H3/Nitro response status\r\n let status = 200;\r\n if (event.node.res.statusCode) status = event.node.res.statusCode;\r\n // Check if response is an error object\r\n if (response && response.statusCode) status = response.statusCode;\r\n\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n return response;\r\n } catch (err: any) {\r\n const status = err.statusCode || err.status || 500;\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n throw err;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { normalizePath } from '../core/normalizer';\r\n\r\n// --- App Router Wrapper (Route Handlers) ---\r\nexport const wrapNextRoute = (handler: Function) => {\r\n return async (req: Request | any, context?: any) => {\r\n // 1. Extract Info\r\n const url = req.url ? new URL(req.url) : { pathname: '/' };\r\n const method = req.method || 'GET';\r\n const ua = req.headers.get ? req.headers.get('user-agent') : undefined;\r\n const ip = req.headers.get ? req.headers.get('x-forwarded-for') : undefined;\r\n\r\n // 2. Run in Context\r\n return client.startTrace({\r\n method,\r\n path: url.pathname,\r\n userAgent: ua,\r\n ip: ip\r\n }, async () => {\r\n try {\r\n const response = await handler(req, context);\r\n const status = response?.status || 200;\r\n \r\n client.endTrace(status, { route: normalizePath(url.pathname) });\r\n return response;\r\n } catch (err: any) {\r\n client.endTrace(500, { route: normalizePath(url.pathname) });\r\n throw err;\r\n }\r\n });\r\n };\r\n};\r\n\r\n// --- Pages Router Wrapper (API Routes) ---\r\nexport const wrapNextPages = (handler: Function) => {\r\n return async (req: any, res: any) => {\r\n const path = req.url ? req.url.split('?')[0] : '/';\r\n \r\n // 1. Run in Context\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n userAgent: req.headers['user-agent'],\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n }, async () => {\r\n \r\n // 2. Hook Response\r\n const done = () => {\r\n client.endTrace(res.statusCode || 200, { route: normalizePath(path) });\r\n };\r\n \r\n res.once('finish', done);\r\n res.once('close', done); // Fallback if finish doesn't fire\r\n\r\n // 3. Execute\r\n try {\r\n return await handler(req, res);\r\n } catch (e) {\r\n // Next.js Pages router usually handles errors internally, \r\n // but we ensure we catch sync errors here\r\n throw e;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { SenzorOptions } from '../core/types';\r\n\r\n// We don't import Fastify types to keep zero-deps, but structure matches\r\nexport const senzorPlugin = (fastify: any, options: SenzorOptions, done: Function) => {\r\n\r\n // Init if options provided inline, otherwise assume global init\r\n if (options && options.apiKey) {\r\n client.init(options);\r\n }\r\n\r\n // Hook: On Request (Start Timer)\r\n fastify.addHook('onRequest', (request: any, reply: any, next: Function) => {\r\n request.senzorStart = performance.now();\r\n next();\r\n });\r\n\r\n // Hook: On Response (End Timer & Track)\r\n fastify.addHook('onResponse', (request: any, reply: any, next: Function) => {\r\n const duration = performance.now() - (request.senzorStart || performance.now());\r\n\r\n // Fastify provides 'routerPath' (e.g. /user/:id)\r\n const route = request.routeOptions?.url || request.routerPath;\r\n\r\n client.track({\r\n method: request.method,\r\n route: route || 'UNKNOWN',\r\n path: request.raw.url || request.url,\r\n status: reply.statusCode,\r\n duration: duration,\r\n ip: request.ip,\r\n userAgent: request.headers['user-agent']\r\n });\r\n\r\n next();\r\n });\r\n\r\n done();\r\n};","import { client } from './core/client';\r\nimport { expressMiddleware } from './middleware/express';\r\nimport { wrapH3 } from './wrappers/h3';\r\nimport { wrapNextRoute, wrapNextPages } from './wrappers/next';\r\nimport { senzorPlugin } from './wrappers/fastify';\r\nimport { SenzorOptions } from './core/types';\r\n\r\nconst Senzor = {\r\n // Core\r\n init: (options: SenzorOptions) => client.init(options),\r\n flush: () => client.flush(),\r\n\r\n // Express / Connect\r\n requestHandler: expressMiddleware,\r\n\r\n // Next.js\r\n wrapNextRoute, // For App Router (Route Handlers)\r\n wrapNextPages, // For Pages Router (API Routes)\r\n\r\n // H3 / Nuxt / Nitro\r\n wrapH3,\r\n\r\n // Fastify\r\n fastifyPlugin: senzorPlugin\r\n};\r\n\r\nexport default Senzor;\r\nexport { Senzor };"],"mappings":"utBAEO,IAAMA,EAAN,KAAgB,CAIrB,YAAoBC,EAAuB,CAAvB,YAAAA,EAHpB,KAAQ,MAAe,CAAC,EACxB,KAA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Q,QAAQ,YAAa,CAACI,EAAcC,EAAYC,IAAmB,CACzEF,EAAQ,YAAc,YAAY,IAAI,EACtCE,EAAK,CACP,CAAC,EAGDN,EAAQ,QAAQ,aAAc,CAACI,EAAcC,EAAYC,IAAmB,CAC1E,IAAMC,EAAW,YAAY,IAAI,GAAKH,EAAQ,aAAe,YAAY,IAAI,GAGvEI,EAAQJ,EAAQ,cAAc,KAAOA,EAAQ,WAEnDD,EAAO,MAAM,CACX,OAAQC,EAAQ,OAChB,MAAOI,GAAS,UAChB,KAAMJ,EAAQ,IAAI,KAAOA,EAAQ,IACjC,OAAQC,EAAM,WACd,SAAUE,EACV,GAAIH,EAAQ,GACZ,UAAWA,EAAQ,QAAQ,YAAY,CACzC,CAAC,EAEDE,EAAK,CACP,CAAC,EAEDJ,EAAK,CACP,EC/BA,IAAMO,EAAS,CAEb,KAAOC,GAA2BC,EAAO,KAAKD,CAAO,EACrD,MAAO,IAAMC,EAAO,MAAM,EAG1B,eAAgBC,EAGhB,cAAAC,EACA,cAAAC,EAGA,OAAAC,EAGA,cAAeC,CACjB,EAEOC,GAAQR","names":["Transport","config","trace","batch","err","import_async_hooks","storage","Context","trace","fn","span","store","import_crypto","import_http","import_https","import_url","shimmer","module","methodName","wrapper","original","instrumentFetch","ingestUrl","debug","ingestHost","originalFetch","input","init","urlStr","trace","Context","method","startTime","spanStartAbs","hostname","response","duration","err","instrumentHttp","requestWrapper","args","options","protocol","host","path","req","captureSpan","res","error","http","https","instrumentMongo","debug","mongodb","Collection","FindCursor","AggregationCursor","recordSpan","name","operation","collection","startAbs","traceStart","err","duration","Context","method","original","args","trace","spanStartAbs","collName","result","res","patchCursor","CursorClass","label","originalToArray","onSuccess","onError","e","instrumentPg","pg","originalQuery","args","trace","Context","startTime","spanStartAbs","sql","result","res","duration","SenzorClient","options","endpoint","debug","Transport","instrumentHttp","instrumentFetch","instrumentMongo","instrumentPg","data","next","trace","Context","status","extraData","duration","payload","name","type","startTime","spanStartAbs","meta","client","expressMiddleware","req","res","next","client","route","normalizePath","path","getRoute","req","fallbackPath","wrapH3","handler","event","req","path","client","response","status","getRoute","err","wrapNextRoute","handler","req","context","url","method","ua","ip","client","response","status","normalizePath","err","wrapNextPages","res","path","done","e","senzorPlugin","fastify","options","done","client","request","reply","next","duration","route","Senzor","options","client","expressMiddleware","wrapNextRoute","wrapNextPages","wrapH3","senzorPlugin","index_default"]}
1
+ {"version":3,"sources":["../src/core/transport.ts","../src/core/context.ts","../src/core/client.ts","../src/instrumentation/http.ts","../src/instrumentation/mongo.ts","../src/instrumentation/pg.ts","../src/middleware/express.ts","../src/core/normalizer.ts","../src/wrappers/h3.ts","../src/wrappers/next.ts","../src/wrappers/fastify.ts","../src/index.ts"],"sourcesContent":["import { SenzorOptions } from './types';\r\n\r\nexport class Transport {\r\n private queue: any[] = [];\r\n private timer: NodeJS.Timeout | null = null;\r\n\r\n constructor(private config: SenzorOptions) {\r\n if (typeof setInterval !== 'undefined') {\r\n this.timer = setInterval(() => this.flush(), config.flushInterval || 10000);\r\n if (this.timer && typeof this.timer.unref === 'function') {\r\n this.timer.unref(); // Don't block process exit\r\n }\r\n }\r\n }\r\n\r\n public add(trace: any) {\r\n this.queue.push(trace);\r\n if (this.queue.length >= (this.config.batchSize || 100)) {\r\n this.flush();\r\n }\r\n }\r\n\r\n public async flush() {\r\n if (this.queue.length === 0) return;\r\n\r\n const batch = [...this.queue];\r\n this.queue = [];\r\n\r\n try {\r\n // Use global fetch (Node 18+)\r\n await fetch(this.config.endpoint || 'https://api.senzor.dev/api/ingest/apm', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'x-service-api-key': this.config.apiKey,\r\n },\r\n body: JSON.stringify(batch),\r\n keepalive: true,\r\n });\r\n \r\n if (this.config.debug) console.log(`[Senzor] Flushed ${batch.length} traces`);\r\n } catch (err) {\r\n if (this.config.debug) console.error('[Senzor] Ingestion Error:', err);\r\n // Dropping data to prevent memory leaks is preferred in APM\r\n }\r\n }\r\n}","import { AsyncLocalStorage } from 'async_hooks';\r\nimport { ActiveTrace, TraceError } from './types';\r\n\r\nexport const storage = new AsyncLocalStorage<ActiveTrace>();\r\n\r\nexport const Context = {\r\n run: <T>(trace: ActiveTrace, fn: () => T): T => {\r\n return storage.run(trace, fn);\r\n },\r\n\r\n current: (): ActiveTrace | undefined => {\r\n return storage.getStore();\r\n },\r\n\r\n addSpan: (span: any) => {\r\n const store = storage.getStore();\r\n if (store) {\r\n store.spans.push(span);\r\n }\r\n },\r\n\r\n // Attach error to current trace\r\n setError: (error: Error) => {\r\n const store = storage.getStore();\r\n if (store) {\r\n store.error = {\r\n name: error.name,\r\n message: error.message,\r\n stack: error.stack\r\n };\r\n }\r\n }\r\n};","import { Transport } from './transport';\r\nimport { Context } from './context';\r\nimport { SenzorOptions, ActiveTrace } from './types';\r\nimport { randomUUID } from 'crypto';\r\nimport { instrumentHttp, instrumentFetch } from '../instrumentation/http';\r\nimport { instrumentMongo } from '../instrumentation/mongo';\r\nimport { instrumentPg } from '../instrumentation/pg';\r\n\r\nexport class SenzorClient {\r\n private transport: Transport | null = null;\r\n private options: SenzorOptions | null = null;\r\n private isInstrumented = false;\r\n\r\n public init(options: SenzorOptions) {\r\n if (!options.apiKey) {\r\n console.warn('[Senzor] API Key missing. SDK disabled.');\r\n return;\r\n }\r\n this.options = options;\r\n const endpoint = options.endpoint || 'https://api.senzor.dev/api/ingest/apm';\r\n const debug = options.debug || false;\r\n\r\n this.transport = new Transport({ ...options, endpoint });\r\n\r\n if (!this.isInstrumented) {\r\n try { instrumentHttp(endpoint, debug); } catch (e) { }\r\n try { instrumentFetch(endpoint, debug); } catch (e) { }\r\n try { instrumentMongo(debug); } catch (e) { }\r\n try { instrumentPg(); } catch (e) { }\r\n\r\n this.isInstrumented = true;\r\n if (debug) console.log('[Senzor] Auto-instrumentation enabled');\r\n }\r\n }\r\n\r\n public startTrace<T>(data: Partial<ActiveTrace['data']> & { headers?: any }, next: () => T): T {\r\n if (!this.transport) return next();\r\n\r\n // Check for Distributed Tracing Headers\r\n let parentTraceId = undefined;\r\n let parentSpanId = undefined;\r\n\r\n if (data.headers) {\r\n // Handle various casing\r\n parentTraceId = data.headers['x-senzor-trace-id'] || data.headers['X-SENZOR-TRACE-ID'];\r\n parentSpanId = data.headers['x-senzor-parent-span-id'] || data.headers['X-SENZOR-PARENT-SPAN-ID'];\r\n }\r\n\r\n const trace: ActiveTrace = {\r\n id: randomUUID(),\r\n startTime: performance.now(),\r\n data: {\r\n ...data,\r\n parentTraceId, // Link to parent\r\n parentSpanId // Link to specific call\r\n },\r\n spans: []\r\n };\r\n\r\n return Context.run(trace, next);\r\n }\r\n\r\n public endTrace(status: number, extraData: any = {}) {\r\n const trace = Context.current();\r\n if (!trace || !this.transport) return;\r\n const duration = performance.now() - trace.startTime;\r\n\r\n // Explicitly destructure to ensure parent IDs are included\r\n const payload = {\r\n traceId: trace.id,\r\n parentTraceId: trace.data.parentTraceId,\r\n parentSpanId: trace.data.parentSpanId,\r\n ...trace.data,\r\n ...extraData,\r\n status, duration, spans: trace.spans, timestamp: new Date().toISOString(),\r\n error: trace.error,\r\n\r\n };\r\n this.transport.add(payload);\r\n }\r\n\r\n // --- NEW: Capture Exception ---\r\n public captureError(error: unknown) {\r\n if (error instanceof Error) {\r\n Context.setError(error);\r\n } else if (typeof error === 'string') {\r\n Context.setError(new Error(error));\r\n }\r\n }\r\n\r\n // ... (manual track, startSpan, flush remain same) ...\r\n public track(data: any) { this.transport?.add({ traceId: randomUUID(), ...data, spans: [], timestamp: new Date().toISOString() }); }\r\n\r\n public startSpan(name: string, type: 'db' | 'http' | 'function' | 'custom' = 'custom') {\r\n const trace = Context.current();\r\n if (!trace) return { end: () => { } };\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n const spanId = randomUUID(); // Manual spans also need IDs\r\n\r\n return {\r\n end: (meta?: any, status?: number) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({ spanId, name, type, startTime, duration, status, meta });\r\n }\r\n };\r\n }\r\n\r\n public async flush() { if (this.transport) await this.transport.flush(); }\r\n}\r\n\r\nexport const client = new SenzorClient();","import http from 'http';\r\nimport https from 'https';\r\nimport { URL } from 'url';\r\nimport { Context } from '../core/context';\r\nimport { randomUUID } from 'crypto';\r\n\r\nconst shimmer = (module: any, methodName: string, wrapper: (original: Function) => Function) => {\r\n if (!module[methodName]) return;\r\n const original = module[methodName];\r\n module[methodName] = wrapper(original);\r\n};\r\n\r\n// --- FETCH INSTRUMENTATION (Node 18+ / Edge) ---\r\nexport const instrumentFetch = (ingestUrl: string, debug = false) => {\r\n if (!globalThis.fetch) return;\r\n\r\n let ingestHost = '';\r\n try { ingestHost = new URL(ingestUrl).hostname; } catch (e) { }\r\n\r\n const originalFetch = globalThis.fetch;\r\n\r\n // @ts-ignore\r\n globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {\r\n // 1. Extract URL\r\n let urlStr = '';\r\n if (typeof input === 'string') urlStr = input;\r\n else if (input instanceof URL) urlStr = input.toString();\r\n else if (input && (input as any).url) urlStr = (input as any).url;\r\n\r\n // 2. Infinite Loop Guard\r\n if (ingestHost && urlStr.includes(ingestHost)) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n // 3. Context Check\r\n const trace = Context.current();\r\n if (!trace) {\r\n return originalFetch(input, init);\r\n }\r\n\r\n // 4. Prepare Metadata & ID\r\n const method = (init?.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n const spanId = randomUUID(); // New ID for this specific outbound call\r\n\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { }\r\n\r\n if (debug) console.log(`[Senzor] Fetch: ${method} ${hostname}`);\r\n\r\n // 5. Inject Distributed Tracing Headers\r\n // We need to clone init or create it to avoid mutating original ref unexpectedly\r\n const newInit = { ...init };\r\n if (!newInit.headers) {\r\n newInit.headers = {};\r\n }\r\n\r\n // Handle different Header formats (Headers object vs plain object)\r\n if (newInit.headers instanceof Headers) {\r\n newInit.headers.set('x-senzor-trace-id', trace.id);\r\n newInit.headers.set('x-senzor-parent-span-id', spanId);\r\n } else if (Array.isArray(newInit.headers)) {\r\n newInit.headers.push(['x-senzor-trace-id', trace.id]);\r\n newInit.headers.push(['x-senzor-parent-span-id', spanId]);\r\n } else {\r\n // Plain object\r\n (newInit.headers as any)['x-senzor-trace-id'] = trace.id;\r\n (newInit.headers as any)['x-senzor-parent-span-id'] = spanId;\r\n }\r\n\r\n try {\r\n // 6. Execute Fetch\r\n const response = await originalFetch(input, newInit);\r\n\r\n // 7. Record Span\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n spanId,\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: response.status,\r\n meta: { url: urlStr, method, library: 'fetch' }\r\n });\r\n\r\n return response;\r\n } catch (err: any) {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n spanId,\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: 500,\r\n meta: { error: err.message, url: urlStr, library: 'fetch' }\r\n });\r\n throw err;\r\n }\r\n };\r\n};\r\n\r\n// --- HTTP/HTTPS INSTRUMENTATION ---\r\nexport const instrumentHttp = (ingestUrl: string, debug = false) => {\r\n let ingestHost = '';\r\n try { ingestHost = new URL(ingestUrl).hostname; } catch (e) { }\r\n\r\n const requestWrapper = (original: Function) => {\r\n return function (this: any, ...args: any[]) {\r\n let options: any = {};\r\n let urlStr = '';\r\n\r\n if (typeof args[0] === 'string' || args[0] instanceof URL) {\r\n urlStr = args[0].toString();\r\n if (typeof args[1] === 'object' && args[1] !== null) options = args[1];\r\n } else {\r\n options = args[0] || {};\r\n const protocol = options.protocol || (options.port === 443 ? 'https:' : 'http:');\r\n const host = options.hostname || options.host || 'localhost';\r\n const path = options.path || '/';\r\n urlStr = `${protocol}//${host}${path}`;\r\n }\r\n\r\n if (ingestHost && (urlStr.includes(ingestHost) || (options.hostname && options.hostname.includes(ingestHost)))) {\r\n return original.apply(this, args);\r\n }\r\n\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const method = (options.method || 'GET').toUpperCase();\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n const spanId = randomUUID(); // Generate ID\r\n\r\n let hostname = 'unknown';\r\n try { hostname = new URL(urlStr).hostname; } catch (e) { hostname = options.hostname || 'unknown'; }\r\n\r\n // Inject Headers\r\n if (!options.headers) options.headers = {};\r\n options.headers['x-senzor-trace-id'] = trace.id;\r\n options.headers['x-senzor-parent-span-id'] = spanId;\r\n\r\n const req = original.apply(this, args);\r\n\r\n const captureSpan = (res: any, error?: Error) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n spanId,\r\n name: `${method} ${hostname}`,\r\n type: 'http',\r\n startTime,\r\n duration,\r\n status: error ? 500 : res?.statusCode || 0,\r\n meta: { url: urlStr, method, library: 'http' }\r\n });\r\n };\r\n\r\n req.on('response', (res: any) => {\r\n res.once('end', () => captureSpan(res));\r\n res.once('close', () => captureSpan(res)); // Safety if stream not consumed\r\n res.once('error', (err: Error) => captureSpan(res, err));\r\n });\r\n\r\n req.on('error', (err: Error) => captureSpan(null, err));\r\n\r\n return req;\r\n };\r\n };\r\n\r\n shimmer(http, 'request', requestWrapper);\r\n shimmer(http, 'get', requestWrapper);\r\n shimmer(https, 'request', requestWrapper);\r\n shimmer(https, 'get', requestWrapper);\r\n};","import { Context } from '../core/context';\r\n\r\nexport const instrumentMongo = (debug = false) => {\r\n try {\r\n const mongodb = require('mongodb');\r\n const Collection = mongodb.Collection;\r\n\r\n // Attempt to get Cursor classes\r\n // Note: The location of these classes varies by driver version, \r\n // checking common locations\r\n const FindCursor = mongodb.FindCursor || require('mongodb/lib/cursor/find_cursor').FindCursor;\r\n const AggregationCursor = mongodb.AggregationCursor || require('mongodb/lib/cursor/aggregation_cursor').AggregationCursor;\r\n\r\n if (debug) console.log('[Senzor] Instrumenting MongoDB (Collection + Cursors)...');\r\n\r\n // --- Helper to Record Span ---\r\n const recordSpan = (name: string, operation: string, collection: string, startAbs: number, traceStart: number, err?: Error) => {\r\n const duration = performance.now() - startAbs;\r\n Context.addSpan({\r\n name: `MongoDB ${name}`,\r\n type: 'db',\r\n startTime: performance.now() - traceStart - duration, // Adjust start time to when op actually started\r\n duration,\r\n status: err ? 500 : 0,\r\n meta: { collection, operation, error: err ? err.message : undefined }\r\n });\r\n if (debug) console.log(`[Senzor] Captured Mongo: ${name} (${duration.toFixed(2)}ms)`);\r\n };\r\n\r\n // --- 1. Instrument Immediate Operations (Insert/Update/Delete) ---\r\n const immediateMethods = ['insertOne', 'insertMany', 'updateOne', 'updateMany', 'deleteOne', 'deleteMany', 'countDocuments'];\r\n\r\n immediateMethods.forEach((method) => {\r\n if (!Collection.prototype[method]) return;\r\n const original = Collection.prototype[method];\r\n\r\n Collection.prototype[method] = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return original.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n const collName = this.collectionName;\r\n\r\n try {\r\n const result = original.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(\r\n (res: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart); return res; },\r\n (err: any) => { recordSpan(method, method, collName, spanStartAbs, traceStart, err); throw err; }\r\n );\r\n }\r\n return result;\r\n } catch (err: any) {\r\n recordSpan(method, method, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n }\r\n };\r\n });\r\n\r\n // --- 2. Instrument Cursor Execution (find -> toArray) ---\r\n const patchCursor = (CursorClass: any, label: string) => {\r\n if (!CursorClass || !CursorClass.prototype.toArray) return;\r\n\r\n const originalToArray = CursorClass.prototype.toArray;\r\n\r\n CursorClass.prototype.toArray = function (...args: any[]) {\r\n const trace = Context.current();\r\n // Cursors are often created in context but executed later. \r\n // We check context at execution time.\r\n if (!trace) return originalToArray.apply(this, args);\r\n\r\n const spanStartAbs = performance.now();\r\n const traceStart = trace.startTime;\r\n // Attempt to get collection name from cursor internal state\r\n const collName = this.namespace?.collection || 'unknown';\r\n\r\n const onSuccess = (res: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart);\r\n return res;\r\n };\r\n const onError = (err: any) => {\r\n recordSpan(label, label, collName, spanStartAbs, traceStart, err);\r\n throw err;\r\n };\r\n\r\n try {\r\n const result = originalToArray.apply(this, args);\r\n if (result && typeof result.then === 'function') {\r\n return result.then(onSuccess, onError);\r\n }\r\n return onSuccess(result);\r\n } catch (e) {\r\n onError(e);\r\n }\r\n };\r\n };\r\n\r\n patchCursor(FindCursor, 'find');\r\n patchCursor(AggregationCursor, 'aggregate');\r\n\r\n } catch (e: any) {\r\n if (debug) console.warn('[Senzor] MongoDB instrumentation warning:', e.message);\r\n }\r\n};","import { Context } from '../core/context';\r\n\r\n// Simple shim for 'pg' library\r\nexport const instrumentPg = () => {\r\n try {\r\n // Try to require pg (it might not be installed by user)\r\n const pg = require('pg');\r\n const originalQuery = pg.Client.prototype.query;\r\n\r\n pg.Client.prototype.query = function (...args: any[]) {\r\n const trace = Context.current();\r\n if (!trace) return originalQuery.apply(this, args);\r\n\r\n const startTime = performance.now() - trace.startTime;\r\n const spanStartAbs = performance.now();\r\n\r\n // Extract SQL (first arg usually string or config object)\r\n const sql = typeof args[0] === 'string' ? args[0] : args[0].text;\r\n\r\n // Wrap callback if present, or handle Promise\r\n const result = originalQuery.apply(this, args);\r\n\r\n if (result && typeof result.then === 'function') {\r\n return result.then((res: any) => {\r\n const duration = performance.now() - spanStartAbs;\r\n Context.addSpan({\r\n name: 'Postgres Query',\r\n type: 'db',\r\n startTime,\r\n duration,\r\n meta: { query: sql }\r\n });\r\n return res;\r\n });\r\n }\r\n return result;\r\n };\r\n } catch (e) {\r\n // User doesn't use pg, ignore\r\n }\r\n};","import { client } from '../core/client';\r\n\r\n// 1. Request Handler (Place before routes)\r\nexport const expressMiddleware = () => {\r\n return (req: any, res: any, next: () => void) => {\r\n client.startTrace({\r\n method: req.method,\r\n path: req.originalUrl || req.url,\r\n ip: req.ip || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n headers: req.headers\r\n }, () => {\r\n\r\n // Auto-detect status code on finish\r\n res.once('finish', () => {\r\n try {\r\n let route = 'UNKNOWN';\r\n // Express populates req.route only if a route matched\r\n if (req.route && req.route.path) {\r\n route = (req.baseUrl || '') + req.route.path;\r\n } else if (res.statusCode === 404) {\r\n route = 'Not Found';\r\n } else {\r\n route = req.path || 'Wildcard';\r\n }\r\n\r\n client.endTrace(res.statusCode, { route });\r\n } catch (e) { /* Fail open */ }\r\n });\r\n\r\n next();\r\n });\r\n };\r\n};\r\n\r\n// 2. Error Handler (Place after routes)\r\n// This is required in Express to capture the actual Error Object (Stack Trace)\r\nexport const expressErrorHandler = () => {\r\n return (err: any, req: any, res: any, next: (err?: any) => void) => {\r\n\r\n // 1. Capture the exception context\r\n client.captureError(err);\r\n\r\n // 2. Pass it to the next error handler (don't swallow it)\r\n next(err);\r\n };\r\n};","/**\r\n * Heuristic URL Normalizer\r\n * Converts raw paths with IDs into generic patterns to prevent high cardinality.\r\n * Example: /users/123/orders/abc-def -> /users/:id/orders/:uuid\r\n */\r\nexport const normalizePath = (path: string): string => {\r\n if (!path || path === '/') return '/';\r\n\r\n return path\r\n // Replace UUIDs (long alphanumeric strings)\r\n .replace(\r\n /[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,\r\n ':uuid'\r\n )\r\n // Replace MongoDB ObjectIds (24 hex chars)\r\n .replace(/[0-9a-fA-F]{24}/g, ':objectId')\r\n // Replace pure numeric IDs (e.g., /123)\r\n .replace(/\\/(\\d+)(?=\\/|$)/g, '/:id')\r\n // Remove query strings\r\n .split('?')[0];\r\n};\r\n\r\n/**\r\n * Tries to extract route from Framework internals, falls back to heuristic\r\n */\r\nexport const getRoute = (req: any, fallbackPath: string): string => {\r\n // Express / Connect\r\n if (req.route && req.route.path) {\r\n return (req.baseUrl || '') + req.route.path;\r\n }\r\n\r\n // H3 / Nitro (Nuxt)\r\n if (req.context && req.context.matchedRoute) {\r\n return req.context.matchedRoute.path;\r\n }\r\n\r\n // Fastify\r\n if (req.routerPath) {\r\n return req.routerPath;\r\n }\r\n\r\n // Fallback: Heuristic Normalization\r\n return normalizePath(fallbackPath);\r\n};","import { client } from '../core/client';\r\nimport { getRoute } from '../core/normalizer';\r\n\r\ntype EventHandler = (event: any) => any;\r\n\r\nexport const wrapH3 = (handler: EventHandler) => {\r\n return (event: any) => {\r\n const req = event.node.req;\r\n const path = req.originalUrl || req.url || '/';\r\n\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n userAgent: req.headers['user-agent'],\r\n headers: req.headers // Pass headers\r\n }, async () => {\r\n try {\r\n const response = await handler(event);\r\n let status = 200;\r\n if (event.node.res.statusCode) status = event.node.res.statusCode;\r\n if (response && response.statusCode) status = response.statusCode;\r\n\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n return response;\r\n } catch (err: any) {\r\n client.captureError(err);\r\n const status = err.statusCode || err.status || 500;\r\n client.endTrace(status, { route: getRoute(event, path) });\r\n throw err;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { normalizePath } from '../core/normalizer';\r\n\r\n// --- App Router Wrapper ---\r\nexport const wrapNextRoute = (handler: Function) => {\r\n return async (req: Request | any, context?: any) => {\r\n\r\n // Extract info from Web Standard Request\r\n const url = req.url ? new URL(req.url) : { pathname: '/' };\r\n const method = req.method || 'GET';\r\n\r\n // Header Extraction\r\n let headers: Record<string, string> = {};\r\n let ua: string | undefined;\r\n let ip: string | undefined;\r\n\r\n if (typeof req.headers.get === 'function') {\r\n // It's a Web Request Object\r\n ua = req.headers.get('user-agent');\r\n ip = req.headers.get('x-forwarded-for');\r\n\r\n // Convert to plain object for trace context extraction\r\n req.headers.forEach((value: string, key: string) => {\r\n headers[key] = value;\r\n });\r\n } else {\r\n // It's a Node Request Object (rare in App router but possible)\r\n headers = req.headers;\r\n ua = headers['user-agent'];\r\n ip = headers['x-forwarded-for'] as string;\r\n }\r\n\r\n return client.startTrace({\r\n method,\r\n path: url.pathname,\r\n userAgent: ua,\r\n ip: ip,\r\n headers: headers // Pass extracted headers\r\n }, async () => {\r\n try {\r\n const response = await handler(req, context);\r\n const status = response?.status || 200;\r\n\r\n client.endTrace(status, { route: normalizePath(url.pathname) });\r\n return response;\r\n } catch (err: any) {\r\n client.captureError(err);\r\n client.endTrace(500, { route: normalizePath(url.pathname) });\r\n throw err;\r\n }\r\n });\r\n };\r\n};\r\n\r\n// --- Pages Router Wrapper ---\r\nexport const wrapNextPages = (handler: Function) => {\r\n return async (req: any, res: any) => {\r\n const path = req.url ? req.url.split('?')[0] : '/';\r\n\r\n return client.startTrace({\r\n method: req.method || 'GET',\r\n path: path,\r\n userAgent: req.headers['user-agent'],\r\n ip: req.headers['x-forwarded-for'] || req.socket?.remoteAddress,\r\n headers: req.headers // Standard Node headers work fine\r\n }, async () => {\r\n\r\n const done = () => {\r\n client.endTrace(res.statusCode || 200, { route: normalizePath(path) });\r\n };\r\n\r\n res.once('finish', done);\r\n res.once('close', done);\r\n\r\n try {\r\n return await handler(req, res);\r\n } catch (e: any) {\r\n client.captureError(e);\r\n throw e;\r\n }\r\n });\r\n };\r\n};","import { client } from '../core/client';\r\nimport { SenzorOptions } from '../core/types';\r\n\r\nexport const senzorPlugin = (fastify: any, options: SenzorOptions, done: Function) => {\r\n if (options && options.apiKey) {\r\n client.init(options);\r\n }\r\n\r\n fastify.addHook('onRequest', (request: any, reply: any, next: Function) => {\r\n client.startTrace({\r\n method: request.method,\r\n path: request.raw.url || request.url,\r\n ip: request.ip,\r\n userAgent: request.headers['user-agent'],\r\n headers: request.headers // Pass headers\r\n }, () => next());\r\n });\r\n\r\n fastify.addHook('onError', (request: any, reply: any, error: any, next: Function) => {\r\n client.captureError(error);\r\n next();\r\n });\r\n\r\n fastify.addHook('onResponse', (request: any, reply: any, next: Function) => {\r\n const route = request.routeOptions?.url || request.routerPath || 'UNKNOWN';\r\n client.endTrace(reply.statusCode, { route });\r\n next();\r\n });\r\n\r\n done();\r\n};","import { client } from './core/client';\r\nimport { expressMiddleware, expressErrorHandler } from './middleware/express';\r\nimport { wrapH3 } from './wrappers/h3';\r\nimport { wrapNextRoute, wrapNextPages } from './wrappers/next';\r\nimport { senzorPlugin } from './wrappers/fastify';\r\nimport { SenzorOptions } from './core/types';\r\n\r\nconst Senzor = {\r\n init: (options: SenzorOptions) => client.init(options),\r\n flush: () => client.flush(),\r\n track: client.track.bind(client),\r\n startSpan: client.startSpan.bind(client),\r\n captureException: client.captureError.bind(client),\r\n\r\n // Express\r\n requestHandler: expressMiddleware,\r\n errorHandler: expressErrorHandler,\r\n\r\n // Next\r\n wrapNextRoute,\r\n wrapNextPages,\r\n\r\n // H3\r\n wrapH3,\r\n\r\n // Fastify\r\n fastifyPlugin: senzorPlugin\r\n};\r\n\r\nexport default Senzor;\r\nexport { Senzor };"],"mappings":"utBAEO,IAAMA,EAAN,KAAgB,CAIrB,YAAoBC,EAAuB,CAAvB,YAAAA,EAHpB,KAAQ,MAAe,CAAC,EACxB,KAAQ,MAA+B,KAGjC,OAAO,YAAgB,MACzB,KAAK,MAAQ,YAAY,IAAM,KAAK,MAAM,EAAGA,EAAO,eAAiB,GAAK,EACtE,KAAK,OAAS,OAAO,KAAK,MAAM,OAAU,YAC5C,KAAK,MAAM,MAAM,EAGvB,CAEO,IAAIC,EAAY,CACrB,KAAK,MAAM,KAAKA,CAAK,EACjB,KAAK,MAAM,SAAW,KAAK,OAAO,WAAa,MACjD,KAAK,MAAM,CAEf,CAEA,MAAa,OAAQ,CACnB,GAAI,KAAK,MAAM,SAAW,EAAG,O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,CACR,CACF,CAAC,CACH,EC9EK,IAAMC,EAAe,CAACC,EAAcC,EAAwBC,IAAmB,CAChFD,GAAWA,EAAQ,QACrBE,EAAO,KAAKF,CAAO,EAGrBD,EAAQ,QAAQ,YAAa,CAACI,EAAcC,EAAYC,IAAmB,CACzEH,EAAO,WAAW,CAChB,OAAQC,EAAQ,OAChB,KAAMA,EAAQ,IAAI,KAAOA,EAAQ,IACjC,GAAIA,EAAQ,GACZ,UAAWA,EAAQ,QAAQ,YAAY,EACvC,QAASA,EAAQ,OACnB,EAAG,IAAME,EAAK,CAAC,CACjB,CAAC,EAEDN,EAAQ,QAAQ,UAAW,CAACI,EAAcC,EAAYE,EAAYD,IAAmB,CACnFH,EAAO,aAAaI,CAAK,EACzBD,EAAK,CACP,CAAC,EAEDN,EAAQ,QAAQ,aAAc,CAACI,EAAcC,EAAYC,IAAmB,CAC1E,IAAME,EAAQJ,EAAQ,cAAc,KAAOA,EAAQ,YAAc,UACjED,EAAO,SAASE,EAAM,WAAY,CAAE,MAAAG,CAAM,CAAC,EAC3CF,EAAK,CACP,CAAC,EAEDJ,EAAK,CACP,ECvBA,IAAMO,EAAS,CACb,KAAOC,GAA2BC,EAAO,KAAKD,CAAO,EACrD,MAAO,IAAMC,EAAO,MAAM,EAC1B,MAAOA,EAAO,MAAM,KAAKA,CAAM,EAC/B,UAAWA,EAAO,UAAU,KAAKA,CAAM,EACvC,iBAAkBA,EAAO,aAAa,KAAKA,CAAM,EAGjD,eAAgBC,EAChB,aAAcC,EAGd,cAAAC,EACA,cAAAC,EAGA,OAAAC,EAGA,cAAeC,CACjB,EAEOC,GAAQT","names":["Transport","config","trace","batch","err","import_async_hooks","storage","Context","trace","fn","span","store","error","import_crypto","import_http","import_https","import_url","import_crypto","shimmer","module","methodName","wrapper","original","instrumentFetch","ingestUrl","debug","ingestHost","originalFetch","input","init","urlStr","trace","Context","method","startTime","spanStartAbs","spanId","hostname","newInit","response","duration","err","instrumentHttp","requestWrapper","args","options","protocol","host","path","req","captureSpan","res","error","http","https","instrumentMongo","debug","mongodb","Collection","FindCursor","AggregationCursor","recordSpan","name","operation","collection","startAbs","traceStart","err","duration","Context","method","original","args","trace","spanStartAbs","collName","result","res","patchCursor","CursorClass","label","originalToArray","onSuccess","onError","e","instrumentPg","pg","originalQuery","args","trace","Context","startTime","spanStartAbs","sql","result","res","duration","SenzorClient","options","endpoint","debug","Transport","instrumentHttp","instrumentFetch","instrumentMongo","instrumentPg","data","next","parentTraceId","parentSpanId","trace","Context","status","extraData","duration","payload","error","name","type","startTime","spanStartAbs","spanId","meta","client","expressMiddleware","req","res","next","client","route","expressErrorHandler","err","normalizePath","path","getRoute","req","fallbackPath","wrapH3","handler","event","req","path","client","response","status","getRoute","err","wrapNextRoute","handler","req","context","url","method","headers","ua","ip","value","key","client","response","status","normalizePath","err","wrapNextPages","res","path","done","e","senzorPlugin","fastify","options","done","client","request","reply","next","error","route","Senzor","options","client","expressMiddleware","expressErrorHandler","wrapNextRoute","wrapNextPages","wrapH3","senzorPlugin","index_default"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var B=Object.create;var A=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var Y=(e,t)=>{for(var r in t)A(e,r,{get:t[r],enumerable:!0})},k=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Q(t))!X.call(e,o)&&o!==r&&A(e,o,{get:()=>t[o],enumerable:!(n=J(t,o))||n.enumerable});return e};var E=(e,t,r)=>(r=e!=null?B(V(e)):{},k(t||!e||!e.__esModule?A(r,"default",{value:e,enumerable:!0}):r,e)),Z=e=>k(A({},"__esModule",{value:!0}),e);var q={};Y(q,{Senzor:()=>j,default:()=>_});module.exports=Z(q);var z=class{constructor(t){this.config=t;this.queue=[];this.timer=null;typeof setInterval<"u"&&(this.timer=setInterval(()=>this.flush(),t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}add(t){this.queue.push(t),this.queue.length>=(this.config.batchSize||100)&&this.flush()}async flush(){if(this.queue.length===0)return;let t=[...this.queue];this.queue=[];try{await fetch(this.config.endpoint||"https://api.senzor.dev/api/ingest/apm",{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey},body:JSON.stringify(t),keepalive:!0}),this.config.debug&&console.log(`[Senzor] Flushed ${t.length} traces`)}catch(r){this.config.debug&&console.error("[Senzor] Ingestion Error:",r)}}};var M=require("async_hooks"),F=new M.AsyncLocalStorage,l={run:(e,t)=>F.run(e,t),current:()=>F.getStore(),addSpan:e=>{let t=F.getStore();t?t.spans.push(e):console.warn("[Senzor] Lost context for span:",e.name)}};var I=require("crypto");var v=E(require("http")),O=E(require("https")),T=require("url");var C=(e,t,r)=>{if(!e[t])return;let n=e[t];e[t]=r(n)},N=(e,t=!1)=>{if(!globalThis.fetch)return;let r="";try{r=new T.URL(e).hostname}catch{}let n=globalThis.fetch;globalThis.fetch=async(o,a)=>{let i="";if(typeof o=="string"?i=o:o instanceof T.URL?i=o.toString():o&&o.url&&(i=o.url),r&&i.includes(r))return n(o,a);let c=l.current();if(!c)return n(o,a);let s=(a?.method||"GET").toUpperCase(),f=performance.now()-c.startTime,w=performance.now(),d="unknown";try{d=new T.URL(i).hostname}catch{}t&&console.log(`[Senzor] Tracking Fetch: ${s} ${d}`);try{let p=await n(o,a),h=performance.now()-w;return l.addSpan({name:`${s} ${d}`,type:"http",startTime:f,duration:h,status:p.status,meta:{url:i,method:s,library:"fetch"}}),p}catch(p){let h=performance.now()-w;throw l.addSpan({name:`${s} ${d}`,type:"http",startTime:f,duration:h,status:500,meta:{error:p.message,url:i,library:"fetch"}}),p}}},R=(e,t=!1)=>{let r="";try{r=new T.URL(e).hostname}catch{}let n=o=>function(...a){let i={},c="";if(typeof a[0]=="string"||a[0]instanceof T.URL)c=a[0].toString(),typeof a[1]=="object"&&a[1]!==null&&(i=a[1]);else{i=a[0]||{};let u=i.protocol||(i.port===443?"https:":"http:"),g=i.hostname||i.host||"localhost",x=i.path||"/";c=`${u}//${g}${x}`}if(r&&(c.includes(r)||i.hostname&&i.hostname.includes(r)))return o.apply(this,a);let s=l.current();if(!s)return o.apply(this,a);let f=(i.method||"GET").toUpperCase(),w=performance.now()-s.startTime,d=performance.now(),p="unknown";try{p=new T.URL(c).hostname}catch{p=i.hostname||"unknown"}let h=o.apply(this,a),y=(u,g)=>{let x=performance.now()-d;l.addSpan({name:`${f} ${p}`,type:"http",startTime:w,duration:x,status:g?500:u?.statusCode||0,meta:{url:c,method:f,library:"http"}})};return h.on("response",u=>{u.once("end",()=>y(u)),u.once("error",g=>y(u,g))}),h.on("error",u=>y(null,u)),h};C(v.default,"request",n),C(v.default,"get",n),C(O.default,"request",n),C(O.default,"get",n)};var U=(e=!1)=>{try{let t=require("mongodb"),r=t.Collection,n=t.FindCursor||require("mongodb/lib/cursor/find_cursor").FindCursor,o=t.AggregationCursor||require("mongodb/lib/cursor/aggregation_cursor").AggregationCursor;e&&console.log("[Senzor] Instrumenting MongoDB (Collection + Cursors)...");let a=(s,f,w,d,p,h)=>{let y=performance.now()-d;l.addSpan({name:`MongoDB ${s}`,type:"db",startTime:performance.now()-p-y,duration:y,status:h?500:0,meta:{collection:w,operation:f,error:h?h.message:void 0}}),e&&console.log(`[Senzor] Captured Mongo: ${s} (${y.toFixed(2)}ms)`)};["insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","countDocuments"].forEach(s=>{if(!r.prototype[s])return;let f=r.prototype[s];r.prototype[s]=function(...w){let d=l.current();if(!d)return f.apply(this,w);let p=performance.now(),h=d.startTime,y=this.collectionName;try{let u=f.apply(this,w);return u&&typeof u.then=="function"?u.then(g=>(a(s,s,y,p,h),g),g=>{throw a(s,s,y,p,h,g),g}):u}catch(u){throw a(s,s,y,p,h,u),u}}});let c=(s,f)=>{if(!s||!s.prototype.toArray)return;let w=s.prototype.toArray;s.prototype.toArray=function(...d){let p=l.current();if(!p)return w.apply(this,d);let h=performance.now(),y=p.startTime,u=this.namespace?.collection||"unknown",g=S=>(a(f,f,u,h,y),S),x=S=>{throw a(f,f,u,h,y,S),S};try{let S=w.apply(this,d);return S&&typeof S.then=="function"?S.then(g,x):g(S)}catch(S){x(S)}}};c(n,"find"),c(o,"aggregate")}catch(t){e&&console.warn("[Senzor] MongoDB instrumentation warning:",t.message)}};var H=()=>{try{let e=require("pg"),t=e.Client.prototype.query;e.Client.prototype.query=function(...r){let n=l.current();if(!n)return t.apply(this,r);let o=performance.now()-n.startTime,a=performance.now(),i=typeof r[0]=="string"?r[0]:r[0].text,c=t.apply(this,r);return c&&typeof c.then=="function"?c.then(s=>{let f=performance.now()-a;return l.addSpan({name:"Postgres Query",type:"db",startTime:o,duration:f,meta:{query:i}}),s}):c}}catch{}};var P=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;if(this.transport=new z({...t,endpoint:r}),!this.isInstrumented){try{R(r,n)}catch{}try{N(r,n)}catch{}try{U(n)}catch{}try{H()}catch{}this.isInstrumented=!0,n&&console.log("[Senzor] Auto-instrumentation enabled (HTTP, Fetch, Mongo)")}}startTrace(t,r){if(!this.transport)return r();let n={id:(0,I.randomUUID)(),startTime:performance.now(),data:t,spans:[]};return l.run(n,r)}endTrace(t,r={}){let n=l.current();if(!n||!this.transport)return;let o=performance.now()-n.startTime,a={traceId:n.id,...n.data,...r,status:t,duration:o,spans:n.spans,timestamp:new Date().toISOString()};this.transport.add(a)}track(t){this.transport?.add({traceId:(0,I.randomUUID)(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,r="custom"){let n=l.current();if(!n)return{end:()=>{}};let o=performance.now()-n.startTime,a=performance.now();return{end:(i,c)=>{l.addSpan({name:t,type:r,startTime:o,duration:performance.now()-a,status:c,meta:i})}}}async flush(){this.transport&&await this.transport.flush()}},m=new P;var D=()=>(e,t,r)=>{m.startTrace({method:e.method,path:e.originalUrl||e.url,ip:e.ip||e.socket?.remoteAddress,userAgent:e.headers["user-agent"]},()=>{t.once("finish",()=>{try{let n="UNKNOWN";e.route&&e.route.path?n=(e.baseUrl||"")+e.route.path:t.statusCode===404?n="Not Found":n=e.path||"Wildcard",m.endTrace(t.statusCode,{route:n})}catch{}}),r()})};var b=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],$=(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:b(t);var K=e=>t=>{let r=t.node.req,n=r.originalUrl||r.url||"/";return m.startTrace({method:r.method||"GET",path:n,ip:r.headers["x-forwarded-for"]||r.socket?.remoteAddress,userAgent:r.headers["user-agent"]},async()=>{try{let o=await e(t),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),o&&o.statusCode&&(a=o.statusCode),m.endTrace(a,{route:$(t,n)}),o}catch(o){let a=o.statusCode||o.status||500;throw m.endTrace(a,{route:$(t,n)}),o}})};var G=e=>async(t,r)=>{let n=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",a=t.headers.get?t.headers.get("user-agent"):void 0,i=t.headers.get?t.headers.get("x-forwarded-for"):void 0;return m.startTrace({method:o,path:n.pathname,userAgent:a,ip:i},async()=>{try{let c=await e(t,r),s=c?.status||200;return m.endTrace(s,{route:b(n.pathname)}),c}catch(c){throw m.endTrace(500,{route:b(n.pathname)}),c}})},L=e=>async(t,r)=>{let n=t.url?t.url.split("?")[0]:"/";return m.startTrace({method:t.method||"GET",path:n,userAgent:t.headers["user-agent"],ip:t.headers["x-forwarded-for"]||t.socket?.remoteAddress},async()=>{let o=()=>{m.endTrace(r.statusCode||200,{route:b(n)})};r.once("finish",o),r.once("close",o);try{return await e(t,r)}catch(a){throw a}})};var W=(e,t,r)=>{t&&t.apiKey&&m.init(t),e.addHook("onRequest",(n,o,a)=>{n.senzorStart=performance.now(),a()}),e.addHook("onResponse",(n,o,a)=>{let i=performance.now()-(n.senzorStart||performance.now()),c=n.routeOptions?.url||n.routerPath;m.track({method:n.method,route:c||"UNKNOWN",path:n.raw.url||n.url,status:o.statusCode,duration:i,ip:n.ip,userAgent:n.headers["user-agent"]}),a()}),r()};var j={init:e=>m.init(e),flush:()=>m.flush(),requestHandler:D,wrapNextRoute:G,wrapNextPages:L,wrapH3:K,fastifyPlugin:W},_=j;0&&(module.exports={Senzor});
1
+ "use strict";var Q=Object.create;var b=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var _=(e,t)=>{for(var n in t)b(e,n,{get:t[n],enumerable:!0})},N=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Z(t))!Y.call(e,o)&&o!==n&&b(e,o,{get:()=>t[o],enumerable:!(r=X(t,o))||r.enumerable});return e};var P=(e,t,n)=>(n=e!=null?Q(V(e)):{},N(t||!e||!e.__esModule?b(n,"default",{value:e,enumerable:!0}):n,e)),q=e=>N(b({},"__esModule",{value:!0}),e);var et={};_(et,{Senzor:()=>J,default:()=>tt});module.exports=q(et);var E=class{constructor(t){this.config=t;this.queue=[];this.timer=null;typeof setInterval<"u"&&(this.timer=setInterval(()=>this.flush(),t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}add(t){this.queue.push(t),this.queue.length>=(this.config.batchSize||100)&&this.flush()}async flush(){if(this.queue.length===0)return;let t=[...this.queue];this.queue=[];try{await fetch(this.config.endpoint||"https://api.senzor.dev/api/ingest/apm",{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey},body:JSON.stringify(t),keepalive:!0}),this.config.debug&&console.log(`[Senzor] Flushed ${t.length} traces`)}catch(n){this.config.debug&&console.error("[Senzor] Ingestion Error:",n)}}};var H=require("async_hooks"),z=new H.AsyncLocalStorage,l={run:(e,t)=>z.run(e,t),current:()=>z.getStore(),addSpan:e=>{let t=z.getStore();t&&t.spans.push(e)},setError:e=>{let t=z.getStore();t&&(t.error={name:e.name,message:e.message,stack:e.stack})}};var C=require("crypto");var F=P(require("http")),O=P(require("https")),x=require("url");var v=require("crypto"),I=(e,t,n)=>{if(!e[t])return;let r=e[t];e[t]=n(r)},$=(e,t=!1)=>{if(!globalThis.fetch)return;let n="";try{n=new x.URL(e).hostname}catch{}let r=globalThis.fetch;globalThis.fetch=async(o,a)=>{let i="";if(typeof o=="string"?i=o:o instanceof x.URL?i=o.toString():o&&o.url&&(i=o.url),n&&i.includes(n))return r(o,a);let u=l.current();if(!u)return r(o,a);let s=(a?.method||"GET").toUpperCase(),d=performance.now()-u.startTime,S=performance.now(),g=(0,v.randomUUID)(),y="unknown";try{y=new x.URL(i).hostname}catch{}t&&console.log(`[Senzor] Fetch: ${s} ${y}`);let p={...a};p.headers||(p.headers={}),p.headers instanceof Headers?(p.headers.set("x-senzor-trace-id",u.id),p.headers.set("x-senzor-parent-span-id",g)):Array.isArray(p.headers)?(p.headers.push(["x-senzor-trace-id",u.id]),p.headers.push(["x-senzor-parent-span-id",g])):(p.headers["x-senzor-trace-id"]=u.id,p.headers["x-senzor-parent-span-id"]=g);try{let h=await r(o,p),m=performance.now()-S;return l.addSpan({spanId:g,name:`${s} ${y}`,type:"http",startTime:d,duration:m,status:h.status,meta:{url:i,method:s,library:"fetch"}}),h}catch(h){let m=performance.now()-S;throw l.addSpan({spanId:g,name:`${s} ${y}`,type:"http",startTime:d,duration:m,status:500,meta:{error:h.message,url:i,library:"fetch"}}),h}}},U=(e,t=!1)=>{let n="";try{n=new x.URL(e).hostname}catch{}let r=o=>function(...a){let i={},u="";if(typeof a[0]=="string"||a[0]instanceof x.URL)u=a[0].toString(),typeof a[1]=="object"&&a[1]!==null&&(i=a[1]);else{i=a[0]||{};let f=i.protocol||(i.port===443?"https:":"http:"),T=i.hostname||i.host||"localhost",w=i.path||"/";u=`${f}//${T}${w}`}if(n&&(u.includes(n)||i.hostname&&i.hostname.includes(n)))return o.apply(this,a);let s=l.current();if(!s)return o.apply(this,a);let d=(i.method||"GET").toUpperCase(),S=performance.now()-s.startTime,g=performance.now(),y=(0,v.randomUUID)(),p="unknown";try{p=new x.URL(u).hostname}catch{p=i.hostname||"unknown"}i.headers||(i.headers={}),i.headers["x-senzor-trace-id"]=s.id,i.headers["x-senzor-parent-span-id"]=y;let h=o.apply(this,a),m=(f,T)=>{let w=performance.now()-g;l.addSpan({spanId:y,name:`${d} ${p}`,type:"http",startTime:S,duration:w,status:T?500:f?.statusCode||0,meta:{url:u,method:d,library:"http"}})};return h.on("response",f=>{f.once("end",()=>m(f)),f.once("close",()=>m(f)),f.once("error",T=>m(f,T))}),h.on("error",f=>m(null,f)),h};I(F.default,"request",r),I(F.default,"get",r),I(O.default,"request",r),I(O.default,"get",r)};var M=(e=!1)=>{try{let t=require("mongodb"),n=t.Collection,r=t.FindCursor||require("mongodb/lib/cursor/find_cursor").FindCursor,o=t.AggregationCursor||require("mongodb/lib/cursor/aggregation_cursor").AggregationCursor;e&&console.log("[Senzor] Instrumenting MongoDB (Collection + Cursors)...");let a=(s,d,S,g,y,p)=>{let h=performance.now()-g;l.addSpan({name:`MongoDB ${s}`,type:"db",startTime:performance.now()-y-h,duration:h,status:p?500:0,meta:{collection:S,operation:d,error:p?p.message:void 0}}),e&&console.log(`[Senzor] Captured Mongo: ${s} (${h.toFixed(2)}ms)`)};["insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","countDocuments"].forEach(s=>{if(!n.prototype[s])return;let d=n.prototype[s];n.prototype[s]=function(...S){let g=l.current();if(!g)return d.apply(this,S);let y=performance.now(),p=g.startTime,h=this.collectionName;try{let m=d.apply(this,S);return m&&typeof m.then=="function"?m.then(f=>(a(s,s,h,y,p),f),f=>{throw a(s,s,h,y,p,f),f}):m}catch(m){throw a(s,s,h,y,p,m),m}}});let u=(s,d)=>{if(!s||!s.prototype.toArray)return;let S=s.prototype.toArray;s.prototype.toArray=function(...g){let y=l.current();if(!y)return S.apply(this,g);let p=performance.now(),h=y.startTime,m=this.namespace?.collection||"unknown",f=w=>(a(d,d,m,p,h),w),T=w=>{throw a(d,d,m,p,h,w),w};try{let w=S.apply(this,g);return w&&typeof w.then=="function"?w.then(f,T):f(w)}catch(w){T(w)}}};u(r,"find"),u(o,"aggregate")}catch(t){e&&console.warn("[Senzor] MongoDB instrumentation warning:",t.message)}};var D=()=>{try{let e=require("pg"),t=e.Client.prototype.query;e.Client.prototype.query=function(...n){let r=l.current();if(!r)return t.apply(this,n);let o=performance.now()-r.startTime,a=performance.now(),i=typeof n[0]=="string"?n[0]:n[0].text,u=t.apply(this,n);return u&&typeof u.then=="function"?u.then(s=>{let d=performance.now()-a;return l.addSpan({name:"Postgres Query",type:"db",startTime:o,duration:d,meta:{query:i}}),s}):u}}catch{}};var R=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}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;if(this.transport=new E({...t,endpoint:n}),!this.isInstrumented){try{U(n,r)}catch{}try{$(n,r)}catch{}try{M(r)}catch{}try{D()}catch{}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}startTrace(t,n){if(!this.transport)return n();let r,o;t.headers&&(r=t.headers["x-senzor-trace-id"]||t.headers["X-SENZOR-TRACE-ID"],o=t.headers["x-senzor-parent-span-id"]||t.headers["X-SENZOR-PARENT-SPAN-ID"]);let a={id:(0,C.randomUUID)(),startTime:performance.now(),data:{...t,parentTraceId:r,parentSpanId:o},spans:[]};return l.run(a,n)}endTrace(t,n={}){let r=l.current();if(!r||!this.transport)return;let o=performance.now()-r.startTime,a={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,...r.data,...n,status:t,duration:o,spans:r.spans,timestamp:new Date().toISOString(),error:r.error};this.transport.add(a)}captureError(t){t instanceof Error?l.setError(t):typeof t=="string"&&l.setError(new Error(t))}track(t){this.transport?.add({traceId:(0,C.randomUUID)(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=l.current();if(!r)return{end:()=>{}};let o=performance.now()-r.startTime,a=performance.now(),i=(0,C.randomUUID)();return{end:(u,s)=>{let d=performance.now()-a;l.addSpan({spanId:i,name:t,type:n,startTime:o,duration:d,status:s,meta:u})}}}async flush(){this.transport&&await this.transport.flush()}},c=new R;var K=()=>(e,t,n)=>{c.startTrace({method:e.method,path:e.originalUrl||e.url,ip:e.ip||e.socket?.remoteAddress,userAgent:e.headers["user-agent"],headers:e.headers},()=>{t.once("finish",()=>{try{let r="UNKNOWN";e.route&&e.route.path?r=(e.baseUrl||"")+e.route.path:t.statusCode===404?r="Not Found":r=e.path||"Wildcard",c.endTrace(t.statusCode,{route:r})}catch{}}),n()})},G=()=>(e,t,n,r)=>{c.captureError(e),r(e)};var A=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],k=(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:A(t);var L=e=>t=>{let n=t.node.req,r=n.originalUrl||n.url||"/";return c.startTrace({method:n.method||"GET",path:r,ip:n.headers["x-forwarded-for"]||n.socket?.remoteAddress,userAgent:n.headers["user-agent"],headers:n.headers},async()=>{try{let o=await e(t),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),o&&o.statusCode&&(a=o.statusCode),c.endTrace(a,{route:k(t,r)}),o}catch(o){c.captureError(o);let a=o.statusCode||o.status||500;throw c.endTrace(a,{route:k(t,r)}),o}})};var W=e=>async(t,n)=>{let r=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",a={},i,u;return typeof t.headers.get=="function"?(i=t.headers.get("user-agent"),u=t.headers.get("x-forwarded-for"),t.headers.forEach((s,d)=>{a[d]=s})):(a=t.headers,i=a["user-agent"],u=a["x-forwarded-for"]),c.startTrace({method:o,path:r.pathname,userAgent:i,ip:u,headers:a},async()=>{try{let s=await e(t,n),d=s?.status||200;return c.endTrace(d,{route:A(r.pathname)}),s}catch(s){throw c.captureError(s),c.endTrace(500,{route:A(r.pathname)}),s}})},j=e=>async(t,n)=>{let r=t.url?t.url.split("?")[0]:"/";return c.startTrace({method:t.method||"GET",path:r,userAgent:t.headers["user-agent"],ip:t.headers["x-forwarded-for"]||t.socket?.remoteAddress,headers:t.headers},async()=>{let o=()=>{c.endTrace(n.statusCode||200,{route:A(r)})};n.once("finish",o),n.once("close",o);try{return await e(t,n)}catch(a){throw c.captureError(a),a}})};var B=(e,t,n)=>{t&&t.apiKey&&c.init(t),e.addHook("onRequest",(r,o,a)=>{c.startTrace({method:r.method,path:r.raw.url||r.url,ip:r.ip,userAgent:r.headers["user-agent"],headers:r.headers},()=>a())}),e.addHook("onError",(r,o,a,i)=>{c.captureError(a),i()}),e.addHook("onResponse",(r,o,a)=>{let i=r.routeOptions?.url||r.routerPath||"UNKNOWN";c.endTrace(o.statusCode,{route:i}),a()}),n()};var J={init:e=>c.init(e),flush:()=>c.flush(),track:c.track.bind(c),startSpan:c.startSpan.bind(c),captureException:c.captureError.bind(c),requestHandler:K,errorHandler:G,wrapNextRoute:W,wrapNextPages:j,wrapH3:L,fastifyPlugin:B},tt=J;0&&(module.exports={Senzor});
2
2
  //# sourceMappingURL=index.js.map