@xcodleox/devinspector 9.3.2 → 9.3.3
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 +1 -1
- package/dist/angular.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/next.cjs +1 -1
- package/dist/next.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/react-native.cjs +1 -1
- package/dist/react-native.js +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.js +1 -1
- package/dist/svelte.cjs +1 -1
- package/dist/svelte.js +1 -1
- package/dist/vanilla.cjs +1 -1
- package/dist/vanilla.global.js +1 -1
- package/dist/vanilla.js +1 -1
- package/dist/vue.cjs +1 -1
- package/dist/vue.js +1 -1
- package/package.json +1 -1
package/dist/node.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var E=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var Z=(t,e)=>{for(var r in e)E(t,r,{get:e[r],enumerable:!0})},ee=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of W(e))!Y.call(t,s)&&s!==r&&E(t,s,{get:()=>e[s],enumerable:!(n=J(e,s))||n.enumerable});return t};var te=t=>ee(E({},"__esModule",{value:!0}),t);var ge={};Z(ge,{audit:()=>u,auditFetch:()=>he,auditOperation:()=>fe,devInspector:()=>le,devInspectorErrorHandler:()=>me});module.exports=te(ge);var G=require("async_hooks");var N="9.3.2",ne=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),z="https://api.devinspector.com.br/api/ingest/track",L="https://api.devinspector.com.br/api/ingest/apm",B=50,T=1e4,re=6,j=1e4,se=5e3,ie=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function oe(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return ie.some(r=>e.includes(r))}function y(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>T?`${t.slice(0,T)}...[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>=re)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(o=>y(o,e+1,r));let n=t,s={};for(let[o,i]of Object.entries(n)){if(oe(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,r)}return s}finally{r.delete(t)}}function R(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 S(t){return t&&String(t).trim().toUpperCase()||void 0}function $(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 V(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function ae(t){return String(t??"").trim().slice(0,200)}function de(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t,e=200){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ue(t){let e=b(t,50);if(e&&ne.has(e))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 h(t){return y(t)}var M=class{constructor(){this.apiKey="";this.endpoint=z;this.apmEndpoint=L;this.environment="production";this.sdkVersion=N;this.slowThresholdMs=300;this.requestTimeoutMs=j;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||z,this.apmEndpoint=e.apmEndpoint?.trim()||L,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=ue(e.technology),this.installationId=b(e.installationId,200),this.sdkVersion=b(e.sdkVersion,100)||N,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):j,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,T),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>B&&(this.breadcrumbs=this.breadcrumbs.slice(-B))}getBreadcrumbs(){return this.breadcrumbs.map(e=>h(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:h(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),n=new URL(this.apmEndpoint),s=new URL(e,r.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),a=r.pathname.replace(/\/$/,""),d=n.pathname.replace(/\/$/,"");return o===r.origin&&i===a||o===n.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")}async captureRequest(e){let r=S(e.method)||"GET",n=String(e.url||"").trim();if(!n)return;let s=$(e.statusCode)??0,o=A(e.durationMs)??0,i=V(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};!(s>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:n,statusCode:s,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(a)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let n=A(e.durationMs)??0,s={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:n,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:n,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(s)})}captureMetric(e,r,n={},s={}){let o=ae(e);if(!o)return Promise.resolve();let i;try{i=de(r)}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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...n,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 n=e?.message?.trim()||"Erro desconhecido",s={...r},o=S(s.method),i=$(s.statusCode??s.status),a=A(s.durationMs),d=V(s.ip),p=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0,f=typeof s.requestId=="string"&&s.requestId.trim()||void 0,m=typeof s.traceId=="string"&&s.traceId.trim()||void 0,l=typeof s.spanId=="string"&&s.spanId.trim()||void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.durationMs,delete s.ip,delete s.requestId,delete s.traceId,delete s.spanId,this.sendError({type:"error",message:n,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...f?{requestId:f}:{},...m?{traceId:m}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...s,timestamp:new Date().toISOString()})})}captureException(e,r={}){let n=e instanceof Error?e:new Error(R(e));return this.captureError(n,r)}captureMessage(e,r={}){let n=String(e||"").trim();return n?this.sendApm({type:"message",message:n.slice(0,T),environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<se){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let n=this.getPendingConnectionTestEndpoint();if(n)return this.connectionTestRequest=this.fetchPendingConnectionTest(n).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n,s;try{typeof AbortController<"u"&&(n=new AbortController,s=setTimeout(()=>{n?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:n?.signal});if(!o.ok)return;let i=await o.json(),a=b(i.connectionTestId??i.testId,200);if(!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=i.expiresAt?new Date(i.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{s!==void 0&&clearTimeout(s)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}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?.((n,s)=>{this.captureError(n,{platform:"react-native",fatal:s}).finally(()=>{typeof r=="function"&&r(n,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let n=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(n,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let n=r.reason instanceof Error?r.reason:new Error(R(r.reason));this.captureError(n,{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 n=w("event"),s={...r,...this.getIntegrationContext(),eventId:n},o={id:n,endpoint:e,payload:h(s),resolve:()=>{}};return new Promise(i=>{o.resolve=i,this.sendQueue.push(o),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.refreshPendingConnectionTest();let r={...e.payload,...this.getIntegrationContext()},n=typeof r.connectionTestId=="string"?r.connectionTestId:void 0;await this.sendToEndpoint(e.endpoint,h(r))&&n&&this.clearConnectionTest(n)}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 n=typeof fetch=="function"?fetch:void 0;if(!n)return!1;let s=y(r),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=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};return a&&(d.keepalive=!0),(await n(e,d)).ok}catch{return!1}finally{i!==void 0&&clearTimeout(i)}}},K="__DEVINSPECT_AUDIT_CORE_INSTANCE__",F=typeof globalThis<"u"?globalThis:{},u=F[K]||new M;F[K]=u;async function H(t,e,r={}){let n=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!n)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=S(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&u.isIngestUrl(s))return n(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.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",a),p.set("x-devinspector-span-id",d);let f={...e,headers:p},m=typeof performance<"u"?performance.now():Date.now();try{let l=await n(t,f),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m)),g=l.status>=400||c>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:l.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),g?u.captureRequest({method:o,url:s,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d}):u.captureRequest({method:o,url:s,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d}),l}catch(l){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m));u.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:s,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=l instanceof Error?l:new Error(R(l));throw u.captureError(g,{url:s,method:o,type:r.errorType||"network_error",requestId:i,traceId:a,spanId:d}),l}}var k=new G.AsyncLocalStorage;function ce(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[n,s]of Object.entries(t)){let o=n.toLowerCase();e[n]=r.has(o)?"[REDACTED]":s}return e}function I(t,e){if(!t?.headers)return;let r=e.toLowerCase(),n=t.headers,s=n[r]??n[e];if(Array.isArray(s))return s.length>0?String(s[0]):void 0;if(s!=null)return String(s);for(let[o,i]of Object.entries(n))if(o.toLowerCase()===r)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function X(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function pe(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function le(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(n,s,o)=>{let i=n?.originalUrl||n?.url||"";if(i&&u.isIngestUrl(i)||r.some(g=>pe(i,g)))return o();let d=Date.now(),p=I(n,"x-devinspector-request-id")||u.createRequestId(),f=I(n,"x-devinspector-trace-id")||u.createTraceId(),m=I(n,"x-devinspector-span-id")||u.createSpanId(),l=X(n);n?.headers&&(n.headers["x-devinspector-request-id"]=p,n.headers["x-devinspector-trace-id"]=f,n.headers["x-devinspector-span-id"]=m);let c={req:n,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:f,spanId:m,ip:l};return k.run(c,()=>{u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:f,spanId:m,ip:c.ip}}),s.on("finish",()=>{let g=Math.max(0,Date.now()-d),v=typeof s?.statusCode=="number"?s.statusCode:0,U=v>=400,C=g>=e,D=c.slowQueries>0,x=typeof n?.route?.path=="string"?n.route.path:void 0,P=typeof n?.baseUrl=="string"?n.baseUrl:"",q=x?`${P}${x}`:P||i,Q=c.queriesCount,O=c.slowQueries,_=c.slowestQueryMs;u.captureRequest({method:n?.method||"GET",url:i,statusCode:v,durationMs:g,ip:c.ip,userAgent:n?.headers?.["user-agent"],route:q,dbQueriesCount:Q,slowQueryMs:_,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:U,isSlow:C,hasSlowQuery:D,slowQueries:O}}),u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:v,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:q,dbQueriesCount:Q,slowQueries:O,slowQueryMs:_,isError:U,isSlow:C,hasSlowQuery:D}})}),o()})}}async function he(t,e){return H(t,e,{errorType:"node_network_error"})}async function fe(t,e,r){let n=k.getStore(),s=r??u.getSlowThresholdMs(),o=Date.now();n&&n.queriesCount++;let i=n?.req?.originalUrl||n?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=s;return n&&p&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:s,ip:n?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:s,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:i,ip:n?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function me(){return async(t,e,r,n)=>{let s=k.getStore(),o=s?.requestId||I(e,"x-devinspector-request-id"),i=s?.traceId||I(e,"x-devinspector-trace-id"),a=s?.spanId||I(e,"x-devinspector-span-id"),d=s?.ip||X(e),p=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,f=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:p,requestId:o,traceId:i,spanId:a,ip:d}});try{await u.captureException(f,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:p,headers:ce(e?.headers||{}),ip:d,requestId:o,traceId:i,spanId:a,metadata:{errorHandler:"express",route:e?.route?.path,baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await u.flush()}catch(m){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",m)}return r?.headersSent,n(f)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
|
|
1
|
+
"use strict";var E=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(t,e)=>{for(var r in e)E(t,r,{get:e[r],enumerable:!0})},ne=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Z(e))!ee.call(t,s)&&s!==r&&E(t,s,{get:()=>e[s],enumerable:!(n=W(e,s))||n.enumerable});return t};var re=t=>ne(E({},"__esModule",{value:!0}),t);var be={};te(be,{audit:()=>u,auditFetch:()=>Ie,auditOperation:()=>Te,devInspector:()=>ye,devInspectorErrorHandler:()=>we});module.exports=re(be);var Y=require("async_hooks");var N="9.3.3",se=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),L="https://api.devinspector.com.br/api/ingest/track",z="https://api.devinspector.com.br/api/ingest/apm",B=50,b=1e4,ie=6,j=1e4,oe=5e3,$=3,ae=1e3,de=1e4,ue=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ce(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return ue.some(r=>e.includes(r))}function y(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>b?`${t.slice(0,b)}...[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>=ie)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(o=>y(o,e+1,r));let n=t,s={};for(let[o,i]of Object.entries(n)){if(ce(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,r)}return s}finally{r.delete(t)}}function R(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 M(t){return t&&String(t).trim().toUpperCase()||void 0}function V(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 K(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function pe(t){return String(t??"").trim().slice(0,200)}function le(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function w(t,e=200){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function he(t){let e=w(t,50);if(e&&se.has(e))return e}function T(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)}function F(t){let e=Math.max(0,t-1);return Math.min(ae*2**e,de)}function me(t,e){return setTimeout(t,Math.max(0,e))}var S=class{constructor(){this.apiKey="";this.endpoint=L;this.apmEndpoint=z;this.environment="production";this.sdkVersion=N;this.slowThresholdMs=300;this.requestTimeoutMs=j;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||L,this.apmEndpoint=e.apmEndpoint?.trim()||z,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=he(e.technology),this.installationId=w(e.installationId,200),this.sdkVersion=w(e.sdkVersion,100)||N,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):j,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>B&&(this.breadcrumbs=this.breadcrumbs.slice(-B))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),n=new URL(this.apmEndpoint),s=new URL(e,r.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),a=r.pathname.replace(/\/$/,""),d=n.pathname.replace(/\/$/,"");return o===r.origin&&i===a||o===n.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return T("req")}createTraceId(){return T("trace")}createSpanId(){return T("span")}async captureRequest(e){let r=M(e.method)||"GET",n=String(e.url||"").trim();if(!n)return;let s=V(e.statusCode)??0,o=A(e.durationMs)??0,i=K(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};!(s>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:n,statusCode:s,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(a)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let n=A(e.durationMs)??0,s={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:n,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:n,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,r,n={},s={}){let o=pe(e);if(!o)return Promise.resolve();let i;try{i=le(r)}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({...n,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 n=e?.message?.trim()||"Erro desconhecido",s={...r},o=M(s.method),i=V(s.statusCode??s.status),a=A(s.durationMs),d=K(s.ip),p=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0,m=typeof s.requestId=="string"&&s.requestId.trim()||void 0,f=typeof s.traceId=="string"&&s.traceId.trim()||void 0,h=typeof s.spanId=="string"&&s.spanId.trim()||void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.durationMs,delete s.ip,delete s.requestId,delete s.traceId,delete s.spanId,this.sendError({type:"error",message:n,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...m?{requestId:m}:{},...f?{traceId:f}:{},...h?{spanId:h}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...s,timestamp:new Date().toISOString()})})}captureException(e,r={}){let n=e instanceof Error?e:new Error(R(e));return this.captureError(n,r)}captureMessage(e,r={}){let n=String(e||"").trim();return n?this.sendApm({type:"message",message:n.slice(0,b),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<oe){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let n=this.getPendingConnectionTestEndpoint();if(n)return this.connectionTestRequest=this.fetchPendingConnectionTest(n).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n,s;try{typeof AbortController<"u"&&(n=new AbortController,s=setTimeout(()=>{n?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:n?.signal});if(!o.ok)return;let i=await o.json(),a=w(i.connectionTestId??i.testId,200);if(!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=i.expiresAt?new Date(i.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{s!==void 0&&clearTimeout(s)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}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?.((n,s)=>{this.captureError(n,{platform:"react-native",fatal:s}).finally(()=>{typeof r=="function"&&r(n,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let n=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(n,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let n=r.reason instanceof Error?r.reason:new Error(R(r.reason));this.captureError(n,{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 n=T("event"),s={...r,...this.getIntegrationContext(),eventId:n},o={id:n,endpoint:e,payload:l(s),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(i=>{o.resolve=i,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let r=Date.now();if(e.nextAttemptAt>r){this.scheduleQueueRetry(e.nextAttemptAt-r);break}try{await this.refreshPendingConnectionTest();let n={...e.payload,...this.getIntegrationContext()},s=typeof n.connectionTestId=="string"?n.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(n))){this.sendQueue.shift(),s&&this.clearConnectionTest(s),e.resolve();continue}if(e.attempts+=1,e.attempts>=$){this.sendQueue.shift(),e.resolve();continue}let i=F(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}catch{if(e.attempts+=1,e.attempts>=$){this.sendQueue.shift(),e.resolve();continue}let n=F(e.attempts);e.nextAttemptAt=Date.now()+n,this.scheduleQueueRetry(n);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let r of e)r();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let r=Math.max(0,e.nextAttemptAt-Date.now());r>0?this.scheduleQueueRetry(r):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=me(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,r){let n=typeof fetch=="function"?fetch:void 0;if(!n)return!1;let s=y(r),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=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};return a&&(d.keepalive=!0),(await n(e,d)).ok}catch{return!1}finally{i!==void 0&&clearTimeout(i)}}},H="__DEVINSPECT_AUDIT_CORE_INSTANCE__",G=typeof globalThis<"u"?globalThis:{},u=G[H]||new S;G[H]=u;async function X(t,e,r={}){let n=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!n)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=M(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&u.isIngestUrl(s))return n(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.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",a),p.set("x-devinspector-span-id",d);let m={...e,headers:p},f=typeof performance<"u"?performance.now():Date.now();try{let h=await n(t,m),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));return u.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:h.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:s,statusCode:h.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d}),h}catch(h){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));u.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:s,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=h instanceof Error?h:new Error(R(h));throw u.captureError(g,{url:s,method:o,type:r.errorType||"network_error",requestId:i,traceId:a,spanId:d}),h}}var k=new Y.AsyncLocalStorage;function fe(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[n,s]of Object.entries(t)){let o=n.toLowerCase();e[n]=r.has(o)?"[REDACTED]":s}return e}function I(t,e){if(!t?.headers)return;let r=e.toLowerCase(),n=t.headers,s=n[r]??n[e];if(Array.isArray(s))return s.length>0?String(s[0]):void 0;if(s!=null)return String(s);for(let[o,i]of Object.entries(n))if(o.toLowerCase()===r)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function J(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function ge(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function ye(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(n,s,o)=>{let i=n?.originalUrl||n?.url||"";if(i&&u.isIngestUrl(i)||r.some(g=>ge(i,g)))return o();let d=Date.now(),p=I(n,"x-devinspector-request-id")||u.createRequestId(),m=I(n,"x-devinspector-trace-id")||u.createTraceId(),f=I(n,"x-devinspector-span-id")||u.createSpanId(),h=J(n);n?.headers&&(n.headers["x-devinspector-request-id"]=p,n.headers["x-devinspector-trace-id"]=m,n.headers["x-devinspector-span-id"]=f);let c={req:n,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:m,spanId:f,ip:h};return k.run(c,()=>{u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:m,spanId:f,ip:c.ip}}),s.on("finish",()=>{let g=Math.max(0,Date.now()-d),v=typeof s?.statusCode=="number"?s.statusCode:0,x=v>=400,U=g>=e,D=c.slowQueries>0,C=typeof n?.route?.path=="string"?n.route.path:void 0,P=typeof n?.baseUrl=="string"?n.baseUrl:"",q=C?`${P}${C}`:P||i,Q=c.queriesCount,_=c.slowQueries,O=c.slowestQueryMs;u.captureRequest({method:n?.method||"GET",url:i,statusCode:v,durationMs:g,ip:c.ip,userAgent:n?.headers?.["user-agent"],route:q,dbQueriesCount:Q,slowQueryMs:O,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:x,isSlow:U,hasSlowQuery:D,slowQueries:_}}),u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:v,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:q,dbQueriesCount:Q,slowQueries:_,slowQueryMs:O,isError:x,isSlow:U,hasSlowQuery:D}})}),o()})}}async function Ie(t,e){return X(t,e,{errorType:"node_network_error"})}async function Te(t,e,r){let n=k.getStore(),s=r??u.getSlowThresholdMs(),o=Date.now();n&&n.queriesCount++;let i=n?.req?.originalUrl||n?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=s;return n&&p&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:s,ip:n?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:s,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:i,ip:n?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function we(){return async(t,e,r,n)=>{let s=k.getStore(),o=s?.requestId||I(e,"x-devinspector-request-id"),i=s?.traceId||I(e,"x-devinspector-trace-id"),a=s?.spanId||I(e,"x-devinspector-span-id"),d=s?.ip||J(e),p=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,m=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:p,requestId:o,traceId:i,spanId:a,ip:d}});try{await u.captureException(m,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:p,headers:fe(e?.headers||{}),ip:d,requestId:o,traceId:i,spanId:a,metadata:{errorHandler:"express",route:e?.route?.path,baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await u.flush()}catch(f){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",f)}return r?.headersSent,n(m)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
|
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage as ne}from"async_hooks";var _="9.3.2",G=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),N="https://api.devinspector.com.br/api/ingest/track",z="https://api.devinspector.com.br/api/ingest/apm",L=50,T=1e4,X=6,B=1e4,J=5e3,W=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Y(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return W.some(r=>e.includes(r))}function y(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>T?`${t.slice(0,T)}...[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>=X)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(o=>y(o,e+1,r));let n=t,s={};for(let[o,i]of Object.entries(n)){if(Y(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,r)}return s}finally{r.delete(t)}}function A(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 R(t){return t&&String(t).trim().toUpperCase()||void 0}function j(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function E(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function $(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function Z(t){return String(t??"").trim().slice(0,200)}function ee(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t,e=200){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function te(t){let e=b(t,50);if(e&&G.has(e))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 h(t){return y(t)}var S=class{constructor(){this.apiKey="";this.endpoint=N;this.apmEndpoint=z;this.environment="production";this.sdkVersion=_;this.slowThresholdMs=300;this.requestTimeoutMs=B;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||N,this.apmEndpoint=e.apmEndpoint?.trim()||z,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=te(e.technology),this.installationId=b(e.installationId,200),this.sdkVersion=b(e.sdkVersion,100)||_,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):B,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,T),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>L&&(this.breadcrumbs=this.breadcrumbs.slice(-L))}getBreadcrumbs(){return this.breadcrumbs.map(e=>h(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:h(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),n=new URL(this.apmEndpoint),s=new URL(e,r.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),a=r.pathname.replace(/\/$/,""),d=n.pathname.replace(/\/$/,"");return o===r.origin&&i===a||o===n.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")}async captureRequest(e){let r=R(e.method)||"GET",n=String(e.url||"").trim();if(!n)return;let s=j(e.statusCode)??0,o=E(e.durationMs)??0,i=$(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};!(s>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:n,statusCode:s,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(a)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let n=E(e.durationMs)??0,s={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:n,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:n,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(s)})}captureMetric(e,r,n={},s={}){let o=Z(e);if(!o)return Promise.resolve();let i;try{i=ee(r)}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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...n,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 n=e?.message?.trim()||"Erro desconhecido",s={...r},o=R(s.method),i=j(s.statusCode??s.status),a=E(s.durationMs),d=$(s.ip),p=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0,f=typeof s.requestId=="string"&&s.requestId.trim()||void 0,m=typeof s.traceId=="string"&&s.traceId.trim()||void 0,l=typeof s.spanId=="string"&&s.spanId.trim()||void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.durationMs,delete s.ip,delete s.requestId,delete s.traceId,delete s.spanId,this.sendError({type:"error",message:n,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...f?{requestId:f}:{},...m?{traceId:m}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...s,timestamp:new Date().toISOString()})})}captureException(e,r={}){let n=e instanceof Error?e:new Error(A(e));return this.captureError(n,r)}captureMessage(e,r={}){let n=String(e||"").trim();return n?this.sendApm({type:"message",message:n.slice(0,T),environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<J){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let n=this.getPendingConnectionTestEndpoint();if(n)return this.connectionTestRequest=this.fetchPendingConnectionTest(n).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n,s;try{typeof AbortController<"u"&&(n=new AbortController,s=setTimeout(()=>{n?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:n?.signal});if(!o.ok)return;let i=await o.json(),a=b(i.connectionTestId??i.testId,200);if(!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=i.expiresAt?new Date(i.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{s!==void 0&&clearTimeout(s)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}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?.((n,s)=>{this.captureError(n,{platform:"react-native",fatal:s}).finally(()=>{typeof r=="function"&&r(n,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let n=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(n,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let n=r.reason instanceof Error?r.reason:new Error(A(r.reason));this.captureError(n,{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 n=w("event"),s={...r,...this.getIntegrationContext(),eventId:n},o={id:n,endpoint:e,payload:h(s),resolve:()=>{}};return new Promise(i=>{o.resolve=i,this.sendQueue.push(o),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.refreshPendingConnectionTest();let r={...e.payload,...this.getIntegrationContext()},n=typeof r.connectionTestId=="string"?r.connectionTestId:void 0;await this.sendToEndpoint(e.endpoint,h(r))&&n&&this.clearConnectionTest(n)}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 n=typeof fetch=="function"?fetch:void 0;if(!n)return!1;let s=y(r),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=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};return a&&(d.keepalive=!0),(await n(e,d)).ok}catch{return!1}finally{i!==void 0&&clearTimeout(i)}}},V="__DEVINSPECT_AUDIT_CORE_INSTANCE__",K=typeof globalThis<"u"?globalThis:{},u=K[V]||new S;K[V]=u;async function F(t,e,r={}){let n=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!n)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=R(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&u.isIngestUrl(s))return n(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.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",a),p.set("x-devinspector-span-id",d);let f={...e,headers:p},m=typeof performance<"u"?performance.now():Date.now();try{let l=await n(t,f),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m)),g=l.status>=400||c>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:l.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),g?u.captureRequest({method:o,url:s,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d}):u.captureRequest({method:o,url:s,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d}),l}catch(l){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m));u.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:s,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=l instanceof Error?l:new Error(A(l));throw u.captureError(g,{url:s,method:o,type:r.errorType||"network_error",requestId:i,traceId:a,spanId:d}),l}}var M=new ne;function re(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[n,s]of Object.entries(t)){let o=n.toLowerCase();e[n]=r.has(o)?"[REDACTED]":s}return e}function I(t,e){if(!t?.headers)return;let r=e.toLowerCase(),n=t.headers,s=n[r]??n[e];if(Array.isArray(s))return s.length>0?String(s[0]):void 0;if(s!=null)return String(s);for(let[o,i]of Object.entries(n))if(o.toLowerCase()===r)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function H(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function se(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function de(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(n,s,o)=>{let i=n?.originalUrl||n?.url||"";if(i&&u.isIngestUrl(i)||r.some(g=>se(i,g)))return o();let d=Date.now(),p=I(n,"x-devinspector-request-id")||u.createRequestId(),f=I(n,"x-devinspector-trace-id")||u.createTraceId(),m=I(n,"x-devinspector-span-id")||u.createSpanId(),l=H(n);n?.headers&&(n.headers["x-devinspector-request-id"]=p,n.headers["x-devinspector-trace-id"]=f,n.headers["x-devinspector-span-id"]=m);let c={req:n,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:f,spanId:m,ip:l};return M.run(c,()=>{u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:f,spanId:m,ip:c.ip}}),s.on("finish",()=>{let g=Math.max(0,Date.now()-d),v=typeof s?.statusCode=="number"?s.statusCode:0,k=v>=400,U=g>=e,C=c.slowQueries>0,D=typeof n?.route?.path=="string"?n.route.path:void 0,x=typeof n?.baseUrl=="string"?n.baseUrl:"",P=D?`${x}${D}`:x||i,q=c.queriesCount,Q=c.slowQueries,O=c.slowestQueryMs;u.captureRequest({method:n?.method||"GET",url:i,statusCode:v,durationMs:g,ip:c.ip,userAgent:n?.headers?.["user-agent"],route:P,dbQueriesCount:q,slowQueryMs:O,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:k,isSlow:U,hasSlowQuery:C,slowQueries:Q}}),u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:v,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:P,dbQueriesCount:q,slowQueries:Q,slowQueryMs:O,isError:k,isSlow:U,hasSlowQuery:C}})}),o()})}}async function ue(t,e){return F(t,e,{errorType:"node_network_error"})}async function ce(t,e,r){let n=M.getStore(),s=r??u.getSlowThresholdMs(),o=Date.now();n&&n.queriesCount++;let i=n?.req?.originalUrl||n?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=s;return n&&p&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:s,ip:n?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:s,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:i,ip:n?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function pe(){return async(t,e,r,n)=>{let s=M.getStore(),o=s?.requestId||I(e,"x-devinspector-request-id"),i=s?.traceId||I(e,"x-devinspector-trace-id"),a=s?.spanId||I(e,"x-devinspector-span-id"),d=s?.ip||H(e),p=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,f=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:p,requestId:o,traceId:i,spanId:a,ip:d}});try{await u.captureException(f,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:p,headers:re(e?.headers||{}),ip:d,requestId:o,traceId:i,spanId:a,metadata:{errorHandler:"express",route:e?.route?.path,baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await u.flush()}catch(m){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",m)}return r?.headersSent,n(f)}}export{u as audit,ue as auditFetch,ce as auditOperation,de as devInspector,pe as devInspectorErrorHandler};
|
|
1
|
+
import{AsyncLocalStorage as ae}from"async_hooks";var O="9.3.3",Y=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),N="https://api.devinspector.com.br/api/ingest/track",L="https://api.devinspector.com.br/api/ingest/apm",z=50,b=1e4,J=6,B=1e4,W=5e3,j=3,Z=1e3,ee=1e4,te=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ne(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return te.some(r=>e.includes(r))}function y(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>b?`${t.slice(0,b)}...[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>=J)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(o=>y(o,e+1,r));let n=t,s={};for(let[o,i]of Object.entries(n)){if(ne(o)){s[o]="[REDACTED]";continue}s[o]=y(i,e+1,r)}return s}finally{r.delete(t)}}function A(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 R(t){return t&&String(t).trim().toUpperCase()||void 0}function $(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function E(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function V(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function re(t){return String(t??"").trim().slice(0,200)}function se(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function w(t,e=200){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ie(t){let e=w(t,50);if(e&&Y.has(e))return e}function T(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)}function K(t){let e=Math.max(0,t-1);return Math.min(Z*2**e,ee)}function oe(t,e){return setTimeout(t,Math.max(0,e))}var M=class{constructor(){this.apiKey="";this.endpoint=N;this.apmEndpoint=L;this.environment="production";this.sdkVersion=O;this.slowThresholdMs=300;this.requestTimeoutMs=B;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||N,this.apmEndpoint=e.apmEndpoint?.trim()||L,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=ie(e.technology),this.installationId=w(e.installationId,200),this.sdkVersion=w(e.sdkVersion,100)||O,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):B,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>z&&(this.breadcrumbs=this.breadcrumbs.slice(-z))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),n=new URL(this.apmEndpoint),s=new URL(e,r.origin),o=s.origin,i=s.pathname.replace(/\/$/,""),a=r.pathname.replace(/\/$/,""),d=n.pathname.replace(/\/$/,"");return o===r.origin&&i===a||o===n.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return T("req")}createTraceId(){return T("trace")}createSpanId(){return T("span")}async captureRequest(e){let r=R(e.method)||"GET",n=String(e.url||"").trim();if(!n)return;let s=$(e.statusCode)??0,o=E(e.durationMs)??0,i=V(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};!(s>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:n,statusCode:s,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(a)})}captureDbQuery(e){let r=String(e.operation||"").trim();if(!r)return Promise.resolve();let n=E(e.durationMs)??0,s={...e.metadata||{},operation:r,collection:e.collection||"Unknown",durationMs:n,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:e.url,method:"DB",durationMs:n,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,r,n={},s={}){let o=re(e);if(!o)return Promise.resolve();let i;try{i=se(r)}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({...n,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 n=e?.message?.trim()||"Erro desconhecido",s={...r},o=R(s.method),i=$(s.statusCode??s.status),a=E(s.durationMs),d=V(s.ip),p=s.url!==void 0&&s.url!==null?String(s.url).trim():void 0,m=typeof s.requestId=="string"&&s.requestId.trim()||void 0,f=typeof s.traceId=="string"&&s.traceId.trim()||void 0,h=typeof s.spanId=="string"&&s.spanId.trim()||void 0;return delete s.method,delete s.statusCode,delete s.status,delete s.durationMs,delete s.ip,delete s.requestId,delete s.traceId,delete s.spanId,this.sendError({type:"error",message:n,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...m?{requestId:m}:{},...f?{traceId:f}:{},...h?{spanId:h}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...s,timestamp:new Date().toISOString()})})}captureException(e,r={}){let n=e instanceof Error?e:new Error(A(e));return this.captureError(n,r)}captureMessage(e,r={}){let n=String(e||"").trim();return n?this.sendApm({type:"message",message:n.slice(0,b),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<W){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let n=this.getPendingConnectionTestEndpoint();if(n)return this.connectionTestRequest=this.fetchPendingConnectionTest(n).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n,s;try{typeof AbortController<"u"&&(n=new AbortController,s=setTimeout(()=>{n?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:n?.signal});if(!o.ok)return;let i=await o.json(),a=w(i.connectionTestId??i.testId,200);if(!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=i.expiresAt?new Date(i.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{s!==void 0&&clearTimeout(s)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}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?.((n,s)=>{this.captureError(n,{platform:"react-native",fatal:s}).finally(()=>{typeof r=="function"&&r(n,s)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let n=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(n,{url:r.filename||window.location.href,line:r.lineno,column:r.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",r=>{let n=r.reason instanceof Error?r.reason:new Error(A(r.reason));this.captureError(n,{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 n=T("event"),s={...r,...this.getIntegrationContext(),eventId:n},o={id:n,endpoint:e,payload:l(s),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(i=>{o.resolve=i,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let r=Date.now();if(e.nextAttemptAt>r){this.scheduleQueueRetry(e.nextAttemptAt-r);break}try{await this.refreshPendingConnectionTest();let n={...e.payload,...this.getIntegrationContext()},s=typeof n.connectionTestId=="string"?n.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(n))){this.sendQueue.shift(),s&&this.clearConnectionTest(s),e.resolve();continue}if(e.attempts+=1,e.attempts>=j){this.sendQueue.shift(),e.resolve();continue}let i=K(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}catch{if(e.attempts+=1,e.attempts>=j){this.sendQueue.shift(),e.resolve();continue}let n=K(e.attempts);e.nextAttemptAt=Date.now()+n,this.scheduleQueueRetry(n);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let r of e)r();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let r=Math.max(0,e.nextAttemptAt-Date.now());r>0?this.scheduleQueueRetry(r):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=oe(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,r){let n=typeof fetch=="function"?fetch:void 0;if(!n)return!1;let s=y(r),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=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};return a&&(d.keepalive=!0),(await n(e,d)).ok}catch{return!1}finally{i!==void 0&&clearTimeout(i)}}},F="__DEVINSPECT_AUDIT_CORE_INSTANCE__",H=typeof globalThis<"u"?globalThis:{},u=H[F]||new M;H[F]=u;async function G(t,e,r={}){let n=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!n)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=R(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(s&&u.isIngestUrl(s))return n(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.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",a),p.set("x-devinspector-span-id",d);let m={...e,headers:p},f=typeof performance<"u"?performance.now():Date.now();try{let h=await n(t,m),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));return u.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{phase:"complete",statusCode:h.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:s,statusCode:h.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d}),h}catch(h){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));u.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:s,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=h instanceof Error?h:new Error(A(h));throw u.captureError(g,{url:s,method:o,type:r.errorType||"network_error",requestId:i,traceId:a,spanId:d}),h}}var S=new ae;function de(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[n,s]of Object.entries(t)){let o=n.toLowerCase();e[n]=r.has(o)?"[REDACTED]":s}return e}function I(t,e){if(!t?.headers)return;let r=e.toLowerCase(),n=t.headers,s=n[r]??n[e];if(Array.isArray(s))return s.length>0?String(s[0]):void 0;if(s!=null)return String(s);for(let[o,i]of Object.entries(n))if(o.toLowerCase()===r)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function X(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function ue(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function he(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(n,s,o)=>{let i=n?.originalUrl||n?.url||"";if(i&&u.isIngestUrl(i)||r.some(g=>ue(i,g)))return o();let d=Date.now(),p=I(n,"x-devinspector-request-id")||u.createRequestId(),m=I(n,"x-devinspector-trace-id")||u.createTraceId(),f=I(n,"x-devinspector-span-id")||u.createSpanId(),h=X(n);n?.headers&&(n.headers["x-devinspector-request-id"]=p,n.headers["x-devinspector-trace-id"]=m,n.headers["x-devinspector-span-id"]=f);let c={req:n,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:m,spanId:f,ip:h};return S.run(c,()=>{u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:m,spanId:f,ip:c.ip}}),s.on("finish",()=>{let g=Math.max(0,Date.now()-d),v=typeof s?.statusCode=="number"?s.statusCode:0,k=v>=400,x=g>=e,U=c.slowQueries>0,D=typeof n?.route?.path=="string"?n.route.path:void 0,C=typeof n?.baseUrl=="string"?n.baseUrl:"",P=D?`${C}${D}`:C||i,q=c.queriesCount,Q=c.slowQueries,_=c.slowestQueryMs;u.captureRequest({method:n?.method||"GET",url:i,statusCode:v,durationMs:g,ip:c.ip,userAgent:n?.headers?.["user-agent"],route:P,dbQueriesCount:q,slowQueryMs:_,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:k,isSlow:x,hasSlowQuery:U,slowQueries:Q}}),u.addBreadcrumb({type:"http",message:`${n?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:v,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:P,dbQueriesCount:q,slowQueries:Q,slowQueryMs:_,isError:k,isSlow:x,hasSlowQuery:U}})}),o()})}}async function me(t,e){return G(t,e,{errorType:"node_network_error"})}async function fe(t,e,r){let n=S.getStore(),s=r??u.getSlowThresholdMs(),o=Date.now();n&&n.queriesCount++;let i=n?.req?.originalUrl||n?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=s;return n&&p&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:s,ip:n?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:s,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:i,ip:n?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function ge(){return async(t,e,r,n)=>{let s=S.getStore(),o=s?.requestId||I(e,"x-devinspector-request-id"),i=s?.traceId||I(e,"x-devinspector-trace-id"),a=s?.spanId||I(e,"x-devinspector-span-id"),d=s?.ip||X(e),p=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,m=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:p,requestId:o,traceId:i,spanId:a,ip:d}});try{await u.captureException(m,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:p,headers:de(e?.headers||{}),ip:d,requestId:o,traceId:i,spanId:a,metadata:{errorHandler:"express",route:e?.route?.path,baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await u.flush()}catch(f){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",f)}return r?.headersSent,n(m)}}export{u as audit,me as auditFetch,fe as auditOperation,he as devInspector,ge as devInspectorErrorHandler};
|
package/dist/react-native.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var V=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:!0})},F=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of L(e))!z.call(n,r)&&r!==t&&v(n,r,{get:()=>e[r],enumerable:!(i=Q(e,r))||i.enumerable});return n};var B=n=>F(v({},"__esModule",{value:!0}),n);var ee={};V(ee,{AuditErrorBoundary:()=>k,audit:()=>u,auditFetch:()=>W,enableNetworkTracing:()=>Z});module.exports=B(ee);var O=require("react");var _="9.3.2",j=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),C="https://api.devinspector.com.br/api/ingest/track",D="https://api.devinspector.com.br/api/ingest/apm",q=50,b=1e4,K=6,P=1e4,H=5e3,G=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function $(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return G.some(t=>e.includes(t))}function f(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=K)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if($(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,t)}return r}finally{t.delete(n)}}function w(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=f(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function R(n){return n&&String(n).trim().toUpperCase()||void 0}function M(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function E(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function U(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function X(n){return String(n??"").trim().slice(0,200)}function J(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function Y(n){let e=T(n,50);if(e&&j.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function d(n){return f(n)}var A=class{constructor(){this.apiKey="";this.endpoint=C;this.apmEndpoint=D;this.environment="production";this.sdkVersion=_;this.slowThresholdMs=300;this.requestTimeoutMs=P;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||C,this.apmEndpoint=e.apmEndpoint?.trim()||D,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=Y(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||_,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):P,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>q&&(this.breadcrumbs=this.breadcrumbs.slice(-q))}getBreadcrumbs(){return this.breadcrumbs.map(e=>d(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:d(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=R(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=M(e.statusCode)??0,s=E(e.durationMs)??0,o=U(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=E(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=X(e);if(!s)return Promise.resolve();let o;try{o=J(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=R(r.method),o=M(r.statusCode??r.status),c=E(r.durationMs),a=U(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,m=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...m?{traceId:m}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(w(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<H){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(w(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:d(r),resolve:()=>{}};return new Promise(o=>{s.resolve=o,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.refreshPendingConnectionTest();let t={...e.payload,...this.getIntegrationContext()},i=typeof t.connectionTestId=="string"?t.connectionTestId:void 0;await this.sendToEndpoint(e.endpoint,d(t))&&i&&this.clearConnectionTest(i)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let t of e)t()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},N="__DEVINSPECT_AUDIT_CORE_INSTANCE__",x=typeof globalThis<"u"?globalThis:{},u=x[N]||new A;x[N]=u;async function S(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=R(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&u.isIngestUrl(r))return i(n,e);let o=u.createRequestId(),c=u.createTraceId(),a=u.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},m=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m)),I=l.status>=400||h>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:h,requestId:o,traceId:c,spanId:a}}),I?u.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}):u.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m));u.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:h,requestId:o,traceId:c,spanId:a}}),u.captureRequest({method:s,url:r,statusCode:0,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let I=l instanceof Error?l:new Error(w(l));throw u.captureError(I,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}var k=class extends O.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){u.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),u.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function W(n,e){return S(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function Z(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return S(s,o,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}0&&(module.exports={AuditErrorBoundary,audit,auditFetch,enableNetworkTracing});
|
|
1
|
+
"use strict";var I=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var B=(n,e)=>{for(var t in e)I(n,t,{get:e[t],enumerable:!0})},j=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of V(e))!F.call(n,r)&&r!==t&&I(n,r,{get:()=>e[r],enumerable:!(i=z(e,r))||i.enumerable});return n};var K=n=>j(I({},"__esModule",{value:!0}),n);var se={};B(se,{AuditErrorBoundary:()=>_,audit:()=>d,auditFetch:()=>re,enableNetworkTracing:()=>ie});module.exports=K(se);var O=require("react");var k="9.3.3",H=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),S="https://api.devinspector.com.br/api/ingest/track",D="https://api.devinspector.com.br/api/ingest/apm",M=50,b=1e4,G=6,C=1e4,$=5e3,q=3,Y=1e3,X=1e4,J=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function W(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return J.some(t=>e.includes(t))}function h(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=G)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>h(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(W(s)){r[s]="[REDACTED]";continue}r[s]=h(o,e+1,t)}return r}finally{t.delete(n)}}function v(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=h(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function w(n){return n&&String(n).trim().toUpperCase()||void 0}function P(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function E(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function U(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function Z(n){return String(n??"").trim().slice(0,200)}function ee(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function te(n){let e=T(n,50);if(e&&H.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(n){return h(n)}function x(n){let e=Math.max(0,n-1);return Math.min(Y*2**e,X)}function ne(n,e){return setTimeout(n,Math.max(0,e))}var R=class{constructor(){this.apiKey="";this.endpoint=S;this.apmEndpoint=D;this.environment="production";this.sdkVersion=k;this.slowThresholdMs=300;this.requestTimeoutMs=C;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||S,this.apmEndpoint=e.apmEndpoint?.trim()||D,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=te(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||k,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):C,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?h(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?h(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>M&&(this.breadcrumbs=this.breadcrumbs.slice(-M))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=w(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=P(e.statusCode)??0,s=E(e.durationMs)??0,o=U(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=E(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=Z(e);if(!s)return Promise.resolve();let o;try{o=ee(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=w(r.method),o=P(r.statusCode??r.status),c=E(r.durationMs),a=U(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,f=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...f?{traceId:f}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(v(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<$){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(v(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:u(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext()},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,u(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=q){this.sendQueue.shift(),e.resolve();continue}let o=x(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=q){this.sendQueue.shift(),e.resolve();continue}let i=x(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=ne(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=h(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},N="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Q=typeof globalThis<"u"?globalThis:{},d=Q[N]||new R;Q[N]=d;async function A(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=w(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(n,e);let o=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},f=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));return d.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:0,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let L=l instanceof Error?l:new Error(v(l));throw d.captureError(L,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}var _=class extends O.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){d.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),d.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function re(n,e){return A(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function ie(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return A(s,o,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}0&&(module.exports={AuditErrorBoundary,audit,auditFetch,enableNetworkTracing});
|
package/dist/react-native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Component as j}from"react";var S="9.3.2",x=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),k="https://api.devinspector.com.br/api/ingest/track",_="https://api.devinspector.com.br/api/ingest/apm",C=50,b=1e4,O=6,D=1e4,Q=5e3,L=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function z(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return L.some(t=>e.includes(t))}function f(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=O)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(z(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,t)}return r}finally{t.delete(n)}}function E(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=f(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function w(n){return n&&String(n).trim().toUpperCase()||void 0}function q(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function v(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function P(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function V(n){return String(n??"").trim().slice(0,200)}function F(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function B(n){let e=T(n,50);if(e&&x.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function d(n){return f(n)}var R=class{constructor(){this.apiKey="";this.endpoint=k;this.apmEndpoint=_;this.environment="production";this.sdkVersion=S;this.slowThresholdMs=300;this.requestTimeoutMs=D;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||k,this.apmEndpoint=e.apmEndpoint?.trim()||_,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=B(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||S,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):D,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>C&&(this.breadcrumbs=this.breadcrumbs.slice(-C))}getBreadcrumbs(){return this.breadcrumbs.map(e=>d(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:d(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=w(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=q(e.statusCode)??0,s=v(e.durationMs)??0,o=P(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=v(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=V(e);if(!s)return Promise.resolve();let o;try{o=F(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=w(r.method),o=q(r.statusCode??r.status),c=v(r.durationMs),a=P(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,m=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...m?{traceId:m}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(E(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:d(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:d({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<Q){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(E(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:d(r),resolve:()=>{}};return new Promise(o=>{s.resolve=o,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.refreshPendingConnectionTest();let t={...e.payload,...this.getIntegrationContext()},i=typeof t.connectionTestId=="string"?t.connectionTestId:void 0;await this.sendToEndpoint(e.endpoint,d(t))&&i&&this.clearConnectionTest(i)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let t of e)t()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},M="__DEVINSPECT_AUDIT_CORE_INSTANCE__",U=typeof globalThis<"u"?globalThis:{},u=U[M]||new R;U[M]=u;async function A(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=w(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&u.isIngestUrl(r))return i(n,e);let o=u.createRequestId(),c=u.createTraceId(),a=u.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},m=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m)),I=l.status>=400||h>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:h,requestId:o,traceId:c,spanId:a}}),I?u.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}):u.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m));u.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:h,requestId:o,traceId:c,spanId:a}}),u.captureRequest({method:s,url:r,statusCode:0,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let I=l instanceof Error?l:new Error(E(l));throw u.captureError(I,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}var N=class extends j{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){u.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),u.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function Y(n,e){return A(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function W(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return A(s,o,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}export{N as AuditErrorBoundary,u as audit,Y as auditFetch,W as enableNetworkTracing};
|
|
1
|
+
import{Component as Y}from"react";var A="9.3.3",O=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),_="https://api.devinspector.com.br/api/ingest/track",k="https://api.devinspector.com.br/api/ingest/apm",S=50,b=1e4,L=6,D=1e4,z=5e3,M=3,V=1e3,F=1e4,B=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function j(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return B.some(t=>e.includes(t))}function h(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=L)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>h(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(j(s)){r[s]="[REDACTED]";continue}r[s]=h(o,e+1,t)}return r}finally{t.delete(n)}}function E(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=h(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function v(n){return n&&String(n).trim().toUpperCase()||void 0}function C(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function I(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function q(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function K(n){return String(n??"").trim().slice(0,200)}function H(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function G(n){let e=T(n,50);if(e&&O.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(n){return h(n)}function P(n){let e=Math.max(0,n-1);return Math.min(V*2**e,F)}function $(n,e){return setTimeout(n,Math.max(0,e))}var w=class{constructor(){this.apiKey="";this.endpoint=_;this.apmEndpoint=k;this.environment="production";this.sdkVersion=A;this.slowThresholdMs=300;this.requestTimeoutMs=D;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||_,this.apmEndpoint=e.apmEndpoint?.trim()||k,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=G(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||A,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):D,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?h(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?h(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>S&&(this.breadcrumbs=this.breadcrumbs.slice(-S))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=v(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=C(e.statusCode)??0,s=I(e.durationMs)??0,o=q(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=I(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=K(e);if(!s)return Promise.resolve();let o;try{o=H(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=v(r.method),o=C(r.statusCode??r.status),c=I(r.durationMs),a=q(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,f=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...f?{traceId:f}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(E(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<z){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(E(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:u(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext()},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,u(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=M){this.sendQueue.shift(),e.resolve();continue}let o=P(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=M){this.sendQueue.shift(),e.resolve();continue}let i=P(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=$(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=h(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},U="__DEVINSPECT_AUDIT_CORE_INSTANCE__",x=typeof globalThis<"u"?globalThis:{},d=x[U]||new w;x[U]=d;async function R(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=v(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(n,e);let o=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},f=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));return d.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:0,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let Q=l instanceof Error?l:new Error(E(l));throw d.captureError(Q,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}var N=class extends Y{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){d.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),d.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function ne(n,e){return R(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function re(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return R(s,o,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}export{N as AuditErrorBoundary,d as audit,ne as auditFetch,re as enableNetworkTracing};
|
package/dist/react.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var F=(n,e)=>{for(var t in e)E(n,t,{get:e[t],enumerable:!0})},B=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of z(e))!V.call(n,r)&&r!==t&&E(n,r,{get:()=>e[r],enumerable:!(i=L(e,r))||i.enumerable});return n};var j=n=>B(E({},"__esModule",{value:!0}),n);var te={};F(te,{AuditErrorBoundary:()=>k,audit:()=>d,auditFetch:()=>Z,enableNetworkTracing:()=>ee});module.exports=j(te);var O=require("react");var C="9.3.2",K=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),_="https://api.devinspector.com.br/api/ingest/track",D="https://api.devinspector.com.br/api/ingest/apm",q=50,b=1e4,H=6,P=1e4,G=5e3,$=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function X(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return $.some(t=>e.includes(t))}function f(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=H)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(X(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,t)}return r}finally{t.delete(n)}}function w(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=f(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function R(n){return n&&String(n).trim().toUpperCase()||void 0}function M(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function v(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function U(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function J(n){return String(n??"").trim().slice(0,200)}function Y(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function W(n){let e=T(n,50);if(e&&K.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(n){return f(n)}var A=class{constructor(){this.apiKey="";this.endpoint=_;this.apmEndpoint=D;this.environment="production";this.sdkVersion=C;this.slowThresholdMs=300;this.requestTimeoutMs=P;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||_,this.apmEndpoint=e.apmEndpoint?.trim()||D,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=W(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||C,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):P,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>q&&(this.breadcrumbs=this.breadcrumbs.slice(-q))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=R(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=M(e.statusCode)??0,s=v(e.durationMs)??0,o=U(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=v(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=J(e);if(!s)return Promise.resolve();let o;try{o=Y(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=R(r.method),o=M(r.statusCode??r.status),c=v(r.durationMs),a=U(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,m=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...m?{traceId:m}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(w(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<G){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(w(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:u(r),resolve:()=>{}};return new Promise(o=>{s.resolve=o,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.refreshPendingConnectionTest();let t={...e.payload,...this.getIntegrationContext()},i=typeof t.connectionTestId=="string"?t.connectionTestId:void 0;await this.sendToEndpoint(e.endpoint,u(t))&&i&&this.clearConnectionTest(i)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let t of e)t()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},x="__DEVINSPECT_AUDIT_CORE_INSTANCE__",N=typeof globalThis<"u"?globalThis:{},d=N[x]||new A;N[x]=d;async function S(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=R(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(n,e);let o=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},m=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m)),I=l.status>=400||h>=d.getSlowThresholdMs();return d.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:h,requestId:o,traceId:c,spanId:a}}),I?d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}):d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m));d.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:h,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:0,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let I=l instanceof Error?l:new Error(w(l));throw d.captureError(I,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}var Q=require("react/jsx-runtime"),k=class extends O.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){d.addBreadcrumb({type:"react_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),d.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??(0,Q.jsx)("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function Z(n,e){return S(n,e,{errorType:"react_network_error"})}function ee(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return S(s,o,{errorType:"react_network_error",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}0&&(module.exports={AuditErrorBoundary,audit,auditFetch,enableNetworkTracing});
|
|
1
|
+
"use strict";var I=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var j=(n,e)=>{for(var t in e)I(n,t,{get:e[t],enumerable:!0})},K=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of F(e))!B.call(n,r)&&r!==t&&I(n,r,{get:()=>e[r],enumerable:!(i=V(e,r))||i.enumerable});return n};var H=n=>K(I({},"__esModule",{value:!0}),n);var oe={};j(oe,{AuditErrorBoundary:()=>k,audit:()=>d,auditFetch:()=>ie,enableNetworkTracing:()=>se});module.exports=H(oe);var O=require("react");var S="9.3.3",G=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),_="https://api.devinspector.com.br/api/ingest/track",D="https://api.devinspector.com.br/api/ingest/apm",M=50,b=1e4,$=6,C=1e4,Y=5e3,q=3,X=1e3,J=1e4,W=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Z(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return W.some(t=>e.includes(t))}function h(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=$)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>h(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(Z(s)){r[s]="[REDACTED]";continue}r[s]=h(o,e+1,t)}return r}finally{t.delete(n)}}function v(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=h(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function w(n){return n&&String(n).trim().toUpperCase()||void 0}function P(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function E(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function U(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function ee(n){return String(n??"").trim().slice(0,200)}function te(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function ne(n){let e=T(n,50);if(e&&G.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(n){return h(n)}function x(n){let e=Math.max(0,n-1);return Math.min(X*2**e,J)}function re(n,e){return setTimeout(n,Math.max(0,e))}var R=class{constructor(){this.apiKey="";this.endpoint=_;this.apmEndpoint=D;this.environment="production";this.sdkVersion=S;this.slowThresholdMs=300;this.requestTimeoutMs=C;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||_,this.apmEndpoint=e.apmEndpoint?.trim()||D,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=ne(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||S,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):C,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?h(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?h(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>M&&(this.breadcrumbs=this.breadcrumbs.slice(-M))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=w(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=P(e.statusCode)??0,s=E(e.durationMs)??0,o=U(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=E(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=ee(e);if(!s)return Promise.resolve();let o;try{o=te(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=w(r.method),o=P(r.statusCode??r.status),c=E(r.durationMs),a=U(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,f=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...f?{traceId:f}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(v(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<Y){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(v(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:u(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext()},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,u(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=q){this.sendQueue.shift(),e.resolve();continue}let o=x(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=q){this.sendQueue.shift(),e.resolve();continue}let i=x(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=re(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=h(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},Q="__DEVINSPECT_AUDIT_CORE_INSTANCE__",N=typeof globalThis<"u"?globalThis:{},d=N[Q]||new R;N[Q]=d;async function A(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=w(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(n,e);let o=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},f=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));return d.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:0,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let z=l instanceof Error?l:new Error(v(l));throw d.captureError(z,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}var L=require("react/jsx-runtime"),k=class extends O.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){d.addBreadcrumb({type:"react_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),d.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??(0,L.jsx)("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function ie(n,e){return A(n,e,{errorType:"react_network_error"})}function se(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return A(s,o,{errorType:"react_network_error",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}0&&(module.exports={AuditErrorBoundary,audit,auditFetch,enableNetworkTracing});
|
package/dist/react.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Component as j}from"react";var S="9.3.2",N=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),k="https://api.devinspector.com.br/api/ingest/track",C="https://api.devinspector.com.br/api/ingest/apm",_=50,b=1e4,O=6,D=1e4,Q=5e3,L=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function z(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return L.some(t=>e.includes(t))}function f(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=O)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(z(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,t)}return r}finally{t.delete(n)}}function v(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=f(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function w(n){return n&&String(n).trim().toUpperCase()||void 0}function q(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function E(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function P(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function V(n){return String(n??"").trim().slice(0,200)}function F(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function B(n){let e=T(n,50);if(e&&N.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(n){return f(n)}var R=class{constructor(){this.apiKey="";this.endpoint=k;this.apmEndpoint=C;this.environment="production";this.sdkVersion=S;this.slowThresholdMs=300;this.requestTimeoutMs=D;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||k,this.apmEndpoint=e.apmEndpoint?.trim()||C,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=B(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||S,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):D,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}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 t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>_&&(this.breadcrumbs=this.breadcrumbs.slice(-_))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=w(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=q(e.statusCode)??0,s=E(e.durationMs)??0,o=P(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=E(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=V(e);if(!s)return Promise.resolve();let o;try{o=F(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=w(r.method),o=q(r.statusCode??r.status),c=E(r.durationMs),a=P(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,m=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...m?{traceId:m}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(v(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<Q){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(v(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:u(r),resolve:()=>{}};return new Promise(o=>{s.resolve=o,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.refreshPendingConnectionTest();let t={...e.payload,...this.getIntegrationContext()},i=typeof t.connectionTestId=="string"?t.connectionTestId:void 0;await this.sendToEndpoint(e.endpoint,u(t))&&i&&this.clearConnectionTest(i)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let t of e)t()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},M="__DEVINSPECT_AUDIT_CORE_INSTANCE__",U=typeof globalThis<"u"?globalThis:{},d=U[M]||new R;U[M]=d;async function A(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=w(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(n,e);let o=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},m=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m)),I=l.status>=400||h>=d.getSlowThresholdMs();return d.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:h,requestId:o,traceId:c,spanId:a}}),I?d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}):d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-m));d.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:h,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:0,durationMs:h,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let I=l instanceof Error?l:new Error(v(l));throw d.captureError(I,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}import{jsx as K}from"react/jsx-runtime";var x=class extends j{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){d.addBreadcrumb({type:"react_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),d.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??K("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function W(n,e){return A(n,e,{errorType:"react_network_error"})}function Z(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return A(s,o,{errorType:"react_network_error",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}export{x as AuditErrorBoundary,d as audit,W as auditFetch,Z as enableNetworkTracing};
|
|
1
|
+
import{Component as Y}from"react";var A="9.3.3",O=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),k="https://api.devinspector.com.br/api/ingest/track",S="https://api.devinspector.com.br/api/ingest/apm",_=50,b=1e4,L=6,D=1e4,z=5e3,M=3,V=1e3,F=1e4,B=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function j(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return B.some(t=>e.includes(t))}function h(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=L)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(s=>h(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(j(s)){r[s]="[REDACTED]";continue}r[s]=h(o,e+1,t)}return r}finally{t.delete(n)}}function E(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=h(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function v(n){return n&&String(n).trim().toUpperCase()||void 0}function C(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.round(n)}function I(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function q(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function K(n){return String(n??"").trim().slice(0,200)}function H(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function T(n,e=200){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function G(n){let e=T(n,50);if(e&&O.has(e))return e}function y(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function u(n){return h(n)}function P(n){let e=Math.max(0,n-1);return Math.min(V*2**e,F)}function $(n,e){return setTimeout(n,Math.max(0,e))}var w=class{constructor(){this.apiKey="";this.endpoint=k;this.apmEndpoint=S;this.environment="production";this.sdkVersion=A;this.slowThresholdMs=300;this.requestTimeoutMs=D;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||k,this.apmEndpoint=e.apmEndpoint?.trim()||S,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.technology=G(e.technology),this.installationId=T(e.installationId,200),this.sdkVersion=T(e.sdkVersion,100)||A,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):D,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),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}getTechnology(){return this.technology}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?h(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,b),metadata:e.metadata?h(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>_&&(this.breadcrumbs=this.breadcrumbs.slice(-_))}getBreadcrumbs(){return this.breadcrumbs.map(e=>u(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,installationId:this.installationId,sdkVersion:this.sdkVersion,user:u(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return y("req")}createTraceId(){return y("trace")}createSpanId(){return y("span")}async captureRequest(e){let t=v(e.method)||"GET",i=String(e.url||"").trim();if(!i)return;let r=C(e.statusCode)??0,s=I(e.durationMs)??0,o=q(e.ip),c={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...o?{ip:o}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u(c)})}captureDbQuery(e){let t=String(e.operation||"").trim();if(!t)return Promise.resolve();let i=I(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:e.collection||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,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(r)})}captureMetric(e,t,i={},r={}){let s=K(e);if(!s)return Promise.resolve();let o;try{o=H(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},s=v(r.method),o=C(r.statusCode??r.status),c=I(r.durationMs),a=q(r.ip),p=r.url!==void 0&&r.url!==null?String(r.url).trim():void 0,g=typeof r.requestId=="string"&&r.requestId.trim()||void 0,f=typeof r.traceId=="string"&&r.traceId.trim()||void 0,l=typeof r.spanId=="string"&&r.spanId.trim()||void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.requestId,delete r.traceId,delete r.spanId,this.sendError({type:"error",message:i,stackTrace:e?.stack||"",...p?{url:p}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{requestId:g}:{},...f?{traceId:f}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(E(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:u(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:u({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<z){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=T(o.connectionTestId??o.testId,200);if(!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,line:t.lineno,column:t.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(E(t.reason));this.captureError(i,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=y("event"),r={...t,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:u(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext()},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,u(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=M){this.sendQueue.shift(),e.resolve();continue}let o=P(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=M){this.sendQueue.shift(),e.resolve();continue}let i=P(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=$(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=h(t),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},U="__DEVINSPECT_AUDIT_CORE_INSTANCE__",x=typeof globalThis<"u"?globalThis:{},d=x[U]||new w;x[U]=d;async function R(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),s=v(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(n,e);let o=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",o),p.set("x-devinspector-trace-id",c),p.set("x-devinspector-span-id",a);let g={...e,headers:p},f=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,g),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));return d.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:l.status,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),d.captureRequest({method:s,url:r,statusCode:0,durationMs:m,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let N=l instanceof Error?l:new Error(E(l));throw d.captureError(N,{url:r,method:s,type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a}),l}}import{jsx as X}from"react/jsx-runtime";var Q=class extends Y{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){d.addBreadcrumb({type:"react_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),d.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??X("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function re(n,e){return R(n,e,{errorType:"react_network_error"})}function ie(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(s,o){return R(s,o,{errorType:"react_network_error",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}export{Q as AuditErrorBoundary,d as audit,re as auditFetch,ie as enableNetworkTracing};
|