@xcodleox/devinspector 9.0.3 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/angular.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var y=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var x=(t,e)=>{for(var r in e)y(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of P(e))!Q.call(t,n)&&n!==r&&y(t,n,{get:()=>e[n],enumerable:!(s=D(e,n))||s.enumerable});return t};var N=t=>C(y({},"__esModule",{value:!0}),t);var z={};x(z,{AuditAngularErrorHandler:()=>m,audit:()=>a,auditInterceptor:()=>G,devInspectorInterceptor:()=>q});module.exports=N(z);var k=require("@angular/core"),b=require("@angular/common/http"),_=require("rxjs/operators");var v="https://api.devinspector.com.br/api/ingest/track",I="https://api.devinspector.com.br/api/ingest/apm";var O=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function B(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return O.some(r=>e.includes(r))}function l(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>l(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(B(i)){n[i]="[REDACTED]";continue}n[i]=l(o,e+1,r)}return n}finally{r.delete(t)}}function T(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=l(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function M(t){return t&&String(t).trim().toUpperCase()||void 0}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function H(t){return String(t??"").trim().slice(0,200)}function L(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function g(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(t){return l(t)}var w=class{constructor(){this.apiKey="";this.endpoint=v;this.apmEndpoint=I;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||v,this.apmEndpoint=e.apmEndpoint?.trim()||I,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?l(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?l(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),c=r.pathname.replace(/\/$/,""),d=s.pathname.replace(/\/$/,"");return i===r.origin&&o===c||i===s.origin&&o===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return g("req")}createTraceId(){return g("trace")}createSpanId(){return g("span")}captureRequest(e){let r=M(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=R(e.statusCode)??0,i=A(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=A(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(n)})}captureMetric(e,r,s={},n={}){let i=H(e);if(!i)return Promise.resolve();let o;try{o=L(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=M(n.method),o=R(n.statusCode??n.status),c=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...c?{url:c}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(T(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(T(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:g("event"),endpoint:e,payload:u(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=l(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(c&&(d.keepalive=!0),!(await s(e,d)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},U="__DEVINSPECT_AUDIT_CORE_INSTANCE__",S=typeof globalThis<"u"?globalThis:{},a=S[U]||new w;S[U]=a;var m=class{handleError(e){let r=e instanceof Error?e:new Error(String(e));a.captureError(r,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""}),console.error("[DevInspector Angular Error]:",e)}};m.\u0275fac=t=>new(t||m);m.\u0275prov=(0,k.\u0275\u0275defineInjectable)({token:m,factory:m.\u0275fac,providedIn:"root"});var q=(t,e)=>{let r=t.urlWithParams||t.url||"";if(r&&a.isIngestUrl(r))return e(t);let s=a.createRequestId(),n=a.createTraceId(),i=a.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":s,"x-devinspector-trace-id":n,"x-devinspector-span-id":i}}),c=typeof performance<"u"?performance.now():Date.now();return e(o).pipe((0,_.tap)({next:d=>{if(!(d instanceof b.HttpResponse))return;let p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),f=d.status||0;(f>=400||p>=a.getSlowThresholdMs())&&a.captureRequest({method:t.method||"GET",url:r,statusCode:f,durationMs:p,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),a.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:f,durationMs:p,requestId:s,traceId:n,spanId:i}})},error:d=>{let p=d instanceof b.HttpErrorResponse?d:null,f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),h=p?.status||0,E=p?.message||p?.statusText||"Erro de rede no cliente";a.captureRequest({method:t.method||"GET",url:r,statusCode:h,durationMs:f,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),a.captureException(new Error(`HTTP Error ${h}: ${E}`),{url:r,method:t.method||"GET",status:h,statusText:p?.statusText||"",type:"angular_network_error",requestId:s,traceId:n,spanId:i}),a.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:h,durationMs:f,requestId:s,traceId:n,spanId:i,error:E}})}}))},G=q;0&&(module.exports={AuditAngularErrorHandler,audit,auditInterceptor,devInspectorInterceptor});
1
+ "use strict";var y=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var x=(t,e)=>{for(var r in e)y(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of P(e))!Q.call(t,n)&&n!==r&&y(t,n,{get:()=>e[n],enumerable:!(s=D(e,n))||s.enumerable});return t};var N=t=>C(y({},"__esModule",{value:!0}),t);var z={};x(z,{AuditAngularErrorHandler:()=>l,audit:()=>a,auditInterceptor:()=>G,devInspectorInterceptor:()=>_});module.exports=N(z);var k=require("@angular/core"),b=require("@angular/common/http"),q=require("rxjs/operators");var v="https://api.devinspector.com.br/api/ingest/track",I="https://api.devinspector.com.br/api/ingest/apm";var O=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function B(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return O.some(r=>e.includes(r))}function f(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>f(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(B(i)){n[i]="[REDACTED]";continue}n[i]=f(o,e+1,r)}return n}finally{r.delete(t)}}function T(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function M(t){return t&&String(t).trim().toUpperCase()||void 0}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function H(t){return String(t??"").trim().slice(0,200)}function L(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function g(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function d(t){return f(t)}var w=class{constructor(){this.apiKey="";this.endpoint=v;this.apmEndpoint=I;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||v,this.apmEndpoint=e.apmEndpoint?.trim()||I,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?f(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>d(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),p=r.pathname.replace(/\/$/,""),u=s.pathname.replace(/\/$/,"");return i===r.origin&&o===p||i===s.origin&&o===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return g("req")}createTraceId(){return g("trace")}createSpanId(){return g("span")}captureRequest(e){let r=M(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=R(e.statusCode)??0,i=A(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=A(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(n)})}captureMetric(e,r,s={},n={}){let i=H(e);if(!i)return Promise.resolve();let o;try{o=L(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=M(n.method),o=R(n.statusCode??n.status),p=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,u=typeof n.requestId=="string"&&n.requestId.trim()||void 0,c=typeof n.traceId=="string"&&n.traceId.trim()||void 0,m=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...p?{url:p}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},...u?{requestId:u}:{},...c?{traceId:c}:{},...m?{spanId:m}:{},environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(T(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(T(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:g("event"),endpoint:e,payload:d(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=f(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let p=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(p&&(u.keepalive=!0),!(await s(e,u)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},U="__DEVINSPECT_AUDIT_CORE_INSTANCE__",S=typeof globalThis<"u"?globalThis:{},a=S[U]||new w;S[U]=a;var l=class{handleError(e){let r=e instanceof Error?e:new Error(String(e));a.captureError(r,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""}),console.error("[DevInspector Angular Error]:",e)}};l.\u0275fac=t=>new(t||l);l.\u0275prov=(0,k.\u0275\u0275defineInjectable)({token:l,factory:l.\u0275fac,providedIn:"root"});var _=(t,e)=>{let r=t.urlWithParams||t.url||"";if(r&&a.isIngestUrl(r))return e(t);let s=a.createRequestId(),n=a.createTraceId(),i=a.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":s,"x-devinspector-trace-id":n,"x-devinspector-span-id":i}}),p=typeof performance<"u"?performance.now():Date.now();return e(o).pipe((0,q.tap)({next:u=>{if(!(u instanceof b.HttpResponse))return;let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-p)),m=u.status||0;(m>=400||c>=a.getSlowThresholdMs())&&a.captureRequest({method:t.method||"GET",url:r,statusCode:m,durationMs:c,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),a.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:m,durationMs:c,requestId:s,traceId:n,spanId:i}})},error:u=>{let c=u instanceof b.HttpErrorResponse?u:null,m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-p)),h=c?.status||0,E=c?.message||c?.statusText||"Erro de rede no cliente";a.captureRequest({method:t.method||"GET",url:r,statusCode:h,durationMs:m,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),a.captureException(new Error(`HTTP Error ${h}: ${E}`),{url:r,method:t.method||"GET",statusCode:h,statusText:c?.statusText||"",type:"angular_network_error",requestId:s,traceId:n,spanId:i}),a.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:h,durationMs:m,requestId:s,traceId:n,spanId:i,error:E}})}}))},G=_;0&&(module.exports={AuditAngularErrorHandler,audit,auditInterceptor,devInspectorInterceptor});
package/dist/angular.js CHANGED
@@ -1 +1 @@
1
- import{\u0275\u0275defineInjectable as q}from"@angular/core";import{HttpResponse as D,HttpErrorResponse as P}from"@angular/common/http";import{tap as Q}from"rxjs/operators";var w="https://api.devinspector.com.br/api/ingest/track",E="https://api.devinspector.com.br/api/ingest/apm";var U=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function S(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return U.some(r=>e.includes(r))}function m(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>m(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(S(i)){n[i]="[REDACTED]";continue}n[i]=m(o,e+1,r)}return n}finally{r.delete(t)}}function v(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=m(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function I(t){return t&&String(t).trim().toUpperCase()||void 0}function T(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function M(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function k(t){return String(t??"").trim().slice(0,200)}function _(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function g(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function a(t){return m(t)}var b=class{constructor(){this.apiKey="";this.endpoint=w;this.apmEndpoint=E;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||w,this.apmEndpoint=e.apmEndpoint?.trim()||E,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?m(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?m(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>a(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:a(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),c=r.pathname.replace(/\/$/,""),d=s.pathname.replace(/\/$/,"");return i===r.origin&&o===c||i===s.origin&&o===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return g("req")}createTraceId(){return g("trace")}createSpanId(){return g("span")}captureRequest(e){let r=I(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=T(e.statusCode)??0,i=M(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:a(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:a(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=M(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:a(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:a(n)})}captureMetric(e,r,s={},n={}){let i=k(e);if(!i)return Promise.resolve();let o;try{o=_(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:a(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:a({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=I(n.method),o=T(n.statusCode??n.status),c=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...c?{url:c}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},environment:this.environment,release:this.release,user:a(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:a({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(v(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:a(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:a({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(v(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:g("event"),endpoint:e,payload:a(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=m(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(c&&(d.keepalive=!0),!(await s(e,d)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},R="__DEVINSPECT_AUDIT_CORE_INSTANCE__",A=typeof globalThis<"u"?globalThis:{},u=A[R]||new b;A[R]=u;var l=class{handleError(e){let r=e instanceof Error?e:new Error(String(e));u.captureError(r,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""}),console.error("[DevInspector Angular Error]:",e)}};l.\u0275fac=t=>new(t||l);l.\u0275prov=q({token:l,factory:l.\u0275fac,providedIn:"root"});var x=(t,e)=>{let r=t.urlWithParams||t.url||"";if(r&&u.isIngestUrl(r))return e(t);let s=u.createRequestId(),n=u.createTraceId(),i=u.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":s,"x-devinspector-trace-id":n,"x-devinspector-span-id":i}}),c=typeof performance<"u"?performance.now():Date.now();return e(o).pipe(Q({next:d=>{if(!(d instanceof D))return;let p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),f=d.status||0;(f>=400||p>=u.getSlowThresholdMs())&&u.captureRequest({method:t.method||"GET",url:r,statusCode:f,durationMs:p,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),u.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:f,durationMs:p,requestId:s,traceId:n,spanId:i}})},error:d=>{let p=d instanceof P?d:null,f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),h=p?.status||0,y=p?.message||p?.statusText||"Erro de rede no cliente";u.captureRequest({method:t.method||"GET",url:r,statusCode:h,durationMs:f,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),u.captureException(new Error(`HTTP Error ${h}: ${y}`),{url:r,method:t.method||"GET",status:h,statusText:p?.statusText||"",type:"angular_network_error",requestId:s,traceId:n,spanId:i}),u.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:h,durationMs:f,requestId:s,traceId:n,spanId:i,error:y}})}}))},K=x;export{l as AuditAngularErrorHandler,u as audit,K as auditInterceptor,x as devInspectorInterceptor};
1
+ import{\u0275\u0275defineInjectable as _}from"@angular/core";import{HttpResponse as D,HttpErrorResponse as P}from"@angular/common/http";import{tap as Q}from"rxjs/operators";var w="https://api.devinspector.com.br/api/ingest/track",E="https://api.devinspector.com.br/api/ingest/apm";var U=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function S(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return U.some(r=>e.includes(r))}function l(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>l(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(S(i)){n[i]="[REDACTED]";continue}n[i]=l(o,e+1,r)}return n}finally{r.delete(t)}}function v(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=l(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function I(t){return t&&String(t).trim().toUpperCase()||void 0}function T(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function M(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function k(t){return String(t??"").trim().slice(0,200)}function q(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function g(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(t){return l(t)}var b=class{constructor(){this.apiKey="";this.endpoint=w;this.apmEndpoint=E;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||w,this.apmEndpoint=e.apmEndpoint?.trim()||E,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?l(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?l(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),p=r.pathname.replace(/\/$/,""),a=s.pathname.replace(/\/$/,"");return i===r.origin&&o===p||i===s.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return g("req")}createTraceId(){return g("trace")}createSpanId(){return g("span")}captureRequest(e){let r=I(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=T(e.statusCode)??0,i=M(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=M(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(n)})}captureMetric(e,r,s={},n={}){let i=k(e);if(!i)return Promise.resolve();let o;try{o=q(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=I(n.method),o=T(n.statusCode??n.status),p=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,a=typeof n.requestId=="string"&&n.requestId.trim()||void 0,c=typeof n.traceId=="string"&&n.traceId.trim()||void 0,m=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...p?{url:p}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},...a?{requestId:a}:{},...c?{traceId:c}:{},...m?{spanId:m}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(v(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(v(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:g("event"),endpoint:e,payload:u(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=l(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let p=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(p&&(a.keepalive=!0),!(await s(e,a)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},R="__DEVINSPECT_AUDIT_CORE_INSTANCE__",A=typeof globalThis<"u"?globalThis:{},d=A[R]||new b;A[R]=d;var f=class{handleError(e){let r=e instanceof Error?e:new Error(String(e));d.captureError(r,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""}),console.error("[DevInspector Angular Error]:",e)}};f.\u0275fac=t=>new(t||f);f.\u0275prov=_({token:f,factory:f.\u0275fac,providedIn:"root"});var x=(t,e)=>{let r=t.urlWithParams||t.url||"";if(r&&d.isIngestUrl(r))return e(t);let s=d.createRequestId(),n=d.createTraceId(),i=d.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":s,"x-devinspector-trace-id":n,"x-devinspector-span-id":i}}),p=typeof performance<"u"?performance.now():Date.now();return e(o).pipe(Q({next:a=>{if(!(a instanceof D))return;let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-p)),m=a.status||0;(m>=400||c>=d.getSlowThresholdMs())&&d.captureRequest({method:t.method||"GET",url:r,statusCode:m,durationMs:c,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),d.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:m,durationMs:c,requestId:s,traceId:n,spanId:i}})},error:a=>{let c=a instanceof P?a:null,m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-p)),h=c?.status||0,y=c?.message||c?.statusText||"Erro de rede no cliente";d.captureRequest({method:t.method||"GET",url:r,statusCode:h,durationMs:m,route:t.url,requestId:s,traceId:n,spanId:i,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),d.captureException(new Error(`HTTP Error ${h}: ${y}`),{url:r,method:t.method||"GET",statusCode:h,statusText:c?.statusText||"",type:"angular_network_error",requestId:s,traceId:n,spanId:i}),d.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${r}`,metadata:{statusCode:h,durationMs:m,requestId:s,traceId:n,spanId:i,error:y}})}}))},K=x;export{f as AuditAngularErrorHandler,d as audit,K as auditInterceptor,x as devInspectorInterceptor};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var y=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var r in e)y(t,r,{get:e[r],enumerable:!0})},Q=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _(e))!k.call(t,n)&&n!==r&&y(t,n,{get:()=>e[n],enumerable:!(i=D(e,n))||i.enumerable});return t};var C=t=>Q(y({},"__esModule",{value:!0}),t);var x={};P(x,{AuditCore:()=>f,audit:()=>a,coreAuditFetch:()=>S});module.exports=C(x);var I="https://api.devinspector.com.br/api/ingest/track",T="https://api.devinspector.com.br/api/ingest/apm";var N=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function O(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return N.some(r=>e.includes(r))}function m(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>m(s,e+1,r));let i=t,n={};for(let[s,o]of Object.entries(i)){if(O(s)){n[s]="[REDACTED]";continue}n[s]=m(o,e+1,r)}return n}finally{r.delete(t)}}function w(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=m(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function E(t){return t&&String(t).trim().toUpperCase()||void 0}function M(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function B(t){return String(t??"").trim().slice(0,200)}function L(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function g(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(t){return m(t)}var f=class{constructor(){this.apiKey="";this.endpoint=I;this.apmEndpoint=T;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||I,this.apmEndpoint=e.apmEndpoint?.trim()||T,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?m(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?m(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),s=n.origin,o=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return s===r.origin&&o===d||s===i.origin&&o===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return g("req")}createTraceId(){return g("trace")}createSpanId(){return g("span")}captureRequest(e){let r=E(e.method)||"GET",i=String(e.url||"").trim();if(!i)return Promise.resolve();let n=M(e.statusCode)??0,s=A(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:s,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let i=A(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(n)})}captureMetric(e,r,i={},n={}){let s=B(e);if(!s)return Promise.resolve();let o;try{o=L(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...i,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},s=E(n.method),o=M(n.statusCode??n.status),d=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...d?{url:d}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(w(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,1e4),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(w(r.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i={id:g("event"),endpoint:e,payload:u(r),resolve:()=>{}};return new Promise(n=>{i.resolve=n,this.sendQueue.push(i),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return;let n=m(r),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let d=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:s?.signal};if(d&&(c.keepalive=!0),!(await i(e,c)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},R="__DEVINSPECT_AUDIT_CORE_INSTANCE__",U=typeof globalThis<"u"?globalThis:{},a=U[R]||new f;U[R]=a;async function S(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),s=E(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&a.isIngestUrl(n))return i(t,e);let o=a.createRequestId(),d=a.createTraceId(),c=a.createSpanId(),h=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));h.set("x-devinspector-request-id",o),h.set("x-devinspector-trace-id",d),h.set("x-devinspector-span-id",c);let q={...e,headers:h},v=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,q),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-v)),b=p.status>=400||l>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${s} ${n}`,metadata:{phase:"complete",statusCode:p.status,durationMs:l,requestId:o,traceId:d,spanId:c}}),b&&a.captureRequest({method:s,url:n,statusCode:p.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:c}),p}catch(p){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-v));a.addBreadcrumb({type:"http_error",message:`${s} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:o,traceId:d,spanId:c}}),a.captureRequest({method:s,url:n,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:c});let b=p instanceof Error?p:new Error(w(p));throw a.captureError(b,{url:n,method:s,type:r.errorType||"network_error"}),p}}0&&(module.exports={AuditCore,audit,coreAuditFetch});
1
+ "use strict";var w=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})},Q=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _(e))!k.call(t,n)&&n!==r&&w(t,n,{get:()=>e[n],enumerable:!(i=D(e,n))||i.enumerable});return t};var C=t=>Q(w({},"__esModule",{value:!0}),t);var x={};P(x,{AuditCore:()=>h,audit:()=>c,coreAuditFetch:()=>q});module.exports=C(x);var T="https://api.devinspector.com.br/api/ingest/track",M="https://api.devinspector.com.br/api/ingest/apm";var N=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function O(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return N.some(r=>e.includes(r))}function l(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>l(s,e+1,r));let i=t,n={};for(let[s,o]of Object.entries(i)){if(O(s)){n[s]="[REDACTED]";continue}n[s]=l(o,e+1,r)}return n}finally{r.delete(t)}}function E(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=l(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function I(t){return t&&String(t).trim().toUpperCase()||void 0}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function B(t){return String(t??"").trim().slice(0,200)}function L(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function d(t){return l(t)}var h=class{constructor(){this.apiKey="";this.endpoint=T;this.apmEndpoint=M;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||T,this.apmEndpoint=e.apmEndpoint?.trim()||M,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?l(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?l(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>d(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),s=n.origin,o=n.pathname.replace(/\/$/,""),a=r.pathname.replace(/\/$/,""),u=i.pathname.replace(/\/$/,"");return s===r.origin&&o===a||s===i.origin&&o===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}captureRequest(e){let r=I(e.method)||"GET",i=String(e.url||"").trim();if(!i)return Promise.resolve();let n=A(e.statusCode)??0,s=R(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:s,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let i=R(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(n)})}captureMetric(e,r,i={},n={}){let s=B(e);if(!s)return Promise.resolve();let o;try{o=L(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...i,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},s=I(n.method),o=A(n.statusCode??n.status),a=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,u=typeof n.requestId=="string"&&n.requestId.trim()||void 0,m=typeof n.traceId=="string"&&n.traceId.trim()||void 0,g=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...a?{url:a}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...u?{requestId:u}:{},...m?{traceId:m}:{},...g?{spanId:g}:{},environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(E(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,1e4),environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(E(r.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i={id:b("event"),endpoint:e,payload:d(r),resolve:()=>{}};return new Promise(n=>{i.resolve=n,this.sendQueue.push(i),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return;let n=l(r),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:s?.signal};if(a&&(u.keepalive=!0),!(await i(e,u)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},U="__DEVINSPECT_AUDIT_CORE_INSTANCE__",S=typeof globalThis<"u"?globalThis:{},c=S[U]||new h;S[U]=c;async function q(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),s=I(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&c.isIngestUrl(n))return i(t,e);let o=c.createRequestId(),a=c.createTraceId(),u=c.createSpanId(),m=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));m.set("x-devinspector-request-id",o),m.set("x-devinspector-trace-id",a),m.set("x-devinspector-span-id",u);let g={...e,headers:m},v=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,g),f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-v)),y=p.status>=400||f>=c.getSlowThresholdMs();return c.addBreadcrumb({type:"http",message:`${s} ${n}`,metadata:{phase:"complete",statusCode:p.status,durationMs:f,requestId:o,traceId:a,spanId:u}}),y&&c.captureRequest({method:s,url:n,statusCode:p.status,durationMs:f,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:a,spanId:u}),p}catch(p){let f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-v));c.addBreadcrumb({type:"http_error",message:`${s} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:f,requestId:o,traceId:a,spanId:u}}),c.captureRequest({method:s,url:n,statusCode:0,durationMs:f,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:a,spanId:u});let y=p instanceof Error?p:new Error(E(p));throw c.captureError(y,{url:n,method:s,type:r.errorType||"network_error",requestId:o,traceId:a,spanId:u}),p}}0&&(module.exports={AuditCore,audit,coreAuditFetch});
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var v="https://api.devinspector.com.br/api/ingest/track",I="https://api.devinspector.com.br/api/ingest/apm";var S=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function q(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return S.some(r=>e.includes(r))}function m(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>m(s,e+1,r));let i=t,n={};for(let[s,o]of Object.entries(i)){if(q(s)){n[s]="[REDACTED]";continue}n[s]=m(o,e+1,r)}return n}finally{r.delete(t)}}function y(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=m(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function w(t){return t&&String(t).trim().toUpperCase()||void 0}function T(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function M(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function D(t){return String(t??"").trim().slice(0,200)}function _(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function f(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(t){return m(t)}var g=class{constructor(){this.apiKey="";this.endpoint=v;this.apmEndpoint=I;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||v,this.apmEndpoint=e.apmEndpoint?.trim()||I,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?m(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?m(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),s=n.origin,o=n.pathname.replace(/\/$/,""),a=r.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return s===r.origin&&o===a||s===i.origin&&o===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return f("req")}createTraceId(){return f("trace")}createSpanId(){return f("span")}captureRequest(e){let r=w(e.method)||"GET",i=String(e.url||"").trim();if(!i)return Promise.resolve();let n=T(e.statusCode)??0,s=M(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:s,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let i=M(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(n)})}captureMetric(e,r,i={},n={}){let s=D(e);if(!s)return Promise.resolve();let o;try{o=_(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...i,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},s=w(n.method),o=T(n.statusCode??n.status),a=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...a?{url:a}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(y(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,1e4),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(y(r.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i={id:f("event"),endpoint:e,payload:u(r),resolve:()=>{}};return new Promise(n=>{i.resolve=n,this.sendQueue.push(i),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return;let n=m(r),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:s?.signal};if(a&&(c.keepalive=!0),!(await i(e,c)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},A="__DEVINSPECT_AUDIT_CORE_INSTANCE__",R=typeof globalThis<"u"?globalThis:{},d=R[A]||new g;R[A]=d;async function k(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),s=w(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&d.isIngestUrl(n))return i(t,e);let o=d.createRequestId(),a=d.createTraceId(),c=d.createSpanId(),h=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));h.set("x-devinspector-request-id",o),h.set("x-devinspector-trace-id",a),h.set("x-devinspector-span-id",c);let U={...e,headers:h},E=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,U),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-E)),b=p.status>=400||l>=d.getSlowThresholdMs();return d.addBreadcrumb({type:"http",message:`${s} ${n}`,metadata:{phase:"complete",statusCode:p.status,durationMs:l,requestId:o,traceId:a,spanId:c}}),b&&d.captureRequest({method:s,url:n,statusCode:p.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:a,spanId:c}),p}catch(p){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-E));d.addBreadcrumb({type:"http_error",message:`${s} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:o,traceId:a,spanId:c}}),d.captureRequest({method:s,url:n,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:a,spanId:c});let b=p instanceof Error?p:new Error(y(p));throw d.captureError(b,{url:n,method:s,type:r.errorType||"network_error"}),p}}export{g as AuditCore,d as audit,k as coreAuditFetch};
1
+ var v="https://api.devinspector.com.br/api/ingest/track",T="https://api.devinspector.com.br/api/ingest/apm";var S=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function q(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return S.some(r=>e.includes(r))}function l(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>l(s,e+1,r));let i=t,n={};for(let[s,o]of Object.entries(i)){if(q(s)){n[s]="[REDACTED]";continue}n[s]=l(o,e+1,r)}return n}finally{r.delete(t)}}function w(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=l(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function E(t){return t&&String(t).trim().toUpperCase()||void 0}function M(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function D(t){return String(t??"").trim().slice(0,200)}function _(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function g(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function d(t){return l(t)}var b=class{constructor(){this.apiKey="";this.endpoint=v;this.apmEndpoint=T;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||v,this.apmEndpoint=e.apmEndpoint?.trim()||T,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?l(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?l(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>d(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),s=n.origin,o=n.pathname.replace(/\/$/,""),a=r.pathname.replace(/\/$/,""),u=i.pathname.replace(/\/$/,"");return s===r.origin&&o===a||s===i.origin&&o===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return g("req")}createTraceId(){return g("trace")}createSpanId(){return g("span")}captureRequest(e){let r=E(e.method)||"GET",i=String(e.url||"").trim();if(!i)return Promise.resolve();let n=M(e.statusCode)??0,s=A(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:s,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let i=A(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(n)})}captureMetric(e,r,i={},n={}){let s=D(e);if(!s)return Promise.resolve();let o;try{o=_(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...i,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},s=E(n.method),o=M(n.statusCode??n.status),a=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,u=typeof n.requestId=="string"&&n.requestId.trim()||void 0,m=typeof n.traceId=="string"&&n.traceId.trim()||void 0,h=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...a?{url:a}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...u?{requestId:u}:{},...m?{traceId:m}:{},...h?{spanId:h}:{},environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(w(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,1e4),environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(w(r.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i={id:g("event"),endpoint:e,payload:d(r),resolve:()=>{}};return new Promise(n=>{i.resolve=n,this.sendQueue.push(i),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return;let n=l(r),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:s?.signal};if(a&&(u.keepalive=!0),!(await i(e,u)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},R="__DEVINSPECT_AUDIT_CORE_INSTANCE__",U=typeof globalThis<"u"?globalThis:{},c=U[R]||new b;U[R]=c;async function k(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),s=E(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&c.isIngestUrl(n))return i(t,e);let o=c.createRequestId(),a=c.createTraceId(),u=c.createSpanId(),m=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));m.set("x-devinspector-request-id",o),m.set("x-devinspector-trace-id",a),m.set("x-devinspector-span-id",u);let h={...e,headers:m},I=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,h),f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-I)),y=p.status>=400||f>=c.getSlowThresholdMs();return c.addBreadcrumb({type:"http",message:`${s} ${n}`,metadata:{phase:"complete",statusCode:p.status,durationMs:f,requestId:o,traceId:a,spanId:u}}),y&&c.captureRequest({method:s,url:n,statusCode:p.status,durationMs:f,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:a,spanId:u}),p}catch(p){let f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-I));c.addBreadcrumb({type:"http_error",message:`${s} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:f,requestId:o,traceId:a,spanId:u}}),c.captureRequest({method:s,url:n,statusCode:0,durationMs:f,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:a,spanId:u});let y=p instanceof Error?p:new Error(w(p));throw c.captureError(y,{url:n,method:s,type:r.errorType||"network_error",requestId:o,traceId:a,spanId:u}),p}}export{b as AuditCore,c as audit,k as coreAuditFetch};
package/dist/next.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var w=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})},N=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of x(e))!C.call(t,n)&&n!==r&&w(t,n,{get:()=>e[n],enumerable:!(s=D(e,n))||s.enumerable});return t};var O=t=>N(w({},"__esModule",{value:!0}),t);var K={};P(K,{audit:()=>a,auditFetch:()=>j,captureNextError:()=>M,initNextDevInspector:()=>$,withAuditAction:()=>F,withAuditApi:()=>G});module.exports=O(K);var R="https://api.devinspector.com.br/api/ingest/track",A="https://api.devinspector.com.br/api/ingest/apm";var Q=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function B(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return Q.some(r=>e.includes(r))}function g(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>g(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(B(i)){n[i]="[REDACTED]";continue}n[i]=g(o,e+1,r)}return n}finally{r.delete(t)}}function v(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function I(t){return t&&String(t).trim().toUpperCase()||void 0}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function U(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function L(t){return String(t??"").trim().slice(0,200)}function z(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function y(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(t){return g(t)}var E=class{constructor(){this.apiKey="";this.endpoint=R;this.apmEndpoint=A;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||R,this.apmEndpoint=e.apmEndpoint?.trim()||A,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?g(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?g(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,""),u=s.pathname.replace(/\/$/,"");return i===r.origin&&o===d||i===s.origin&&o===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}captureRequest(e){let r=I(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=S(e.statusCode)??0,i=U(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=U(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(n)})}captureMetric(e,r,s={},n={}){let i=L(e);if(!i)return Promise.resolve();let o;try{o=z(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=I(n.method),o=S(n.statusCode??n.status),d=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...d?{url:d}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(v(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(v(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:y("event"),endpoint:e,payload:p(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=g(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let d=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(d&&(u.keepalive=!0),!(await s(e,u)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},q="__DEVINSPECT_AUDIT_CORE_INSTANCE__",_=typeof globalThis<"u"?globalThis:{},a=_[q]||new E;_[q]=a;async function k(t,e,r={}){let s=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!s)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),i=I(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&a.isIngestUrl(n))return s(t,e);let o=a.createRequestId(),d=a.createTraceId(),u=a.createSpanId(),m=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));m.set("x-devinspector-request-id",o),m.set("x-devinspector-trace-id",d),m.set("x-devinspector-span-id",u);let f={...e,headers:m},h=typeof performance<"u"?performance.now():Date.now();try{let c=await s(t,f),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),b=c.status>=400||l>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${i} ${n}`,metadata:{phase:"complete",statusCode:c.status,durationMs:l,requestId:o,traceId:d,spanId:u}}),b&&a.captureRequest({method:i,url:n,statusCode:c.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u}),c}catch(c){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));a.addBreadcrumb({type:"http_error",message:`${i} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:o,traceId:d,spanId:u}}),a.captureRequest({method:i,url:n,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u});let b=c instanceof Error?c:new Error(v(c));throw a.captureError(b,{url:n,method:i,type:r.errorType||"network_error"}),c}}function $(t){a.init(t)}function M(t,e={}){let r=t instanceof Error?t:new Error(String(t));a.captureError(r,{framework:"Next.js",...e})}async function j(t,e){return k(t,e,{errorType:"nextjs_network_error"})}function G(t){return async function(...e){let r=typeof performance<"u"?performance.now():Date.now(),s=e[0],n=e[1],i=s?.method||"GET",o=s?.url||s?.nextUrl?.href||"/api",d=typeof s?.headers?.get=="function"?s.headers.get("user-agent")||"":s?.headers?.["user-agent"]||"",u=T(s,"x-devinspector-request-id")||a.createRequestId(),m=T(s,"x-devinspector-trace-id")||a.createTraceId(),f=T(s,"x-devinspector-span-id")||a.createSpanId();a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"start",requestId:u,traceId:m,spanId:f}});try{let h=await t(...e),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r)),l=Number(h?.status??n?.statusCode??200)||200;return(l>=400||c>=a.getSlowThresholdMs())&&a.captureRequest({method:i,url:o,statusCode:l,durationMs:c,route:o,userAgent:d,requestId:u,traceId:m,spanId:f}),a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"complete",statusCode:l,durationMs:c,requestId:u,traceId:m,spanId:f}}),h}catch(h){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r));throw a.captureRequest({method:i,url:o,statusCode:500,durationMs:c,route:o,userAgent:d,requestId:u,traceId:m,spanId:f}),a.addBreadcrumb({type:"http_error",message:`${i} ${o}`,metadata:{framework:"Next.js",statusCode:500,durationMs:c,requestId:u,traceId:m,spanId:f}}),M(h,{url:o,method:i,type:"api_route_error",requestId:u,traceId:m,spanId:f}),h}}}function F(t,e){return(async(...r)=>{let s=typeof performance<"u"?performance.now():Date.now(),n=a.createRequestId(),i=a.createTraceId(),o=a.createSpanId();a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:n,traceId:i,spanId:o}});try{let d=await e(...r),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));return u>=a.getSlowThresholdMs()&&a.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:u,requestId:n,traceId:i,spanId:o}}),d}catch(d){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));throw a.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:u,requestId:n,traceId:i,spanId:o}}),M(d,{actionName:t,type:"server_action_error",requestId:n,traceId:i,spanId:o}),d}})}function T(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let r=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(r)?r[0]:r?String(r):void 0}0&&(module.exports={audit,auditFetch,captureNextError,initNextDevInspector,withAuditAction,withAuditApi});
1
+ "use strict";var w=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})},N=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of x(e))!C.call(t,n)&&n!==r&&w(t,n,{get:()=>e[n],enumerable:!(s=D(e,n))||s.enumerable});return t};var O=t=>N(w({},"__esModule",{value:!0}),t);var K={};P(K,{audit:()=>a,auditFetch:()=>j,captureNextError:()=>M,initNextDevInspector:()=>$,withAuditAction:()=>F,withAuditApi:()=>G});module.exports=O(K);var R="https://api.devinspector.com.br/api/ingest/track",A="https://api.devinspector.com.br/api/ingest/apm";var Q=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function B(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return Q.some(r=>e.includes(r))}function g(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>g(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(B(i)){n[i]="[REDACTED]";continue}n[i]=g(o,e+1,r)}return n}finally{r.delete(t)}}function I(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function v(t){return t&&String(t).trim().toUpperCase()||void 0}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function U(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function L(t){return String(t??"").trim().slice(0,200)}function z(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function y(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return g(t)}var E=class{constructor(){this.apiKey="";this.endpoint=R;this.apmEndpoint=A;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||R,this.apmEndpoint=e.apmEndpoint?.trim()||A,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?g(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?g(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,""),u=s.pathname.replace(/\/$/,"");return i===r.origin&&o===d||i===s.origin&&o===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}captureRequest(e){let r=v(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=S(e.statusCode)??0,i=U(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=U(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(n)})}captureMetric(e,r,s={},n={}){let i=L(e);if(!i)return Promise.resolve();let o;try{o=z(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=v(n.method),o=S(n.statusCode??n.status),d=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,u=typeof n.requestId=="string"&&n.requestId.trim()||void 0,p=typeof n.traceId=="string"&&n.traceId.trim()||void 0,f=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...d?{url:d}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},...u?{requestId:u}:{},...p?{traceId:p}:{},...f?{spanId:f}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(I(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(I(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:y("event"),endpoint:e,payload:m(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=g(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let d=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(d&&(u.keepalive=!0),!(await s(e,u)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},q="__DEVINSPECT_AUDIT_CORE_INSTANCE__",_=typeof globalThis<"u"?globalThis:{},a=_[q]||new E;_[q]=a;async function k(t,e,r={}){let s=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!s)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),i=v(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&a.isIngestUrl(n))return s(t,e);let o=a.createRequestId(),d=a.createTraceId(),u=a.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",d),p.set("x-devinspector-span-id",u);let f={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let c=await s(t,f),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),b=c.status>=400||l>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${i} ${n}`,metadata:{phase:"complete",statusCode:c.status,durationMs:l,requestId:o,traceId:d,spanId:u}}),b&&a.captureRequest({method:i,url:n,statusCode:c.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u}),c}catch(c){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));a.addBreadcrumb({type:"http_error",message:`${i} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:o,traceId:d,spanId:u}}),a.captureRequest({method:i,url:n,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u});let b=c instanceof Error?c:new Error(I(c));throw a.captureError(b,{url:n,method:i,type:r.errorType||"network_error",requestId:o,traceId:d,spanId:u}),c}}function $(t){a.init(t)}function M(t,e={}){let r=t instanceof Error?t:new Error(String(t));a.captureError(r,{...e,framework:"Next.js"})}async function j(t,e){return k(t,e,{errorType:"nextjs_network_error"})}function G(t){return async function(...e){let r=typeof performance<"u"?performance.now():Date.now(),s=e[0],n=e[1],i=s?.method||"GET",o=s?.url||s?.nextUrl?.href||"/api",d=typeof s?.headers?.get=="function"?s.headers.get("user-agent")||"":s?.headers?.["user-agent"]||"",u=T(s,"x-devinspector-request-id")||a.createRequestId(),p=T(s,"x-devinspector-trace-id")||a.createTraceId(),f=T(s,"x-devinspector-span-id")||a.createSpanId();a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"start",requestId:u,traceId:p,spanId:f}});try{let h=await t(...e),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r)),l=Number(h?.status??n?.statusCode??200)||200;return(l>=400||c>=a.getSlowThresholdMs())&&a.captureRequest({method:i,url:o,statusCode:l,durationMs:c,route:o,userAgent:d,requestId:u,traceId:p,spanId:f}),a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"complete",statusCode:l,durationMs:c,requestId:u,traceId:p,spanId:f}}),h}catch(h){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r));throw a.captureRequest({method:i,url:o,statusCode:500,durationMs:c,route:o,userAgent:d,requestId:u,traceId:p,spanId:f}),a.addBreadcrumb({type:"http_error",message:`${i} ${o}`,metadata:{framework:"Next.js",statusCode:500,durationMs:c,requestId:u,traceId:p,spanId:f}}),M(h,{url:o,method:i,type:"api_route_error",requestId:u,traceId:p,spanId:f}),h}}}function F(t,e){return(async(...r)=>{let s=typeof performance<"u"?performance.now():Date.now(),n=a.createRequestId(),i=a.createTraceId(),o=a.createSpanId();a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:n,traceId:i,spanId:o}});try{let d=await e(...r),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));return u>=a.getSlowThresholdMs()&&a.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:u,requestId:n,traceId:i,spanId:o}}),d}catch(d){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));throw a.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:u,requestId:n,traceId:i,spanId:o}}),M(d,{actionName:t,type:"server_action_error",requestId:n,traceId:i,spanId:o}),d}})}function T(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let r=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(r)?r[0]:r?String(r):void 0}0&&(module.exports={audit,auditFetch,captureNextError,initNextDevInspector,withAuditAction,withAuditApi});
package/dist/next.js CHANGED
@@ -1 +1 @@
1
- var T="https://api.devinspector.com.br/api/ingest/track",M="https://api.devinspector.com.br/api/ingest/apm";var k=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function D(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return k.some(r=>e.includes(r))}function g(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>g(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(D(i)){n[i]="[REDACTED]";continue}n[i]=g(o,e+1,r)}return n}finally{r.delete(t)}}function w(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function v(t){return t&&String(t).trim().toUpperCase()||void 0}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function x(t){return String(t??"").trim().slice(0,200)}function C(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function y(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(t){return g(t)}var I=class{constructor(){this.apiKey="";this.endpoint=T;this.apmEndpoint=M;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||T,this.apmEndpoint=e.apmEndpoint?.trim()||M,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?g(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?g(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,""),u=s.pathname.replace(/\/$/,"");return i===r.origin&&o===d||i===s.origin&&o===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}captureRequest(e){let r=v(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=R(e.statusCode)??0,i=A(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=A(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(n)})}captureMetric(e,r,s={},n={}){let i=x(e);if(!i)return Promise.resolve();let o;try{o=C(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=v(n.method),o=R(n.statusCode??n.status),d=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...d?{url:d}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(w(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(w(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:y("event"),endpoint:e,payload:p(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=g(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let d=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(d&&(u.keepalive=!0),!(await s(e,u)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},S="__DEVINSPECT_AUDIT_CORE_INSTANCE__",U=typeof globalThis<"u"?globalThis:{},a=U[S]||new I;U[S]=a;async function q(t,e,r={}){let s=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!s)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),i=v(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&a.isIngestUrl(n))return s(t,e);let o=a.createRequestId(),d=a.createTraceId(),u=a.createSpanId(),m=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));m.set("x-devinspector-request-id",o),m.set("x-devinspector-trace-id",d),m.set("x-devinspector-span-id",u);let f={...e,headers:m},h=typeof performance<"u"?performance.now():Date.now();try{let c=await s(t,f),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),b=c.status>=400||l>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${i} ${n}`,metadata:{phase:"complete",statusCode:c.status,durationMs:l,requestId:o,traceId:d,spanId:u}}),b&&a.captureRequest({method:i,url:n,statusCode:c.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u}),c}catch(c){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));a.addBreadcrumb({type:"http_error",message:`${i} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:o,traceId:d,spanId:u}}),a.captureRequest({method:i,url:n,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u});let b=c instanceof Error?c:new Error(w(c));throw a.captureError(b,{url:n,method:i,type:r.errorType||"network_error"}),c}}function O(t){a.init(t)}function _(t,e={}){let r=t instanceof Error?t:new Error(String(t));a.captureError(r,{framework:"Next.js",...e})}async function Q(t,e){return q(t,e,{errorType:"nextjs_network_error"})}function B(t){return async function(...e){let r=typeof performance<"u"?performance.now():Date.now(),s=e[0],n=e[1],i=s?.method||"GET",o=s?.url||s?.nextUrl?.href||"/api",d=typeof s?.headers?.get=="function"?s.headers.get("user-agent")||"":s?.headers?.["user-agent"]||"",u=E(s,"x-devinspector-request-id")||a.createRequestId(),m=E(s,"x-devinspector-trace-id")||a.createTraceId(),f=E(s,"x-devinspector-span-id")||a.createSpanId();a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"start",requestId:u,traceId:m,spanId:f}});try{let h=await t(...e),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r)),l=Number(h?.status??n?.statusCode??200)||200;return(l>=400||c>=a.getSlowThresholdMs())&&a.captureRequest({method:i,url:o,statusCode:l,durationMs:c,route:o,userAgent:d,requestId:u,traceId:m,spanId:f}),a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"complete",statusCode:l,durationMs:c,requestId:u,traceId:m,spanId:f}}),h}catch(h){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r));throw a.captureRequest({method:i,url:o,statusCode:500,durationMs:c,route:o,userAgent:d,requestId:u,traceId:m,spanId:f}),a.addBreadcrumb({type:"http_error",message:`${i} ${o}`,metadata:{framework:"Next.js",statusCode:500,durationMs:c,requestId:u,traceId:m,spanId:f}}),_(h,{url:o,method:i,type:"api_route_error",requestId:u,traceId:m,spanId:f}),h}}}function L(t,e){return(async(...r)=>{let s=typeof performance<"u"?performance.now():Date.now(),n=a.createRequestId(),i=a.createTraceId(),o=a.createSpanId();a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:n,traceId:i,spanId:o}});try{let d=await e(...r),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));return u>=a.getSlowThresholdMs()&&a.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:u,requestId:n,traceId:i,spanId:o}}),d}catch(d){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));throw a.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:u,requestId:n,traceId:i,spanId:o}}),_(d,{actionName:t,type:"server_action_error",requestId:n,traceId:i,spanId:o}),d}})}function E(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let r=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(r)?r[0]:r?String(r):void 0}export{a as audit,Q as auditFetch,_ as captureNextError,O as initNextDevInspector,L as withAuditAction,B as withAuditApi};
1
+ var T="https://api.devinspector.com.br/api/ingest/track",M="https://api.devinspector.com.br/api/ingest/apm";var k=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function D(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return k.some(r=>e.includes(r))}function g(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(i=>g(i,e+1,r));let s=t,n={};for(let[i,o]of Object.entries(s)){if(D(i)){n[i]="[REDACTED]";continue}n[i]=g(o,e+1,r)}return n}finally{r.delete(t)}}function w(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function I(t){return t&&String(t).trim().toUpperCase()||void 0}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function x(t){return String(t??"").trim().slice(0,200)}function C(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function y(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return g(t)}var v=class{constructor(){this.apiKey="";this.endpoint=T;this.apmEndpoint=M;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||T,this.apmEndpoint=e.apmEndpoint?.trim()||M,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?g(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?g(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),s=new URL(this.apmEndpoint),n=new URL(e,r.origin),i=n.origin,o=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,""),u=s.pathname.replace(/\/$/,"");return i===r.origin&&o===d||i===s.origin&&o===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}captureRequest(e){let r=I(e.method)||"GET",s=String(e.url||"").trim();if(!s)return Promise.resolve();let n=R(e.statusCode)??0,i=A(e.durationMs)??0,o={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:r,url:s,statusCode:n,durationMs:i,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(o)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let s=A(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:s,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:s,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(n)})}captureMetric(e,r,s={},n={}){let i=x(e);if(!i)return Promise.resolve();let o;try{o=C(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:i,metricValue:o,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...s,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let s=e?.message?.trim()||"Erro desconhecido",n={...r},i=I(n.method),o=R(n.statusCode??n.status),d=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,u=typeof n.requestId=="string"&&n.requestId.trim()||void 0,p=typeof n.traceId=="string"&&n.traceId.trim()||void 0,f=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.requestId,delete n.traceId,delete n.spanId,delete n.durationMs,this.sendError({type:"error",message:s,stackTrace:e?.stack||"",...d?{url:d}:{},...i?{method:i}:{},...o!==void 0?{statusCode:o}:{},...u?{requestId:u}:{},...p?{traceId:p}:{},...f?{spanId:f}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let s=e instanceof Error?e:new Error(w(e));return this.captureError(s,r)}captureMessage(e,r={}){let s=String(e||"").trim();return s?this.sendApm({type:"message",message:s.slice(0,1e4),environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((s,n)=>{this.captureError(s,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(s,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let s=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(s,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let s=r.reason instanceof Error?r.reason:new Error(w(r.reason));this.captureError(s,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let s={id:y("event"),endpoint:e,payload:m(r),resolve:()=>{}};return new Promise(n=>{s.resolve=n,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let r of e)r()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,r){let s=typeof fetch=="function"?fetch:void 0;if(!s)return;let n=g(r),i,o;try{typeof AbortController<"u"&&(i=new AbortController,o=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let d=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:i?.signal};if(d&&(u.keepalive=!0),!(await s(e,u)).ok)return}catch{return}finally{o!==void 0&&clearTimeout(o)}}},S="__DEVINSPECT_AUDIT_CORE_INSTANCE__",U=typeof globalThis<"u"?globalThis:{},a=U[S]||new v;U[S]=a;async function q(t,e,r={}){let s=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!s)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),i=I(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&a.isIngestUrl(n))return s(t,e);let o=a.createRequestId(),d=a.createTraceId(),u=a.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",d),p.set("x-devinspector-span-id",u);let f={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let c=await s(t,f),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),b=c.status>=400||l>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${i} ${n}`,metadata:{phase:"complete",statusCode:c.status,durationMs:l,requestId:o,traceId:d,spanId:u}}),b&&a.captureRequest({method:i,url:n,statusCode:c.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u}),c}catch(c){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));a.addBreadcrumb({type:"http_error",message:`${i} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:o,traceId:d,spanId:u}}),a.captureRequest({method:i,url:n,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:o,traceId:d,spanId:u});let b=c instanceof Error?c:new Error(w(c));throw a.captureError(b,{url:n,method:i,type:r.errorType||"network_error",requestId:o,traceId:d,spanId:u}),c}}function O(t){a.init(t)}function _(t,e={}){let r=t instanceof Error?t:new Error(String(t));a.captureError(r,{...e,framework:"Next.js"})}async function Q(t,e){return q(t,e,{errorType:"nextjs_network_error"})}function B(t){return async function(...e){let r=typeof performance<"u"?performance.now():Date.now(),s=e[0],n=e[1],i=s?.method||"GET",o=s?.url||s?.nextUrl?.href||"/api",d=typeof s?.headers?.get=="function"?s.headers.get("user-agent")||"":s?.headers?.["user-agent"]||"",u=E(s,"x-devinspector-request-id")||a.createRequestId(),p=E(s,"x-devinspector-trace-id")||a.createTraceId(),f=E(s,"x-devinspector-span-id")||a.createSpanId();a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"start",requestId:u,traceId:p,spanId:f}});try{let h=await t(...e),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r)),l=Number(h?.status??n?.statusCode??200)||200;return(l>=400||c>=a.getSlowThresholdMs())&&a.captureRequest({method:i,url:o,statusCode:l,durationMs:c,route:o,userAgent:d,requestId:u,traceId:p,spanId:f}),a.addBreadcrumb({type:"http",message:`${i} ${o}`,metadata:{framework:"Next.js",phase:"complete",statusCode:l,durationMs:c,requestId:u,traceId:p,spanId:f}}),h}catch(h){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-r));throw a.captureRequest({method:i,url:o,statusCode:500,durationMs:c,route:o,userAgent:d,requestId:u,traceId:p,spanId:f}),a.addBreadcrumb({type:"http_error",message:`${i} ${o}`,metadata:{framework:"Next.js",statusCode:500,durationMs:c,requestId:u,traceId:p,spanId:f}}),_(h,{url:o,method:i,type:"api_route_error",requestId:u,traceId:p,spanId:f}),h}}}function L(t,e){return(async(...r)=>{let s=typeof performance<"u"?performance.now():Date.now(),n=a.createRequestId(),i=a.createTraceId(),o=a.createSpanId();a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:n,traceId:i,spanId:o}});try{let d=await e(...r),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));return u>=a.getSlowThresholdMs()&&a.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:u,requestId:n,traceId:i,spanId:o}}),d}catch(d){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-s));throw a.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:u,route:t,requestId:n,traceId:i,spanId:o}),a.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:u,requestId:n,traceId:i,spanId:o}}),_(d,{actionName:t,type:"server_action_error",requestId:n,traceId:i,spanId:o}),d}})}function E(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let r=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(r)?r[0]:r?String(r):void 0}export{a as audit,Q as auditFetch,_ as captureNextError,O as initNextDevInspector,L as withAuditAction,B as withAuditApi};
package/dist/node.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var I=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var L=(t,e)=>{for(var n in e)I(t,n,{get:e[n],enumerable:!0})},z=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of O(e))!B.call(t,s)&&s!==n&&I(t,s,{get:()=>e[s],enumerable:!(r=N(e,s))||r.enumerable});return t};var $=t=>z(I({},"__esModule",{value:!0}),t);var Z={};L(Z,{audit:()=>a,auditFetch:()=>J,auditOperation:()=>W,devInspector:()=>V,devInspectorErrorHandler:()=>Y});module.exports=$(Z);var k=require("async_hooks");var M="https://api.devinspector.com.br/api/ingest/track",R="https://api.devinspector.com.br/api/ingest/apm";var G=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function F(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return G.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let r=t,s={};for(let[o,i]of Object.entries(r)){if(F(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,n)}return s}finally{n.delete(t)}}function v(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=y(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function E(t){return t&&String(t).trim().toUpperCase()||void 0}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function U(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function j(t){return String(t??"").trim().slice(0,200)}function H(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function w(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(t){return y(t)}var T=class{constructor(){this.apiKey="";this.endpoint=M;this.apmEndpoint=R;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||M,this.apmEndpoint=e.apmEndpoint?.trim()||R,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),r=new URL(this.apmEndpoint),s=new URL(e,n.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===n.origin&&i===u||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return w("req")}createTraceId(){return w("trace")}createSpanId(){return w("span")}captureRequest(e){let n=E(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let s=S(e.statusCode)??0,o=U(e.durationMs)??0,i={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:n,url:r,statusCode:s,durationMs:o,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(i)})}captureDbQuery(e){let n=String(e.operation||"").trim();if(!n)return Promise.resolve();let r=U(e.durationMs)??0,s={...e.metadata||{},operation:n,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(s)})}captureMetric(e,n,r={},s={}){let o=j(e);if(!o)return Promise.resolve();let i;try{i=H(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:s.requestId,traceId:s.traceId,spanId:s.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,n={}){let r=e?.message?.trim()||"Erro desconhecido",s={...n},o=E(s.method),i=S(s.statusCode??s.status),u=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.requestId,delete s.traceId,delete s.spanId,delete s.durationMs,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...u?{url:u}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...s,timestamp:new Date().toISOString()})})}captureException(e,n={}){let r=e instanceof Error?e:new Error(v(e));return this.captureError(r,n)}captureMessage(e,n={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,s)=>{this.captureError(r,{platform:"react-native",fatal:s}).finally(()=>{typeof n=="function"&&n(r,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let r=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(r,{url:n.filename||window.location.href,line:n.lineno,column:n.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",n=>{let r=n.reason instanceof Error?n.reason:new Error(v(n.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:w("event"),endpoint:e,payload:p(n),resolve:()=>{}};return new Promise(s=>{r.resolve=s,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let n of e)n()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,n){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let s=y(n),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let u=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(s),signal:o?.signal};if(u&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},A="__DEVINSPECT_AUDIT_CORE_INSTANCE__",q=typeof globalThis<"u"?globalThis:{},a=q[A]||new T;q[A]=a;async function D(t,e,n={}){let r=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let s=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=E(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&a.isIngestUrl(s))return r(t,e);let i=a.createRequestId(),u=a.createTraceId(),d=a.createSpanId(),m=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));m.set("x-devinspector-request-id",i),m.set("x-devinspector-trace-id",u),m.set("x-devinspector-span-id",d);let h={...e,headers:m},f=typeof performance<"u"?performance.now():Date.now();try{let c=await r(t,h),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),g=c.status>=400||l>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:c.status,durationMs:l,requestId:i,traceId:u,spanId:d}}),g&&a.captureRequest({method:o,url:s,statusCode:c.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d}),c}catch(c){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));a.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:i,traceId:u,spanId:d}}),a.captureRequest({method:o,url:s,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d});let g=c instanceof Error?c:new Error(v(c));throw a.captureError(g,{url:s,method:o,type:n.errorType||"network_error"}),c}}var _=new k.AsyncLocalStorage;function K(t){if(!t)return{};let e={},n=["authorization","cookie","set-cookie","x-api-key","proxy-authorization"];for(let[r,s]of Object.entries(t)){let o=r.toLowerCase();e[r]=n.includes(o)?"[REDACTED]":s}return e}function b(t,e){if(!t?.headers)return;let n=e.toLowerCase(),r=t.headers,s=r[n]??r[e];if(Array.isArray(s))return s[0];if(s!=null)return String(s);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===n)return Array.isArray(i)?i[0]:i?String(i):void 0}function X(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function V(t){a.init(t);let e=t.slowThresholdMs??a.getSlowThresholdMs(),n=t.ignorePaths??["/uploads","/favicon.ico"];return(r,s,o)=>{let i=r.originalUrl||r.url||"";if(i&&a.isIngestUrl(i)||n.some(l=>X(i,l)))return o();let d=typeof performance<"u"?performance.now():Date.now(),m=b(r,"x-devinspector-request-id")||a.createRequestId(),h=b(r,"x-devinspector-trace-id")||a.createTraceId(),f=b(r,"x-devinspector-span-id")||a.createSpanId();r.headers&&(r.headers["x-devinspector-request-id"]=m,r.headers["x-devinspector-trace-id"]=h,r.headers["x-devinspector-span-id"]=f);let c={req:r,queriesCount:0,slowQueries:0,requestId:m,traceId:h,spanId:f};_.run(c,()=>{a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:m,traceId:h,spanId:f}}),s.on("finish",()=>{let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-d)),g=Number(s.statusCode)||500,Q=g>=400,C=l>=e,x=c.slowQueries>0,P=r.route?.path?`${r.baseUrl||""}${r.route.path}`:r.baseUrl||i;(Q||C||x)&&a.captureRequest({method:r.method||"GET",url:i,statusCode:g,durationMs:l,userAgent:r.headers?.["user-agent"],route:P,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries,requestId:m,traceId:h,spanId:f}),a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:g,durationMs:l,requestId:m,traceId:h,spanId:f,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries}})}),o()})}}async function J(t,e){return D(t,e,{errorType:"node_network_error"})}async function W(t,e,n){let r=_.getStore(),s=n??a.getSlowThresholdMs(),o=typeof performance<"u"?performance.now():Date.now();r&&r.queriesCount++;try{let i=await e(),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o));if(u>=s){r&&(r.slowQueries=Math.max(r.slowQueries,u));let d=r?.req?.originalUrl||r?.req?.url||"";a.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:d}}),a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t}})}return i}catch(i){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o)),d=r?.req?.originalUrl||r?.req?.url||"";throw a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,error:i instanceof Error?i.message:String(i)}}),a.captureException(i instanceof Error?i:new Error(String(i)),{operationName:t,durationMs:u,url:d,method:"DB",requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),a.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}}),i}}function Y(){return(t,e,n,r)=>{let s=b(e,"x-devinspector-request-id"),o=b(e,"x-devinspector-trace-id"),i=b(e,"x-devinspector-span-id");a.captureException(t instanceof Error?t:new Error(String(t)),{url:e.originalUrl||e.url,method:e.method,statusCode:n?.statusCode||500,headers:K(e.headers||{}),requestId:s,traceId:o,spanId:i}),a.addBreadcrumb({type:"http_error",message:`${e.method||"HTTP"} ${e.originalUrl||e.url||""}`,metadata:{framework:"Node.js",statusCode:n?.statusCode||500,requestId:s,traceId:o,spanId:i}}),r(t)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
1
+ "use strict";var w=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var L=(t,e)=>{for(var n in e)w(t,n,{get:e[n],enumerable:!0})},z=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of O(e))!B.call(t,s)&&s!==n&&w(t,s,{get:()=>e[s],enumerable:!(r=N(e,s))||r.enumerable});return t};var $=t=>z(w({},"__esModule",{value:!0}),t);var Z={};L(Z,{audit:()=>a,auditFetch:()=>J,auditOperation:()=>W,devInspector:()=>V,devInspectorErrorHandler:()=>Y});module.exports=$(Z);var k=require("async_hooks");var M="https://api.devinspector.com.br/api/ingest/track",R="https://api.devinspector.com.br/api/ingest/apm";var G=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function F(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return G.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let r=t,s={};for(let[o,i]of Object.entries(r)){if(F(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,n)}return s}finally{n.delete(t)}}function v(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=y(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function E(t){return t&&String(t).trim().toUpperCase()||void 0}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function U(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function j(t){return String(t??"").trim().slice(0,200)}function H(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function l(t){return y(t)}var T=class{constructor(){this.apiKey="";this.endpoint=M;this.apmEndpoint=R;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||M,this.apmEndpoint=e.apmEndpoint?.trim()||R,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),r=new URL(this.apmEndpoint),s=new URL(e,n.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===n.origin&&i===u||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}captureRequest(e){let n=E(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let s=S(e.statusCode)??0,o=U(e.durationMs)??0,i={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:n,url:r,statusCode:s,durationMs:o,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(i)})}captureDbQuery(e){let n=String(e.operation||"").trim();if(!n)return Promise.resolve();let r=U(e.durationMs)??0,s={...e.metadata||{},operation:n,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(s)})}captureMetric(e,n,r={},s={}){let o=j(e);if(!o)return Promise.resolve();let i;try{i=H(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:s.requestId,traceId:s.traceId,spanId:s.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,n={}){let r=e?.message?.trim()||"Erro desconhecido",s={...n},o=E(s.method),i=S(s.statusCode??s.status),u=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0,d=typeof s.requestId=="string"&&s.requestId.trim()||void 0,p=typeof s.traceId=="string"&&s.traceId.trim()||void 0,f=typeof s.spanId=="string"&&s.spanId.trim()||void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.requestId,delete s.traceId,delete s.spanId,delete s.durationMs,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...u?{url:u}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...d?{requestId:d}:{},...p?{traceId:p}:{},...f?{spanId:f}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...s,timestamp:new Date().toISOString()})})}captureException(e,n={}){let r=e instanceof Error?e:new Error(v(e));return this.captureError(r,n)}captureMessage(e,n={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,s)=>{this.captureError(r,{platform:"react-native",fatal:s}).finally(()=>{typeof n=="function"&&n(r,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let r=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(r,{url:n.filename||window.location.href,line:n.lineno,column:n.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",n=>{let r=n.reason instanceof Error?n.reason:new Error(v(n.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:b("event"),endpoint:e,payload:l(n),resolve:()=>{}};return new Promise(s=>{r.resolve=s,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let n of e)n()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,n){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let s=y(n),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let u=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(s),signal:o?.signal};if(u&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},A="__DEVINSPECT_AUDIT_CORE_INSTANCE__",q=typeof globalThis<"u"?globalThis:{},a=q[A]||new T;q[A]=a;async function D(t,e,n={}){let r=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let s=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=E(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&a.isIngestUrl(s))return r(t,e);let i=a.createRequestId(),u=a.createTraceId(),d=a.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",i),p.set("x-devinspector-trace-id",u),p.set("x-devinspector-span-id",d);let f={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let c=await r(t,f),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=c.status>=400||m>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:c.status,durationMs:m,requestId:i,traceId:u,spanId:d}}),g&&a.captureRequest({method:o,url:s,statusCode:c.status,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d}),c}catch(c){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));a.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:i,traceId:u,spanId:d}}),a.captureRequest({method:o,url:s,statusCode:0,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d});let g=c instanceof Error?c:new Error(v(c));throw a.captureError(g,{url:s,method:o,type:n.errorType||"network_error",requestId:i,traceId:u,spanId:d}),c}}var _=new k.AsyncLocalStorage;function K(t){if(!t)return{};let e={},n=["authorization","cookie","set-cookie","x-api-key","proxy-authorization"];for(let[r,s]of Object.entries(t)){let o=r.toLowerCase();e[r]=n.includes(o)?"[REDACTED]":s}return e}function I(t,e){if(!t?.headers)return;let n=e.toLowerCase(),r=t.headers,s=r[n]??r[e];if(Array.isArray(s))return s[0];if(s!=null)return String(s);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===n)return Array.isArray(i)?i[0]:i?String(i):void 0}function X(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function V(t){a.init(t);let e=t.slowThresholdMs??a.getSlowThresholdMs(),n=t.ignorePaths??["/uploads","/favicon.ico"];return(r,s,o)=>{let i=r.originalUrl||r.url||"";if(i&&a.isIngestUrl(i)||n.some(m=>X(i,m)))return o();let d=typeof performance<"u"?performance.now():Date.now(),p=I(r,"x-devinspector-request-id")||a.createRequestId(),f=I(r,"x-devinspector-trace-id")||a.createTraceId(),h=I(r,"x-devinspector-span-id")||a.createSpanId();r.headers&&(r.headers["x-devinspector-request-id"]=p,r.headers["x-devinspector-trace-id"]=f,r.headers["x-devinspector-span-id"]=h);let c={req:r,queriesCount:0,slowQueries:0,requestId:p,traceId:f,spanId:h};_.run(c,()=>{a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:f,spanId:h}}),s.on("finish",()=>{let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-d)),g=Number(s.statusCode)||500,Q=g>=400,C=m>=e,x=c.slowQueries>0,P=r.route?.path?`${r.baseUrl||""}${r.route.path}`:r.baseUrl||i;(Q||C||x)&&a.captureRequest({method:r.method||"GET",url:i,statusCode:g,durationMs:m,userAgent:r.headers?.["user-agent"],route:P,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries,requestId:p,traceId:f,spanId:h}),a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:g,durationMs:m,requestId:p,traceId:f,spanId:h,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries}})}),o()})}}async function J(t,e){return D(t,e,{errorType:"node_network_error"})}async function W(t,e,n){let r=_.getStore(),s=n??a.getSlowThresholdMs(),o=typeof performance<"u"?performance.now():Date.now();r&&r.queriesCount++;try{let i=await e(),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o));if(u>=s){r&&(r.slowQueries=Math.max(r.slowQueries,u));let d=r?.req?.originalUrl||r?.req?.url||"";a.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:d}}),a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t}})}return i}catch(i){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o)),d=r?.req?.originalUrl||r?.req?.url||"";throw a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,error:i instanceof Error?i.message:String(i)}}),a.captureException(i instanceof Error?i:new Error(String(i)),{operationName:t,durationMs:u,url:d,method:"DB",requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),a.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}}),i}}function Y(){return(t,e,n,r)=>{let s=I(e,"x-devinspector-request-id"),o=I(e,"x-devinspector-trace-id"),i=I(e,"x-devinspector-span-id");a.captureException(t instanceof Error?t:new Error(String(t)),{url:e.originalUrl||e.url,method:e.method,statusCode:n?.statusCode||500,headers:K(e.headers||{}),requestId:s,traceId:o,spanId:i}),a.addBreadcrumb({type:"http_error",message:`${e.method||"HTTP"} ${e.originalUrl||e.url||""}`,metadata:{framework:"Node.js",statusCode:n?.statusCode||500,requestId:s,traceId:o,spanId:i}}),r(t)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
package/dist/node.js CHANGED
@@ -1 +1 @@
1
- import{AsyncLocalStorage as B}from"async_hooks";var T="https://api.devinspector.com.br/api/ingest/track",M="https://api.devinspector.com.br/api/ingest/apm";var x=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function P(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return x.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let r=t,s={};for(let[o,i]of Object.entries(r)){if(P(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,n)}return s}finally{n.delete(t)}}function I(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=y(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function v(t){return t&&String(t).trim().toUpperCase()||void 0}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function N(t){return String(t??"").trim().slice(0,200)}function O(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function w(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(t){return y(t)}var E=class{constructor(){this.apiKey="";this.endpoint=T;this.apmEndpoint=M;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||T,this.apmEndpoint=e.apmEndpoint?.trim()||M,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),r=new URL(this.apmEndpoint),s=new URL(e,n.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===n.origin&&i===u||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return w("req")}createTraceId(){return w("trace")}createSpanId(){return w("span")}captureRequest(e){let n=v(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let s=R(e.statusCode)??0,o=S(e.durationMs)??0,i={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:n,url:r,statusCode:s,durationMs:o,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(i)})}captureDbQuery(e){let n=String(e.operation||"").trim();if(!n)return Promise.resolve();let r=S(e.durationMs)??0,s={...e.metadata||{},operation:n,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(s)})}captureMetric(e,n,r={},s={}){let o=N(e);if(!o)return Promise.resolve();let i;try{i=O(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:s.requestId,traceId:s.traceId,spanId:s.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,n={}){let r=e?.message?.trim()||"Erro desconhecido",s={...n},o=v(s.method),i=R(s.statusCode??s.status),u=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.requestId,delete s.traceId,delete s.spanId,delete s.durationMs,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...u?{url:u}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...s,timestamp:new Date().toISOString()})})}captureException(e,n={}){let r=e instanceof Error?e:new Error(I(e));return this.captureError(r,n)}captureMessage(e,n={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,s)=>{this.captureError(r,{platform:"react-native",fatal:s}).finally(()=>{typeof n=="function"&&n(r,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let r=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(r,{url:n.filename||window.location.href,line:n.lineno,column:n.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",n=>{let r=n.reason instanceof Error?n.reason:new Error(I(n.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:w("event"),endpoint:e,payload:p(n),resolve:()=>{}};return new Promise(s=>{r.resolve=s,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let n of e)n()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,n){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let s=y(n),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let u=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(s),signal:o?.signal};if(u&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},U="__DEVINSPECT_AUDIT_CORE_INSTANCE__",A=typeof globalThis<"u"?globalThis:{},a=A[U]||new E;A[U]=a;async function q(t,e,n={}){let r=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let s=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=v(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&a.isIngestUrl(s))return r(t,e);let i=a.createRequestId(),u=a.createTraceId(),d=a.createSpanId(),m=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));m.set("x-devinspector-request-id",i),m.set("x-devinspector-trace-id",u),m.set("x-devinspector-span-id",d);let h={...e,headers:m},f=typeof performance<"u"?performance.now():Date.now();try{let c=await r(t,h),l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),g=c.status>=400||l>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:c.status,durationMs:l,requestId:i,traceId:u,spanId:d}}),g&&a.captureRequest({method:o,url:s,statusCode:c.status,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d}),c}catch(c){let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));a.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:l,requestId:i,traceId:u,spanId:d}}),a.captureRequest({method:o,url:s,statusCode:0,durationMs:l,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d});let g=c instanceof Error?c:new Error(I(c));throw a.captureError(g,{url:s,method:o,type:n.errorType||"network_error"}),c}}var D=new B;function L(t){if(!t)return{};let e={},n=["authorization","cookie","set-cookie","x-api-key","proxy-authorization"];for(let[r,s]of Object.entries(t)){let o=r.toLowerCase();e[r]=n.includes(o)?"[REDACTED]":s}return e}function b(t,e){if(!t?.headers)return;let n=e.toLowerCase(),r=t.headers,s=r[n]??r[e];if(Array.isArray(s))return s[0];if(s!=null)return String(s);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===n)return Array.isArray(i)?i[0]:i?String(i):void 0}function z(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function j(t){a.init(t);let e=t.slowThresholdMs??a.getSlowThresholdMs(),n=t.ignorePaths??["/uploads","/favicon.ico"];return(r,s,o)=>{let i=r.originalUrl||r.url||"";if(i&&a.isIngestUrl(i)||n.some(l=>z(i,l)))return o();let d=typeof performance<"u"?performance.now():Date.now(),m=b(r,"x-devinspector-request-id")||a.createRequestId(),h=b(r,"x-devinspector-trace-id")||a.createTraceId(),f=b(r,"x-devinspector-span-id")||a.createSpanId();r.headers&&(r.headers["x-devinspector-request-id"]=m,r.headers["x-devinspector-trace-id"]=h,r.headers["x-devinspector-span-id"]=f);let c={req:r,queriesCount:0,slowQueries:0,requestId:m,traceId:h,spanId:f};D.run(c,()=>{a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:m,traceId:h,spanId:f}}),s.on("finish",()=>{let l=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-d)),g=Number(s.statusCode)||500,k=g>=400,_=l>=e,Q=c.slowQueries>0,C=r.route?.path?`${r.baseUrl||""}${r.route.path}`:r.baseUrl||i;(k||_||Q)&&a.captureRequest({method:r.method||"GET",url:i,statusCode:g,durationMs:l,userAgent:r.headers?.["user-agent"],route:C,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries,requestId:m,traceId:h,spanId:f}),a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:g,durationMs:l,requestId:m,traceId:h,spanId:f,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries}})}),o()})}}async function H(t,e){return q(t,e,{errorType:"node_network_error"})}async function K(t,e,n){let r=D.getStore(),s=n??a.getSlowThresholdMs(),o=typeof performance<"u"?performance.now():Date.now();r&&r.queriesCount++;try{let i=await e(),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o));if(u>=s){r&&(r.slowQueries=Math.max(r.slowQueries,u));let d=r?.req?.originalUrl||r?.req?.url||"";a.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:d}}),a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t}})}return i}catch(i){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o)),d=r?.req?.originalUrl||r?.req?.url||"";throw a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,error:i instanceof Error?i.message:String(i)}}),a.captureException(i instanceof Error?i:new Error(String(i)),{operationName:t,durationMs:u,url:d,method:"DB",requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),a.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}}),i}}function X(){return(t,e,n,r)=>{let s=b(e,"x-devinspector-request-id"),o=b(e,"x-devinspector-trace-id"),i=b(e,"x-devinspector-span-id");a.captureException(t instanceof Error?t:new Error(String(t)),{url:e.originalUrl||e.url,method:e.method,statusCode:n?.statusCode||500,headers:L(e.headers||{}),requestId:s,traceId:o,spanId:i}),a.addBreadcrumb({type:"http_error",message:`${e.method||"HTTP"} ${e.originalUrl||e.url||""}`,metadata:{framework:"Node.js",statusCode:n?.statusCode||500,requestId:s,traceId:o,spanId:i}}),r(t)}}export{a as audit,H as auditFetch,K as auditOperation,j as devInspector,X as devInspectorErrorHandler};
1
+ import{AsyncLocalStorage as B}from"async_hooks";var T="https://api.devinspector.com.br/api/ingest/track",M="https://api.devinspector.com.br/api/ingest/apm";var x=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function P(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return x.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let r=t,s={};for(let[o,i]of Object.entries(r)){if(P(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,n)}return s}finally{n.delete(t)}}function w(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=y(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function v(t){return t&&String(t).trim().toUpperCase()||void 0}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function N(t){return String(t??"").trim().slice(0,200)}function O(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function l(t){return y(t)}var E=class{constructor(){this.apiKey="";this.endpoint=T;this.apmEndpoint=M;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||T,this.apmEndpoint=e.apmEndpoint?.trim()||M,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),r=new URL(this.apmEndpoint),s=new URL(e,n.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===n.origin&&i===u||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}captureRequest(e){let n=v(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let s=R(e.statusCode)??0,o=S(e.durationMs)??0,i={...e.metadata||{},...e.route!==void 0?{route:e.route}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:n,url:r,statusCode:s,durationMs:o,browser:e.userAgent,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(i)})}captureDbQuery(e){let n=String(e.operation||"").trim();if(!n)return Promise.resolve();let r=S(e.durationMs)??0,s={...e.metadata||{},operation:n,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(s)})}captureMetric(e,n,r={},s={}){let o=N(e);if(!o)return Promise.resolve();let i;try{i=O(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:s.requestId,traceId:s.traceId,spanId:s.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,n={}){let r=e?.message?.trim()||"Erro desconhecido",s={...n},o=v(s.method),i=R(s.statusCode??s.status),u=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0,d=typeof s.requestId=="string"&&s.requestId.trim()||void 0,p=typeof s.traceId=="string"&&s.traceId.trim()||void 0,f=typeof s.spanId=="string"&&s.spanId.trim()||void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.requestId,delete s.traceId,delete s.spanId,delete s.durationMs,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...u?{url:u}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...d?{requestId:d}:{},...p?{traceId:p}:{},...f?{spanId:f}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...s,timestamp:new Date().toISOString()})})}captureException(e,n={}){let r=e instanceof Error?e:new Error(w(e));return this.captureError(r,n)}captureMessage(e,n={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,s)=>{this.captureError(r,{platform:"react-native",fatal:s}).finally(()=>{typeof n=="function"&&n(r,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let r=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(r,{url:n.filename||window.location.href,line:n.lineno,column:n.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",n=>{let r=n.reason instanceof Error?n.reason:new Error(w(n.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:b("event"),endpoint:e,payload:l(n),resolve:()=>{}};return new Promise(s=>{r.resolve=s,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let n of e)n()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,n){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let s=y(n),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let u=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(s),signal:o?.signal};if(u&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},U="__DEVINSPECT_AUDIT_CORE_INSTANCE__",A=typeof globalThis<"u"?globalThis:{},a=A[U]||new E;A[U]=a;async function q(t,e,n={}){let r=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let s=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=v(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&a.isIngestUrl(s))return r(t,e);let i=a.createRequestId(),u=a.createTraceId(),d=a.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",i),p.set("x-devinspector-trace-id",u),p.set("x-devinspector-span-id",d);let f={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let c=await r(t,f),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=c.status>=400||m>=a.getSlowThresholdMs();return a.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:c.status,durationMs:m,requestId:i,traceId:u,spanId:d}}),g&&a.captureRequest({method:o,url:s,statusCode:c.status,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d}),c}catch(c){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));a.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:i,traceId:u,spanId:d}}),a.captureRequest({method:o,url:s,statusCode:0,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:i,traceId:u,spanId:d});let g=c instanceof Error?c:new Error(w(c));throw a.captureError(g,{url:s,method:o,type:n.errorType||"network_error",requestId:i,traceId:u,spanId:d}),c}}var D=new B;function L(t){if(!t)return{};let e={},n=["authorization","cookie","set-cookie","x-api-key","proxy-authorization"];for(let[r,s]of Object.entries(t)){let o=r.toLowerCase();e[r]=n.includes(o)?"[REDACTED]":s}return e}function I(t,e){if(!t?.headers)return;let n=e.toLowerCase(),r=t.headers,s=r[n]??r[e];if(Array.isArray(s))return s[0];if(s!=null)return String(s);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===n)return Array.isArray(i)?i[0]:i?String(i):void 0}function z(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function j(t){a.init(t);let e=t.slowThresholdMs??a.getSlowThresholdMs(),n=t.ignorePaths??["/uploads","/favicon.ico"];return(r,s,o)=>{let i=r.originalUrl||r.url||"";if(i&&a.isIngestUrl(i)||n.some(m=>z(i,m)))return o();let d=typeof performance<"u"?performance.now():Date.now(),p=I(r,"x-devinspector-request-id")||a.createRequestId(),f=I(r,"x-devinspector-trace-id")||a.createTraceId(),h=I(r,"x-devinspector-span-id")||a.createSpanId();r.headers&&(r.headers["x-devinspector-request-id"]=p,r.headers["x-devinspector-trace-id"]=f,r.headers["x-devinspector-span-id"]=h);let c={req:r,queriesCount:0,slowQueries:0,requestId:p,traceId:f,spanId:h};D.run(c,()=>{a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:f,spanId:h}}),s.on("finish",()=>{let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-d)),g=Number(s.statusCode)||500,k=g>=400,_=m>=e,Q=c.slowQueries>0,C=r.route?.path?`${r.baseUrl||""}${r.route.path}`:r.baseUrl||i;(k||_||Q)&&a.captureRequest({method:r.method||"GET",url:i,statusCode:g,durationMs:m,userAgent:r.headers?.["user-agent"],route:C,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries,requestId:p,traceId:f,spanId:h}),a.addBreadcrumb({type:"http",message:`${r.method} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:g,durationMs:m,requestId:p,traceId:f,spanId:h,dbQueriesCount:c.queriesCount,slowQueryMs:c.slowQueries}})}),o()})}}async function H(t,e){return q(t,e,{errorType:"node_network_error"})}async function K(t,e,n){let r=D.getStore(),s=n??a.getSlowThresholdMs(),o=typeof performance<"u"?performance.now():Date.now();r&&r.queriesCount++;try{let i=await e(),u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o));if(u>=s){r&&(r.slowQueries=Math.max(r.slowQueries,u));let d=r?.req?.originalUrl||r?.req?.url||"";a.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:d}}),a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t}})}return i}catch(i){let u=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-o)),d=r?.req?.originalUrl||r?.req?.url||"";throw a.captureDbQuery({operation:t,collection:"Unknown",durationMs:u,url:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,error:i instanceof Error?i.message:String(i)}}),a.captureException(i instanceof Error?i:new Error(String(i)),{operationName:t,durationMs:u,url:d,method:"DB",requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),a.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:u,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}}),i}}function X(){return(t,e,n,r)=>{let s=I(e,"x-devinspector-request-id"),o=I(e,"x-devinspector-trace-id"),i=I(e,"x-devinspector-span-id");a.captureException(t instanceof Error?t:new Error(String(t)),{url:e.originalUrl||e.url,method:e.method,statusCode:n?.statusCode||500,headers:L(e.headers||{}),requestId:s,traceId:o,spanId:i}),a.addBreadcrumb({type:"http_error",message:`${e.method||"HTTP"} ${e.originalUrl||e.url||""}`,metadata:{framework:"Node.js",statusCode:n?.statusCode||500,requestId:s,traceId:o,spanId:i}}),r(t)}}export{a as audit,H as auditFetch,K as auditOperation,j as devInspector,X as devInspectorErrorHandler};