@xcodleox/devinspector 9.3.6 → 9.3.8
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 +5 -2
- package/dist/index.d.ts +5 -2
- 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/angular.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var R=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ie=(t,e)=>{for(var n in e)R(t,n,{get:e[n],enumerable:!0})},se=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ne(e))!re.call(t,r)&&r!==n&&R(t,r,{get:()=>e[r],enumerable:!(i=te(e,r))||i.enumerable});return t};var oe=t=>se(R({},"__esModule",{value:!0}),t);var Ee={};ie(Ee,{AuditAngularErrorHandler:()=>y,audit:()=>l,auditInterceptor:()=>be,devInspectorInterceptor:()=>ee});module.exports=oe(Ee);var W=require("@angular/core"),E=require("@angular/common/http"),Z=require("rxjs/operators");var _="9.3.6",ae=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),de=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",P="https://api.devinspector.com.br/api/ingest/apm",N=50,v=1e4,ue=5e4,M=4e3,L=4e3,Q=2e3,O=1e3,H=200,T=200,ce=100,pe=200,le=100,he=6,z=1e4,fe=5e3,B=3,me=1e3,ge=1e4,ye=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Te(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return ye.some(n=>e.includes(n))}function f(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>v?`${t.slice(0,v)}...[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>=he)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>f(s,e+1,n));let i=t,r={};for(let[s,o]of Object.entries(i)){if(Te(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,n)}return r}finally{n.delete(t)}}function G(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function V(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function j(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function k(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 u(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function Ie(t){return String(t??"").trim().slice(0,200)}function ve(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function I(t,e=T){return u(t,e)}function K(t){let e=I(t,50);if(e&&ae.has(e))return e}function F(t){let e=I(t,50);if(e&&de.has(e))return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(t){return f(t)}function X(t){let e=Math.max(0,t-1);return Math.min(me*2**e,ge)}function we(t,e){return setTimeout(t,Math.max(0,e))}var D=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=P;this.environment="production";this.sdkVersion=_;this.slowThresholdMs=300;this.requestTimeoutMs=z;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()||x,this.apmEndpoint=e.apmEndpoint?.trim()||P,this.environment=u(e.environment,ce)||"production",this.release=u(e.release,pe),this.technology=K(e.technology),this.category=F(e.category),this.installationId=I(e.installationId,T),this.sdkVersion=I(e.sdkVersion,le)||_,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):z,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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>N&&(this.breadcrumbs=this.breadcrumbs.slice(-N))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=n.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===n.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let n=V(e.method)||"GET",i=u(e.url,M);if(!i)return;let r=j(e.statusCode)??0,s=k(e.durationMs)??0,o=$(e.ip),c=u(e.path,L),a=u(e.route,Q),d=u(e.userAgent,O),h=u(e.contentType,H),m=e.query?f(e.query):void 0,g=e.requestBody!==void 0?f(e.requestBody):void 0,w={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:s,...c?{path:c}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...h?{contentType:h}:{},...o?{ip:o}:{},...m?{query:m}:{},...g!==void 0?{requestBody:g}:{},...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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(w)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=k(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:u(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:u(e.url,M),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(r)})}captureMetric(e,n,i={},r={}){let s=Ie(e);if(!s)return Promise.resolve();let o;try{o=ve(n)}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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},s=V(r.method),o=j(r.statusCode??r.status),c=k(r.durationMs),a=$(r.ip),d=u(r.url,M),h=u(r.path,L),m=u(r.route,Q),g=u(r.userAgent,O),w=u(r.contentType,H),A=u(r.requestId,T),q=u(r.traceId,T),S=u(r.spanId,T),C=r.query!==void 0?f(r.query):void 0,U=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,ue)||"",...d?{url:d}:{},...h?{path:h}:{},...m?{route:m}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{userAgent:g}:{},...w?{contentType:w}:{},...C?{query:C}:{},...U!==void 0?{requestBody:U}:{},...A?{requestId:A}:{},...q?{traceId:q}:{},...S?{spanId:S}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(G(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<fe){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=I(o.connectionTestId??o.testId,T),a=I(o.installationId,T);if(a&&!this.installationId&&(this.installationId=a),o.technology&&!this.technology&&(this.technology=K(o.technology)),o.category&&!this.category&&(this.category=F(o.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let d=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d: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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(G(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...n,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:p(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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,p(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=B){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>=B){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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=we(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(n),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)}}},Y="__DEVINSPECT_AUDIT_CORE_INSTANCE__",J=typeof globalThis<"u"?globalThis:{},l=J[Y]||new D;J[Y]=l;var y=class{handleError(e){let n=e instanceof Error?e:new Error(String(e));l.captureError(n,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""})}};y.\u0275fac=t=>new(t||y);y.\u0275prov=(0,W.\u0275\u0275defineInjectable)({token:y,factory:y.\u0275fac,providedIn:"root"});var ee=(t,e)=>{let n=t.urlWithParams||t.url||"";if(n&&l.isIngestUrl(n))return e(t);let i=l.createRequestId(),r=l.createTraceId(),s=l.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":i,"x-devinspector-trace-id":r,"x-devinspector-span-id":s}}),c=typeof performance<"u"?performance.now():Date.now();return e(o).pipe((0,Z.tap)({next:a=>{if(!(a instanceof E.HttpResponse))return;let d=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),h=a.status||0;(h>=400||d>=l.getSlowThresholdMs())&&l.captureRequest({method:t.method||"GET",url:n,statusCode:h,durationMs:d,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),l.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:h,durationMs:d,requestId:i,traceId:r,spanId:s}})},error:a=>{let d=a instanceof E.HttpErrorResponse?a:null,h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),m=d?.status||0,g=d?.message||d?.statusText||"Erro de rede no cliente";l.captureRequest({method:t.method||"GET",url:n,statusCode:m,durationMs:h,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),l.captureException(new Error(`HTTP Error ${m}: ${g}`),{url:n,method:t.method||"GET",statusCode:m,statusText:d?.statusText||"",type:"angular_network_error",requestId:i,traceId:r,spanId:s}),l.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:m,durationMs:h,requestId:i,traceId:r,spanId:s,error:g}})}}))},be=ee;0&&(module.exports={AuditAngularErrorHandler,audit,auditInterceptor,devInspectorInterceptor});
|
|
1
|
+
"use strict";var R=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var ie=Object.prototype.hasOwnProperty;var se=(t,e)=>{for(var n in e)R(t,n,{get:e[n],enumerable:!0})},oe=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of re(e))!ie.call(t,r)&&r!==n&&R(t,r,{get:()=>e[r],enumerable:!(i=ne(e,r))||i.enumerable});return t};var ae=t=>oe(R({},"__esModule",{value:!0}),t);var Ee={};se(Ee,{AuditAngularErrorHandler:()=>y,audit:()=>h,auditInterceptor:()=>be,devInspectorInterceptor:()=>te});module.exports=ae(Ee);var Z=require("@angular/core"),E=require("@angular/common/http"),ee=require("rxjs/operators");var U="9.3.8",de=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ce=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",P="https://api.devinspector.com.br/api/ingest/apm",N=50,w=1e4,ue=5e4,M=4e3,L=4e3,Q=2e3,O=1e3,z=200,T=200,pe=100,le=200,he=100,fe=6,H=1e4,B=5e3,G=3,me=1e3,ge=1e4,ye=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Te(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return ye.some(n=>e.includes(n))}function f(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>w?`${t.slice(0,w)}...[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>=fe)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>f(s,e+1,n));let i=t,r={};for(let[s,o]of Object.entries(i)){if(Te(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,n)}return r}finally{n.delete(t)}}function V(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function $(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function j(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function k(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 c(t,e=w){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function Ie(t){return String(t??"").trim().slice(0,200)}function ve(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function I(t,e=T){return c(t,e)}function F(t){let e=I(t,50);if(e&&de.has(e))return e}function X(t){let e=I(t,50);if(e&&ce.has(e))return e}function v(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 f(t)}function Y(t){let e=Math.max(0,t-1);return Math.min(me*2**e,ge)}function we(t,e){return setTimeout(t,Math.max(0,e))}var C=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=P;this.environment="production";this.sdkVersion=U;this.slowThresholdMs=300;this.requestTimeoutMs=H;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()||x,this.apmEndpoint=e.apmEndpoint?.trim()||P,this.environment=c(e.environment,pe)||"production",this.release=c(e.release,le),this.technology=F(e.technology),this.category=X(e.category),this.installationId=I(e.installationId,T)||v("di"),this.sdkVersion=I(e.sdkVersion,he)||U,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):H,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.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>N&&(this.breadcrumbs=this.breadcrumbs.slice(-N))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),d=i.pathname.replace(/\/$/,"");return s===n.origin&&o===u||s===i.origin&&o===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return v("req")}createTraceId(){return v("trace")}createSpanId(){return v("span")}async captureRequest(e){let n=$(e.method)||"GET",i=c(e.url,M);if(!i)return;let r=j(e.statusCode)??0,s=k(e.durationMs)??0,o=K(e.ip),u=c(e.path,L),d=c(e.route,Q),a=c(e.userAgent,O),p=c(e.contentType,z),m=e.query?f(e.query):void 0,g=e.requestBody!==void 0?f(e.requestBody):void 0,b={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:s,...u?{path:u}:{},...d?{route:d}:{},...a?{userAgent:a}:{},...p?{contentType:p}:{},...o?{ip:o}:{},...m?{query:m}:{},...g!==void 0?{requestBody:g}:{},...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(b)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=k(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:c(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:c(e.url,M),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,n,i={},r={}){let s=Ie(e);if(!s)return Promise.resolve();let o;try{o=ve(n)}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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},s=$(r.method),o=j(r.statusCode??r.status),u=k(r.durationMs),d=K(r.ip),a=c(r.url,M),p=c(r.path,L),m=c(r.route,Q),g=c(r.userAgent,O),b=c(r.contentType,z),A=c(r.requestId,T),D=c(r.traceId,T),q=c(r.spanId,T),S=r.query!==void 0?f(r.query):void 0,_=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,w),stackTrace:e?.stack?.slice(0,ue)||"",...a?{url:a}:{},...p?{path:p}:{},...m?{route:m}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...u!==void 0?{durationMs:u}:{},...d?{ip:d}:{},...g?{userAgent:g}:{},...b?{contentType:b}:{},...S?{query:S}:{},..._!==void 0?{requestBody:_}:{},...A?{requestId:A}:{},...D?{traceId:D}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(V(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,w),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},B)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<B){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),u=I(o.connectionTestId??o.testId,T),d=I(o.installationId,T);if(d&&!this.installationId&&(this.installationId=d),o.technology&&!this.technology&&(this.technology=F(o.technology)),o.category&&!this.category&&(this.category=X(o.category)),!u){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=u;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0,await this.sendIntegrationTest(u)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let n={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,n)&&this.clearConnectionTest(e)}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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(V(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=v("event"),r={...n,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:l(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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let o=Y(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let i=Y(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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=we(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(n),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let u=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};u&&(d.keepalive=!0);let a=await i(e,d);if(!a.ok){let p="";try{p=await a.text()}catch{p=""}console.error(`[DevInspector] Falha ao enviar evento: ${a.status} ${a.statusText}`,p)}return a.ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},J="__DEVINSPECT_AUDIT_CORE_INSTANCE__",W=typeof globalThis<"u"?globalThis:{},h=W[J]||new C;W[J]=h;var y=class{handleError(e){let n=e instanceof Error?e:new Error(String(e));h.captureError(n,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""})}};y.\u0275fac=t=>new(t||y);y.\u0275prov=(0,Z.\u0275\u0275defineInjectable)({token:y,factory:y.\u0275fac,providedIn:"root"});var te=(t,e)=>{let n=t.urlWithParams||t.url||"";if(n&&h.isIngestUrl(n))return e(t);let i=h.createRequestId(),r=h.createTraceId(),s=h.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":i,"x-devinspector-trace-id":r,"x-devinspector-span-id":s}}),u=typeof performance<"u"?performance.now():Date.now();return e(o).pipe((0,ee.tap)({next:d=>{if(!(d instanceof E.HttpResponse))return;let a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-u)),p=d.status||0;(p>=400||a>=h.getSlowThresholdMs())&&h.captureRequest({method:t.method||"GET",url:n,statusCode:p,durationMs:a,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),h.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:p,durationMs:a,requestId:i,traceId:r,spanId:s}})},error:d=>{let a=d instanceof E.HttpErrorResponse?d:null,p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-u)),m=a?.status||0,g=a?.message||a?.statusText||"Erro de rede no cliente";h.captureRequest({method:t.method||"GET",url:n,statusCode:m,durationMs:p,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),h.captureException(new Error(`HTTP Error ${m}: ${g}`),{url:n,method:t.method||"GET",statusCode:m,statusText:a?.statusText||"",type:"angular_network_error",requestId:i,traceId:r,spanId:s}),h.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:m,durationMs:p,requestId:i,traceId:r,spanId:s,error:g}})}}))},be=te;0&&(module.exports={AuditAngularErrorHandler,audit,auditInterceptor,devInspectorInterceptor});
|
package/dist/angular.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{\u0275\u0275defineInjectable as pe}from"@angular/core";import{HttpResponse as le,HttpErrorResponse as he}from"@angular/common/http";import{tap as fe}from"rxjs/operators";var C="9.3.6",Y=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),J=new Set(["frontend","backend","fullstack","mobile"]),U="https://api.devinspector.com.br/api/ingest/track",_="https://api.devinspector.com.br/api/ingest/apm",x=50,v=1e4,W=5e4,A=4e3,P=4e3,N=2e3,L=1e3,Q=200,y=200,Z=100,ee=200,te=100,ne=6,O=1e4,re=5e3,H=3,ie=1e3,se=1e4,oe=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ae(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return oe.some(n=>e.includes(n))}function f(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>v?`${t.slice(0,v)}...[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>=ne)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>f(s,e+1,n));let i=t,r={};for(let[s,o]of Object.entries(i)){if(ae(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,n)}return r}finally{n.delete(t)}}function z(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function B(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function G(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(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 u(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function de(t){return String(t??"").trim().slice(0,200)}function ue(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function I(t,e=y){return u(t,e)}function j(t){let e=I(t,50);if(e&&Y.has(e))return e}function $(t){let e=I(t,50);if(e&&J.has(e))return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(t){return f(t)}function K(t){let e=Math.max(0,t-1);return Math.min(ie*2**e,se)}function ce(t,e){return setTimeout(t,Math.max(0,e))}var M=class{constructor(){this.apiKey="";this.endpoint=U;this.apmEndpoint=_;this.environment="production";this.sdkVersion=C;this.slowThresholdMs=300;this.requestTimeoutMs=O;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()||U,this.apmEndpoint=e.apmEndpoint?.trim()||_,this.environment=u(e.environment,Z)||"production",this.release=u(e.release,ee),this.technology=j(e.technology),this.category=$(e.category),this.installationId=I(e.installationId,y),this.sdkVersion=I(e.sdkVersion,te)||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):O,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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>x&&(this.breadcrumbs=this.breadcrumbs.slice(-x))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),c=n.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===n.origin&&o===c||s===i.origin&&o===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let n=B(e.method)||"GET",i=u(e.url,A);if(!i)return;let r=G(e.statusCode)??0,s=R(e.durationMs)??0,o=V(e.ip),c=u(e.path,P),a=u(e.route,N),d=u(e.userAgent,L),h=u(e.contentType,Q),m=e.query?f(e.query):void 0,g=e.requestBody!==void 0?f(e.requestBody):void 0,w={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:s,...c?{path:c}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...h?{contentType:h}:{},...o?{ip:o}:{},...m?{query:m}:{},...g!==void 0?{requestBody:g}:{},...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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(w)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:u(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:u(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(r)})}captureMetric(e,n,i={},r={}){let s=de(e);if(!s)return Promise.resolve();let o;try{o=ue(n)}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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},s=B(r.method),o=G(r.statusCode??r.status),c=R(r.durationMs),a=V(r.ip),d=u(r.url,A),h=u(r.path,P),m=u(r.route,N),g=u(r.userAgent,L),w=u(r.contentType,Q),E=u(r.requestId,y),k=u(r.traceId,y),D=u(r.spanId,y),q=r.query!==void 0?f(r.query):void 0,S=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,W)||"",...d?{url:d}:{},...h?{path:h}:{},...m?{route:m}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...g?{userAgent:g}:{},...w?{contentType:w}:{},...q?{query:q}:{},...S!==void 0?{requestBody:S}:{},...E?{requestId:E}:{},...k?{traceId:k}:{},...D?{spanId:D}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(z(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<re){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=I(o.connectionTestId??o.testId,y),a=I(o.installationId,y);if(a&&!this.installationId&&(this.installationId=a),o.technology&&!this.technology&&(this.technology=j(o.technology)),o.category&&!this.category&&(this.category=$(o.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let d=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d: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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(z(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...n,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:p(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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,p(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=H){this.sendQueue.shift(),e.resolve();continue}let o=K(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=H){this.sendQueue.shift(),e.resolve();continue}let i=K(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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=ce(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(n),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)}}},F="__DEVINSPECT_AUDIT_CORE_INSTANCE__",X=typeof globalThis<"u"?globalThis:{},l=X[F]||new M;X[F]=l;var T=class{handleError(e){let n=e instanceof Error?e:new Error(String(e));l.captureError(n,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""})}};T.\u0275fac=t=>new(t||T);T.\u0275prov=pe({token:T,factory:T.\u0275fac,providedIn:"root"});var me=(t,e)=>{let n=t.urlWithParams||t.url||"";if(n&&l.isIngestUrl(n))return e(t);let i=l.createRequestId(),r=l.createTraceId(),s=l.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":i,"x-devinspector-trace-id":r,"x-devinspector-span-id":s}}),c=typeof performance<"u"?performance.now():Date.now();return e(o).pipe(fe({next:a=>{if(!(a instanceof le))return;let d=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),h=a.status||0;(h>=400||d>=l.getSlowThresholdMs())&&l.captureRequest({method:t.method||"GET",url:n,statusCode:h,durationMs:d,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),l.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:h,durationMs:d,requestId:i,traceId:r,spanId:s}})},error:a=>{let d=a instanceof he?a:null,h=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-c)),m=d?.status||0,g=d?.message||d?.statusText||"Erro de rede no cliente";l.captureRequest({method:t.method||"GET",url:n,statusCode:m,durationMs:h,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),l.captureException(new Error(`HTTP Error ${m}: ${g}`),{url:n,method:t.method||"GET",statusCode:m,statusText:d?.statusText||"",type:"angular_network_error",requestId:i,traceId:r,spanId:s}),l.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:m,durationMs:h,requestId:i,traceId:r,spanId:s,error:g}})}}))},Me=me;export{T as AuditAngularErrorHandler,l as audit,Me as auditInterceptor,me as devInspectorInterceptor};
|
|
1
|
+
import{\u0275\u0275defineInjectable as pe}from"@angular/core";import{HttpResponse as le,HttpErrorResponse as he}from"@angular/common/http";import{tap as fe}from"rxjs/operators";var S="9.3.8",J=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),W=new Set(["frontend","backend","fullstack","mobile"]),_="https://api.devinspector.com.br/api/ingest/track",U="https://api.devinspector.com.br/api/ingest/apm",x=50,w=1e4,Z=5e4,A=4e3,P=4e3,N=2e3,L=1e3,Q=200,y=200,ee=100,te=200,ne=100,re=6,O=1e4,z=5e3,H=3,ie=1e3,se=1e4,oe=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ae(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return oe.some(n=>e.includes(n))}function f(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>w?`${t.slice(0,w)}...[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(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(s=>f(s,e+1,n));let i=t,r={};for(let[s,o]of Object.entries(i)){if(ae(s)){r[s]="[REDACTED]";continue}r[s]=f(o,e+1,n)}return r}finally{n.delete(t)}}function B(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function G(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function V(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(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 c(t,e=w){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function de(t){return String(t??"").trim().slice(0,200)}function ce(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function I(t,e=y){return c(t,e)}function j(t){let e=I(t,50);if(e&&J.has(e))return e}function K(t){let e=I(t,50);if(e&&W.has(e))return e}function v(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 f(t)}function F(t){let e=Math.max(0,t-1);return Math.min(ie*2**e,se)}function ue(t,e){return setTimeout(t,Math.max(0,e))}var M=class{constructor(){this.apiKey="";this.endpoint=_;this.apmEndpoint=U;this.environment="production";this.sdkVersion=S;this.slowThresholdMs=300;this.requestTimeoutMs=O;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()||U,this.environment=c(e.environment,ee)||"production",this.release=c(e.release,te),this.technology=j(e.technology),this.category=K(e.category),this.installationId=I(e.installationId,y)||v("di"),this.sdkVersion=I(e.sdkVersion,ne)||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):O,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.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>x&&(this.breadcrumbs=this.breadcrumbs.slice(-x))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),s=r.origin,o=r.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),d=i.pathname.replace(/\/$/,"");return s===n.origin&&o===u||s===i.origin&&o===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return v("req")}createTraceId(){return v("trace")}createSpanId(){return v("span")}async captureRequest(e){let n=G(e.method)||"GET",i=c(e.url,A);if(!i)return;let r=V(e.statusCode)??0,s=R(e.durationMs)??0,o=$(e.ip),u=c(e.path,P),d=c(e.route,N),a=c(e.userAgent,L),p=c(e.contentType,Q),m=e.query?f(e.query):void 0,g=e.requestBody!==void 0?f(e.requestBody):void 0,b={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:s,...u?{path:u}:{},...d?{route:d}:{},...a?{userAgent:a}:{},...p?{contentType:p}:{},...o?{ip:o}:{},...m?{query:m}:{},...g!==void 0?{requestBody:g}:{},...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(b)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:c(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:c(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,n,i={},r={}){let s=de(e);if(!s)return Promise.resolve();let o;try{o=ce(n)}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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},s=G(r.method),o=V(r.statusCode??r.status),u=R(r.durationMs),d=$(r.ip),a=c(r.url,A),p=c(r.path,P),m=c(r.route,N),g=c(r.userAgent,L),b=c(r.contentType,Q),E=c(r.requestId,y),k=c(r.traceId,y),C=c(r.spanId,y),D=r.query!==void 0?f(r.query):void 0,q=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,w),stackTrace:e?.stack?.slice(0,Z)||"",...a?{url:a}:{},...p?{path:p}:{},...m?{route:m}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...u!==void 0?{durationMs:u}:{},...d?{ip:d}:{},...g?{userAgent:g}:{},...b?{contentType:b}:{},...D?{query:D}:{},...q!==void 0?{requestBody:q}:{},...E?{requestId:E}:{},...k?{traceId:k}:{},...C?{spanId:C}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(B(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,w),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},z)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<z){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let s=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),u=I(o.connectionTestId??o.testId,y),d=I(o.installationId,y);if(d&&!this.installationId&&(this.installationId=d),o.technology&&!this.technology&&(this.technology=j(o.technology)),o.category&&!this.category&&(this.category=K(o.category)),!u){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=u;let a=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0,await this.sendIntegrationTest(u)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let n={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,n)&&this.clearConnectionTest(e)}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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(B(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=v("event"),r={...n,...this.getIntegrationContext(),eventId:i},s={id:i,endpoint:e,payload:l(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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=H){this.sendQueue.shift(),e.resolve();continue}let o=F(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=H){this.sendQueue.shift(),e.resolve();continue}let i=F(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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=ue(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(n),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.abort()},this.requestTimeoutMs));let u=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:s?.signal};u&&(d.keepalive=!0);let a=await i(e,d);if(!a.ok){let p="";try{p=await a.text()}catch{p=""}console.error(`[DevInspector] Falha ao enviar evento: ${a.status} ${a.statusText}`,p)}return a.ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},h=Y[X]||new M;Y[X]=h;var T=class{handleError(e){let n=e instanceof Error?e:new Error(String(e));h.captureError(n,{framework:"Angular",platform:typeof window<"u"?"browser":"server",url:typeof window<"u"?window.location.href:""})}};T.\u0275fac=t=>new(t||T);T.\u0275prov=pe({token:T,factory:T.\u0275fac,providedIn:"root"});var me=(t,e)=>{let n=t.urlWithParams||t.url||"";if(n&&h.isIngestUrl(n))return e(t);let i=h.createRequestId(),r=h.createTraceId(),s=h.createSpanId(),o=t.clone({setHeaders:{"x-devinspector-request-id":i,"x-devinspector-trace-id":r,"x-devinspector-span-id":s}}),u=typeof performance<"u"?performance.now():Date.now();return e(o).pipe(fe({next:d=>{if(!(d instanceof le))return;let a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-u)),p=d.status||0;(p>=400||a>=h.getSlowThresholdMs())&&h.captureRequest({method:t.method||"GET",url:n,statusCode:p,durationMs:a,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),h.addBreadcrumb({type:"http",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:p,durationMs:a,requestId:i,traceId:r,spanId:s}})},error:d=>{let a=d instanceof he?d:null,p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-u)),m=a?.status||0,g=a?.message||a?.statusText||"Erro de rede no cliente";h.captureRequest({method:t.method||"GET",url:n,statusCode:m,durationMs:p,route:t.url,requestId:i,traceId:r,spanId:s,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}),h.captureException(new Error(`HTTP Error ${m}: ${g}`),{url:n,method:t.method||"GET",statusCode:m,statusText:a?.statusText||"",type:"angular_network_error",requestId:i,traceId:r,spanId:s}),h.addBreadcrumb({type:"http_error",message:`${t.method||"GET"} ${n}`,metadata:{statusCode:m,durationMs:p,requestId:i,traceId:r,spanId:s,error:g}})}}))},Me=me;export{T as AuditAngularErrorHandler,h as audit,Me as auditInterceptor,me as devInspectorInterceptor};
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var R=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(t,e)=>{for(var r in e)R(t,r,{get:e[r],enumerable:!0})},te=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of W(e))!Z.call(t,n)&&n!==r&&R(t,n,{get:()=>e[n],enumerable:!(i=J(e,n))||i.enumerable});return t};var ne=t=>te(R({},"__esModule",{value:!0}),t);var Te={};ee(Te,{AuditCore:()=>E,DEVINSPECTOR_SDK_VERSION:()=>A,audit:()=>h,coreAuditFetch:()=>Y});module.exports=ne(Te);var A="9.3.6",re=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ie=new Set(["frontend","backend","fullstack","mobile"]),P="https://api.devinspector.com.br/api/ingest/track",x="https://api.devinspector.com.br/api/ingest/apm",N=50,v=1e4,se=5e4,M=4e3,Q=4e3,L=2e3,O=1e3,z=200,I=200,oe=100,ae=200,ue=100,ce=6,B=1e4,de=5e3,G=3,pe=1e3,le=1e4,he=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function fe(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return he.some(r=>e.includes(r))}function f(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>v?`${t.slice(0,v)}...[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>=ce)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=>f(o,e+1,r));let i=t,n={};for(let[o,s]of Object.entries(i)){if(fe(o)){n[o]="[REDACTED]";continue}n[o]=f(s,e+1,r)}return n}finally{r.delete(t)}}function k(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function q(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function V(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function D(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 c(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function me(t){return String(t??"").trim().slice(0,200)}function ge(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=I){return c(t,e)}function j(t){let e=b(t,50);if(e&&re.has(e))return e}function H(t){let e=b(t,50);if(e&&ie.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 l(t){return f(t)}function F(t){let e=Math.max(0,t-1);return Math.min(pe*2**e,le)}function ye(t,e){return setTimeout(t,Math.max(0,e))}var E=class{constructor(){this.apiKey="";this.endpoint=P;this.apmEndpoint=x;this.environment="production";this.sdkVersion=A;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()||P,this.apmEndpoint=e.apmEndpoint?.trim()||x,this.environment=c(e.environment,oe)||"production",this.release=c(e.release,ae),this.technology=j(e.technology),this.category=H(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,ue)||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):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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?f(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>N&&(this.breadcrumbs=this.breadcrumbs.slice(-N))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,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),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),o=n.origin,s=n.pathname.replace(/\/$/,""),u=r.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===r.origin&&s===u||o===i.origin&&s===a}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=q(e.method)||"GET",i=c(e.url,M);if(!i)return;let n=V(e.statusCode)??0,o=D(e.durationMs)??0,s=K(e.ip),u=c(e.path,Q),a=c(e.route,L),d=c(e.userAgent,O),y=c(e.contentType,z),g=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(n>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:o,...u?{path:u}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...s?{ip:s}:{},...g?{query:g}:{},...p!==void 0?{requestBody:p}:{},...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(m)})}captureDbQuery(e){let r=String(e.operation||"").trim().slice(0,500);if(!r)return Promise.resolve();let i=D(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:c(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:c(e.url,M),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(n)})}captureMetric(e,r,i={},n={}){let o=me(e);if(!o)return Promise.resolve();let s;try{s=ge(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...i,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},o=q(n.method),s=V(n.statusCode??n.status),u=D(n.durationMs),a=K(n.ip),d=c(n.url,M),y=c(n.path,Q),g=c(n.route,L),p=c(n.userAgent,O),m=c(n.contentType,z),T=c(n.requestId,I),C=c(n.traceId,I),S=c(n.spanId,I),U=n.query!==void 0?f(n.query):void 0,_=n.requestBody!==void 0?f(n.requestBody):void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.url,delete n.path,delete n.route,delete n.userAgent,delete n.contentType,delete n.requestId,delete n.traceId,delete n.spanId,delete n.query,delete n.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,se)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...u!==void 0?{durationMs:u}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...U?{query:U}:{},..._!==void 0?{requestBody:_}:{},...T?{requestId:T}:{},...C?{traceId:C}:{},...S?{spanId:S}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(k(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),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.category?{category:this.category}:{},...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<de){this.connectionTestExpiresAt&&r>=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 r=typeof fetch=="function"?fetch:void 0;if(!r)return;let i,n;try{typeof AbortController<"u"&&(i=new AbortController,n=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),u=b(s.connectionTestId??s.testId,I),a=b(s.installationId,I);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=j(s.technology)),s.category&&!this.category&&(this.category=H(s.category)),!u){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=u;let d=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{n!==void 0&&clearTimeout(n)}}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?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:r.lineno,column:r.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(k(r.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=w("event"),n={...r,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:l(n),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,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 i={...e.payload,...this.getIntegrationContext(),eventId:e.id},n=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(i))){this.sendQueue.shift(),n&&this.clearConnectionTest(n),e.resolve();continue}if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let s=F(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let i=F(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 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=ye(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let n=f(r),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let u=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:o?.signal};return u&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",$=typeof globalThis<"u"?globalThis:{},h=$[X]||new E;$[X]=h;async function Y(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=q(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&h.isIngestUrl(n))return i(t,e);let s=h.createRequestId(),u=h.createTraceId(),a=h.createSpanId(),d=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));d.set("x-devinspector-request-id",s),d.set("x-devinspector-trace-id",u),d.set("x-devinspector-span-id",a);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=p.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:s,traceId:u,spanId:a}}),h.captureRequest({method:o,url:n,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,contentType:T,requestId:s,traceId:u,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${o} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:u,spanId:a}}),h.captureRequest({method:o,url:n,statusCode:0,durationMs:m,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:s,traceId:u,spanId:a});let T=p instanceof Error?p:new Error(k(p));throw h.captureError(T,{url:n,method:o,path:(()=>{try{return new URL(n).pathname}catch{return}})(),type:r.errorType||"network_error",requestId:s,traceId:u,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent}),p}}0&&(module.exports={AuditCore,DEVINSPECTOR_SDK_VERSION,audit,coreAuditFetch});
|
|
1
|
+
"use strict";var R=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(t,e)=>{for(var n in e)R(t,n,{get:e[n],enumerable:!0})},ne=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Z(e))!ee.call(t,r)&&r!==n&&R(t,r,{get:()=>e[r],enumerable:!(i=W(e,r))||i.enumerable});return t};var re=t=>ne(R({},"__esModule",{value:!0}),t);var Te={};te(Te,{AuditCore:()=>E,DEVINSPECTOR_SDK_VERSION:()=>A,audit:()=>h,coreAuditFetch:()=>J});module.exports=re(Te);var A="9.3.8",ie=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),se=new Set(["frontend","backend","fullstack","mobile"]),P="https://api.devinspector.com.br/api/ingest/track",x="https://api.devinspector.com.br/api/ingest/apm",N=50,w=1e4,oe=5e4,C=4e3,Q=4e3,L=2e3,O=1e3,z=200,I=200,ae=100,ce=200,de=100,ue=6,B=1e4,V=5e3,G=3,pe=1e3,le=1e4,he=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function me(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return he.some(n=>e.includes(n))}function f(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>w?`${t.slice(0,w)}...[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>=ue)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>f(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(me(o)){r[o]="[REDACTED]";continue}r[o]=f(s,e+1,n)}return r}finally{n.delete(t)}}function k(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function D(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function K(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function M(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function j(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function u(t,e=w){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function fe(t){return String(t??"").trim().slice(0,200)}function ge(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function v(t,e=I){return u(t,e)}function H(t){let e=v(t,50);if(e&&ie.has(e))return e}function F(t){let e=v(t,50);if(e&&se.has(e))return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function l(t){return f(t)}function $(t){let e=Math.max(0,t-1);return Math.min(pe*2**e,le)}function ye(t,e){return setTimeout(t,Math.max(0,e))}var E=class{constructor(){this.apiKey="";this.endpoint=P;this.apmEndpoint=x;this.environment="production";this.sdkVersion=A;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()||P,this.apmEndpoint=e.apmEndpoint?.trim()||x,this.environment=u(e.environment,ae)||"production",this.release=u(e.release,ce),this.technology=H(e.technology),this.category=F(e.category),this.installationId=v(e.installationId,I)||b("di"),this.sdkVersion=v(e.sdkVersion,de)||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):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.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>N&&(this.breadcrumbs=this.breadcrumbs.slice(-N))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),a=n.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===n.origin&&s===a||o===i.origin&&s===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let n=D(e.method)||"GET",i=u(e.url,C);if(!i)return;let r=K(e.statusCode)??0,o=M(e.durationMs)??0,s=j(e.ip),a=u(e.path,Q),c=u(e.route,L),d=u(e.userAgent,O),m=u(e.contentType,z),y=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,g={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:o,...a?{path:a}:{},...c?{route:c}:{},...d?{userAgent:d}:{},...m?{contentType:m}:{},...s?{ip:s}:{},...y?{query:y}:{},...p!==void 0?{requestBody:p}:{},...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(g)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=M(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:u(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:u(e.url,C),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,n,i={},r={}){let o=fe(e);if(!o)return Promise.resolve();let s;try{s=ge(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},o=D(r.method),s=K(r.statusCode??r.status),a=M(r.durationMs),c=j(r.ip),d=u(r.url,C),m=u(r.path,Q),y=u(r.route,L),p=u(r.userAgent,O),g=u(r.contentType,z),T=u(r.requestId,I),q=u(r.traceId,I),S=u(r.spanId,I),U=r.query!==void 0?f(r.query):void 0,_=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,w),stackTrace:e?.stack?.slice(0,oe)||"",...d?{url:d}:{},...m?{path:m}:{},...y?{route:y}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...c?{ip:c}:{},...p?{userAgent:p}:{},...g?{contentType:g}:{},...U?{query:U}:{},..._!==void 0?{requestBody:_}:{},...T?{requestId:T}:{},...q?{traceId:q}:{},...S?{spanId:S}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(k(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,w),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},V)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<V){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),a=v(s.connectionTestId??s.testId,I),c=v(s.installationId,I);if(c&&!this.installationId&&(this.installationId=c),s.technology&&!this.technology&&(this.technology=H(s.technology)),s.category&&!this.category&&(this.category=F(s.category)),!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0,await this.sendIntegrationTest(a)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let n={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,n)&&this.clearConnectionTest(e)}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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(k(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:l(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let s=$(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let i=$(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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=ye(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};a&&(c.keepalive=!0);let d=await i(e,c);if(!d.ok){let m="";try{m=await d.text()}catch{m=""}console.error(`[DevInspector] Falha ao enviar evento: ${d.status} ${d.statusText}`,m)}return d.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},h=Y[X]||new E;Y[X]=h;async function J(t,e,n={}){let i=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=D(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(t,e);let s=h.createRequestId(),a=h.createTraceId(),c=h.createSpanId(),d=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));d.set("x-devinspector-request-id",s),d.set("x-devinspector-trace-id",a),d.set("x-devinspector-span-id",c);let m={...e,headers:d},y=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,m),g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y)),T=p.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:g,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:p.status,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:c}),p}catch(p){let g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y));h.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:g,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:0,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:a,spanId:c});let T=p instanceof Error?p:new Error(k(p));throw h.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:a,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),p}}0&&(module.exports={AuditCore,DEVINSPECTOR_SDK_VERSION,audit,coreAuditFetch});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
type UnknownRecord = Record<string, unknown>;
|
|
2
2
|
type DevInspectorTechnology = "angular" | "vanilla-js" | "react" | "vue" | "svelte" | "node" | "python" | "java" | "csharp" | "php" | "nextjs" | "react-native";
|
|
3
3
|
type DevInspectorCategory = "frontend" | "backend" | "fullstack" | "mobile";
|
|
4
|
-
declare const DEVINSPECTOR_SDK_VERSION = "9.3.
|
|
4
|
+
declare const DEVINSPECTOR_SDK_VERSION = "9.3.8";
|
|
5
5
|
interface AuditUser {
|
|
6
6
|
id?: string;
|
|
7
7
|
email?: string;
|
|
@@ -64,7 +64,7 @@ interface CustomMetricData {
|
|
|
64
64
|
traceId?: string;
|
|
65
65
|
spanId?: string;
|
|
66
66
|
}
|
|
67
|
-
type AuditEventType = "error" | "message" | "request_metric" | "db_query" | "custom_metric";
|
|
67
|
+
type AuditEventType = "error" | "message" | "request_metric" | "db_query" | "custom_metric" | "integration_test";
|
|
68
68
|
declare class AuditCore {
|
|
69
69
|
private apiKey;
|
|
70
70
|
private endpoint;
|
|
@@ -89,6 +89,7 @@ declare class AuditCore {
|
|
|
89
89
|
private connectionTestExpiresAt?;
|
|
90
90
|
private connectionTestLastCheckedAt;
|
|
91
91
|
private connectionTestRequest?;
|
|
92
|
+
private pendingConnectionTestTimer?;
|
|
92
93
|
init(options: InitOptions): void;
|
|
93
94
|
getApiKey(): string;
|
|
94
95
|
getEndpoint(): string;
|
|
@@ -128,8 +129,10 @@ declare class AuditCore {
|
|
|
128
129
|
flush(): Promise<void>;
|
|
129
130
|
private getIntegrationContext;
|
|
130
131
|
private getPendingConnectionTestEndpoint;
|
|
132
|
+
private startPendingConnectionTestPolling;
|
|
131
133
|
private refreshPendingConnectionTest;
|
|
132
134
|
private fetchPendingConnectionTest;
|
|
135
|
+
private sendIntegrationTest;
|
|
133
136
|
private clearConnectionTest;
|
|
134
137
|
private attachGlobalListeners;
|
|
135
138
|
private sendError;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
type UnknownRecord = Record<string, unknown>;
|
|
2
2
|
type DevInspectorTechnology = "angular" | "vanilla-js" | "react" | "vue" | "svelte" | "node" | "python" | "java" | "csharp" | "php" | "nextjs" | "react-native";
|
|
3
3
|
type DevInspectorCategory = "frontend" | "backend" | "fullstack" | "mobile";
|
|
4
|
-
declare const DEVINSPECTOR_SDK_VERSION = "9.3.
|
|
4
|
+
declare const DEVINSPECTOR_SDK_VERSION = "9.3.8";
|
|
5
5
|
interface AuditUser {
|
|
6
6
|
id?: string;
|
|
7
7
|
email?: string;
|
|
@@ -64,7 +64,7 @@ interface CustomMetricData {
|
|
|
64
64
|
traceId?: string;
|
|
65
65
|
spanId?: string;
|
|
66
66
|
}
|
|
67
|
-
type AuditEventType = "error" | "message" | "request_metric" | "db_query" | "custom_metric";
|
|
67
|
+
type AuditEventType = "error" | "message" | "request_metric" | "db_query" | "custom_metric" | "integration_test";
|
|
68
68
|
declare class AuditCore {
|
|
69
69
|
private apiKey;
|
|
70
70
|
private endpoint;
|
|
@@ -89,6 +89,7 @@ declare class AuditCore {
|
|
|
89
89
|
private connectionTestExpiresAt?;
|
|
90
90
|
private connectionTestLastCheckedAt;
|
|
91
91
|
private connectionTestRequest?;
|
|
92
|
+
private pendingConnectionTestTimer?;
|
|
92
93
|
init(options: InitOptions): void;
|
|
93
94
|
getApiKey(): string;
|
|
94
95
|
getEndpoint(): string;
|
|
@@ -128,8 +129,10 @@ declare class AuditCore {
|
|
|
128
129
|
flush(): Promise<void>;
|
|
129
130
|
private getIntegrationContext;
|
|
130
131
|
private getPendingConnectionTestEndpoint;
|
|
132
|
+
private startPendingConnectionTestPolling;
|
|
131
133
|
private refreshPendingConnectionTest;
|
|
132
134
|
private fetchPendingConnectionTest;
|
|
135
|
+
private sendIntegrationTest;
|
|
133
136
|
private clearConnectionTest;
|
|
134
137
|
private attachGlobalListeners;
|
|
135
138
|
private sendError;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var M="9.3.6",$=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),Y=new Set(["frontend","backend","fullstack","mobile"]),_="https://api.devinspector.com.br/api/ingest/track",P="https://api.devinspector.com.br/api/ingest/apm",x=50,v=1e4,J=5e4,A=4e3,N=4e3,Q=2e3,L=1e3,O=200,I=200,W=100,Z=200,ee=100,te=6,z=1e4,ne=5e3,B=3,re=1e3,ie=1e4,se=["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 se.some(n=>e.includes(n))}function f(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>v?`${t.slice(0,v)}...[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>=te)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>f(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(oe(o)){r[o]="[REDACTED]";continue}r[o]=f(s,e+1,n)}return r}finally{n.delete(t)}}function D(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function k(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function G(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(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 c(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ae(t){return String(t??"").trim().slice(0,200)}function ue(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=I){return c(t,e)}function K(t){let e=b(t,50);if(e&&$.has(e))return e}function j(t){let e=b(t,50);if(e&&Y.has(e))return e}function E(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 f(t)}function H(t){let e=Math.max(0,t-1);return Math.min(re*2**e,ie)}function ce(t,e){return setTimeout(t,Math.max(0,e))}var w=class{constructor(){this.apiKey="";this.endpoint=_;this.apmEndpoint=P;this.environment="production";this.sdkVersion=M;this.slowThresholdMs=300;this.requestTimeoutMs=z;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()||P,this.environment=c(e.environment,W)||"production",this.release=c(e.release,Z),this.technology=K(e.technology),this.category=j(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,ee)||M,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):z,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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>x&&(this.breadcrumbs=this.breadcrumbs.slice(-x))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===n.origin&&s===u||o===i.origin&&s===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return E("req")}createTraceId(){return E("trace")}createSpanId(){return E("span")}async captureRequest(e){let n=k(e.method)||"GET",i=c(e.url,A);if(!i)return;let r=G(e.statusCode)??0,o=R(e.durationMs)??0,s=V(e.ip),u=c(e.path,N),a=c(e.route,Q),d=c(e.userAgent,L),y=c(e.contentType,O),g=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:o,...u?{path:u}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...s?{ip:s}:{},...g?{query:g}:{},...p!==void 0?{requestBody:p}:{},...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(m)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:c(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:c(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,n,i={},r={}){let o=ae(e);if(!o)return Promise.resolve();let s;try{s=ue(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},o=k(r.method),s=G(r.statusCode??r.status),u=R(r.durationMs),a=V(r.ip),d=c(r.url,A),y=c(r.path,N),g=c(r.route,Q),p=c(r.userAgent,L),m=c(r.contentType,O),T=c(r.requestId,I),q=c(r.traceId,I),C=c(r.spanId,I),S=r.query!==void 0?f(r.query):void 0,U=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,J)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...u!==void 0?{durationMs:u}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...S?{query:S}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...q?{traceId:q}:{},...C?{spanId:C}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(D(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<ne){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),u=b(s.connectionTestId??s.testId,I),a=b(s.installationId,I);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=K(s.technology)),s.category&&!this.category&&(this.category=j(s.category)),!u){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=u;let d=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d: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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(D(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=E("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:l(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=B){this.sendQueue.shift(),e.resolve();continue}let s=H(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=B){this.sendQueue.shift(),e.resolve();continue}let i=H(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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=ce(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let u=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:o?.signal};return u&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},F="__DEVINSPECT_AUDIT_CORE_INSTANCE__",X=typeof globalThis<"u"?globalThis:{},h=X[F]||new w;X[F]=h;async function de(t,e,n={}){let i=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=k(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(t,e);let s=h.createRequestId(),u=h.createTraceId(),a=h.createSpanId(),d=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));d.set("x-devinspector-request-id",s),d.set("x-devinspector-trace-id",u),d.set("x-devinspector-span-id",a);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=p.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:s,traceId:u,spanId:a}}),h.captureRequest({method:o,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:u,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:u,spanId:a}}),h.captureRequest({method:o,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:u,spanId:a});let T=p instanceof Error?p:new Error(D(p));throw h.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:u,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),p}}export{w as AuditCore,M as DEVINSPECTOR_SDK_VERSION,h as audit,de as coreAuditFetch};
|
|
1
|
+
var C="9.3.8",Y=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),J=new Set(["frontend","backend","fullstack","mobile"]),_="https://api.devinspector.com.br/api/ingest/track",P="https://api.devinspector.com.br/api/ingest/apm",x=50,w=1e4,W=5e4,A=4e3,N=4e3,Q=2e3,L=1e3,O=200,I=200,Z=100,ee=200,te=100,ne=6,z=1e4,B=5e3,V=3,re=1e3,ie=1e4,se=["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 se.some(n=>e.includes(n))}function f(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>w?`${t.slice(0,w)}...[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>=ne)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>f(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(oe(o)){r[o]="[REDACTED]";continue}r[o]=f(s,e+1,n)}return r}finally{n.delete(t)}}function M(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=f(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function k(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function G(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(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 u(t,e=w){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ae(t){return String(t??"").trim().slice(0,200)}function ce(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function v(t,e=I){return u(t,e)}function j(t){let e=v(t,50);if(e&&Y.has(e))return e}function H(t){let e=v(t,50);if(e&&J.has(e))return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function l(t){return f(t)}function F(t){let e=Math.max(0,t-1);return Math.min(re*2**e,ie)}function de(t,e){return setTimeout(t,Math.max(0,e))}var E=class{constructor(){this.apiKey="";this.endpoint=_;this.apmEndpoint=P;this.environment="production";this.sdkVersion=C;this.slowThresholdMs=300;this.requestTimeoutMs=z;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()||P,this.environment=u(e.environment,Z)||"production",this.release=u(e.release,ee),this.technology=j(e.technology),this.category=H(e.category),this.installationId=v(e.installationId,I)||b("di"),this.sdkVersion=v(e.sdkVersion,te)||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):z,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.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>x&&(this.breadcrumbs=this.breadcrumbs.slice(-x))}getBreadcrumbs(){return this.breadcrumbs.map(e=>l(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:l(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),a=n.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===n.origin&&s===a||o===i.origin&&s===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let n=k(e.method)||"GET",i=u(e.url,A);if(!i)return;let r=G(e.statusCode)??0,o=R(e.durationMs)??0,s=K(e.ip),a=u(e.path,N),c=u(e.route,Q),d=u(e.userAgent,L),h=u(e.contentType,O),y=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,g={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:o,...a?{path:a}:{},...c?{route:c}:{},...d?{userAgent:d}:{},...h?{contentType:h}:{},...s?{ip:s}:{},...y?{query:y}:{},...p!==void 0?{requestBody:p}:{},...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(g)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:u(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:u(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,n,i={},r={}){let o=ae(e);if(!o)return Promise.resolve();let s;try{s=ce(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},o=k(r.method),s=G(r.statusCode??r.status),a=R(r.durationMs),c=K(r.ip),d=u(r.url,A),h=u(r.path,N),y=u(r.route,Q),p=u(r.userAgent,L),g=u(r.contentType,O),T=u(r.requestId,I),D=u(r.traceId,I),q=u(r.spanId,I),S=r.query!==void 0?f(r.query):void 0,U=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,w),stackTrace:e?.stack?.slice(0,W)||"",...d?{url:d}:{},...h?{path:h}:{},...y?{route:y}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...c?{ip:c}:{},...p?{userAgent:p}:{},...g?{contentType:g}:{},...S?{query:S}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...D?{traceId:D}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(M(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,w),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},B)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<B){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),a=v(s.connectionTestId??s.testId,I),c=v(s.installationId,I);if(c&&!this.installationId&&(this.installationId=c),s.technology&&!this.technology&&(this.technology=j(s.technology)),s.category&&!this.category&&(this.category=H(s.category)),!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0,await this.sendIntegrationTest(a)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let n={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,n)&&this.clearConnectionTest(e)}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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(M(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:l(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=V){this.sendQueue.shift(),e.resolve();continue}let s=F(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=V){this.sendQueue.shift(),e.resolve();continue}let i=F(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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=de(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};a&&(c.keepalive=!0);let d=await i(e,c);if(!d.ok){let h="";try{h=await d.text()}catch{h=""}console.error(`[DevInspector] Falha ao enviar evento: ${d.status} ${d.statusText}`,h)}return d.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},$="__DEVINSPECT_AUDIT_CORE_INSTANCE__",X=typeof globalThis<"u"?globalThis:{},m=X[$]||new E;X[$]=m;async function ue(t,e,n={}){let i=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=k(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&m.isIngestUrl(r))return i(t,e);let s=m.createRequestId(),a=m.createTraceId(),c=m.createSpanId(),d=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));d.set("x-devinspector-request-id",s),d.set("x-devinspector-trace-id",a),d.set("x-devinspector-span-id",c);let h={...e,headers:d},y=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,h),g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y)),T=p.headers.get("content-type")||void 0;return m.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:g,requestId:s,traceId:a,spanId:c}}),m.captureRequest({method:o,url:r,statusCode:p.status,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:c}),p}catch(p){let g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y));m.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:g,requestId:s,traceId:a,spanId:c}}),m.captureRequest({method:o,url:r,statusCode:0,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:a,spanId:c});let T=p instanceof Error?p:new Error(M(p));throw m.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:a,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),p}}export{E as AuditCore,C as DEVINSPECTOR_SDK_VERSION,m as audit,ue as coreAuditFetch};
|
package/dist/next.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var E=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var te=Object.prototype.hasOwnProperty;var ne=(t,e)=>{for(var n in e)E(t,n,{get:e[n],enumerable:!0})},re=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ee(e))!te.call(t,r)&&r!==n&&E(t,r,{get:()=>e[r],enumerable:!(i=Z(e,r))||i.enumerable});return t};var ie=t=>re(E({},"__esModule",{value:!0}),t);var Ae={};ne(Ae,{audit:()=>d,auditFetch:()=>ve,captureNextError:()=>D,initNextDevInspector:()=>we,withAuditAction:()=>Ee,withAuditApi:()=>be});module.exports=ie(Ae);var P="9.3.6",se=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),oe=new Set(["frontend","backend","fullstack","mobile"]),N="https://api.devinspector.com.br/api/ingest/track",L="https://api.devinspector.com.br/api/ingest/apm",O=50,v=1e4,ae=5e4,A=4e3,Q=4e3,B=2e3,z=1e3,j=200,I=200,de=100,ue=200,ce=100,pe=6,G=1e4,he=5e3,V=3,le=1e3,fe=1e4,me=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ge(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return me.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>v?`${t.slice(0,v)}...[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>=pe)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(ge(o)){r[o]="[REDACTED]";continue}r[o]=y(s,e+1,n)}return r}finally{n.delete(t)}}function M(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 k(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function H(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(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 h(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ye(t){return String(t??"").trim().slice(0,200)}function Te(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=I){return h(t,e)}function K(t){let e=w(t,50);if(e&&se.has(e))return e}function F(t){let e=w(t,50);if(e&&oe.has(e))return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function g(t){return y(t)}function X(t){let e=Math.max(0,t-1);return Math.min(le*2**e,fe)}function Ie(t,e){return setTimeout(t,Math.max(0,e))}var q=class{constructor(){this.apiKey="";this.endpoint=N;this.apmEndpoint=L;this.environment="production";this.sdkVersion=P;this.slowThresholdMs=300;this.requestTimeoutMs=G;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=h(e.environment,de)||"production",this.release=h(e.release,ue),this.technology=K(e.technology),this.category=F(e.category),this.installationId=w(e.installationId,I),this.sdkVersion=w(e.sdkVersion,ce)||P,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):G,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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>O&&(this.breadcrumbs=this.breadcrumbs.slice(-O))}getBreadcrumbs(){return this.breadcrumbs.map(e=>g(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:g(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),u=n.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===n.origin&&s===u||o===i.origin&&s===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let n=k(e.method)||"GET",i=h(e.url,A);if(!i)return;let r=H(e.statusCode)??0,o=R(e.durationMs)??0,s=$(e.ip),u=h(e.path,Q),a=h(e.route,B),c=h(e.userAgent,z),l=h(e.contentType,j),f=e.query?y(e.query):void 0,p=e.requestBody!==void 0?y(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:o,...u?{path:u}:{},...a?{route:a}:{},...c?{userAgent:c}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...f?{query:f}:{},...p!==void 0?{requestBody:p}:{},...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:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(m)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:h(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:h(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(r)})}captureMetric(e,n,i={},r={}){let o=ye(e);if(!o)return Promise.resolve();let s;try{s=Te(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},o=k(r.method),s=H(r.statusCode??r.status),u=R(r.durationMs),a=$(r.ip),c=h(r.url,A),l=h(r.path,Q),f=h(r.route,B),p=h(r.userAgent,z),m=h(r.contentType,j),T=h(r.requestId,I),_=h(r.traceId,I),x=h(r.spanId,I),S=r.query!==void 0?y(r.query):void 0,U=r.requestBody!==void 0?y(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,ae)||"",...c?{url:c}:{},...l?{path:l}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...u!==void 0?{durationMs:u}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...S?{query:S}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},..._?{traceId:_}:{},...x?{spanId:x}:{},environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(M(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<he){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),u=w(s.connectionTestId??s.testId,I),a=w(s.installationId,I);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=K(s.technology)),s.category&&!this.category&&(this.category=F(s.category)),!u){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=u;let c=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=c&&Number.isFinite(c)?c: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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(M(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:g(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,g(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=V){this.sendQueue.shift(),e.resolve();continue}let s=X(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=V){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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=Ie(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=y(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let u=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:o?.signal};return u&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},Y="__DEVINSPECT_AUDIT_CORE_INSTANCE__",J=typeof globalThis<"u"?globalThis:{},d=J[Y]||new q;J[Y]=d;async function W(t,e,n={}){let i=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=k(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(t,e);let s=d.createRequestId(),u=d.createTraceId(),a=d.createSpanId(),c=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));c.set("x-devinspector-request-id",s),c.set("x-devinspector-trace-id",u),c.set("x-devinspector-span-id",a);let l={...e,headers:c},f=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,l),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=p.headers.get("content-type")||void 0;return d.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:s,traceId:u,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:u,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:u,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:u,spanId:a});let T=p instanceof Error?p:new Error(M(p));throw d.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:u,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),p}}function we(t){d.init(t)}function D(t,e={}){let n=t instanceof Error?t:new Error(String(t));d.captureError(n,{...e,framework:"Next.js"})}async function ve(t,e){return W(t,e,{errorType:"nextjs_network_error"})}function be(t){return async function(...e){let n=typeof performance<"u"?performance.now():Date.now(),i=e[0],r=e[1],o=i?.method||"GET",s=i?.url||i?.nextUrl?.href||"/api",u=typeof i?.headers?.get=="function"?i.headers.get("user-agent")||"":i?.headers?.["user-agent"]||"",a=C(i,"x-devinspector-request-id")||d.createRequestId(),c=C(i,"x-devinspector-trace-id")||d.createTraceId(),l=C(i,"x-devinspector-span-id")||d.createSpanId();d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"start",requestId:a,traceId:c,spanId:l}});try{let f=await t(...e),p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n)),m=Number(f?.status??r?.statusCode??200)||200;return(m>=400||p>=d.getSlowThresholdMs())&&d.captureRequest({method:o,url:s,statusCode:m,durationMs:p,route:s,userAgent:u,requestId:a,traceId:c,spanId:l}),d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"complete",statusCode:m,durationMs:p,requestId:a,traceId:c,spanId:l}}),f}catch(f){let p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));throw d.captureRequest({method:o,url:s,statusCode:500,durationMs:p,route:s,userAgent:u,requestId:a,traceId:c,spanId:l}),d.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{framework:"Next.js",statusCode:500,durationMs:p,requestId:a,traceId:c,spanId:l}}),D(f,{url:s,method:o,type:"api_route_error",requestId:a,traceId:c,spanId:l}),f}}}function Ee(t,e){return(async(...n)=>{let i=typeof performance<"u"?performance.now():Date.now(),r=d.createRequestId(),o=d.createTraceId(),s=d.createSpanId();d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:r,traceId:o,spanId:s}});try{let u=await e(...n),a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));return a>=d.getSlowThresholdMs()&&d.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:a,requestId:r,traceId:o,spanId:s}}),u}catch(u){let a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));throw d.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:a,requestId:r,traceId:o,spanId:s}}),D(u,{actionName:t,type:"server_action_error",requestId:r,traceId:o,spanId:s}),u}})}function C(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let n=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(n)?n[0]:n?String(n):void 0}0&&(module.exports={audit,auditFetch,captureNextError,initNextDevInspector,withAuditAction,withAuditApi});
|
|
1
|
+
"use strict";var E=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var re=(t,e)=>{for(var n in e)E(t,n,{get:e[n],enumerable:!0})},ie=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of te(e))!ne.call(t,r)&&r!==n&&E(t,r,{get:()=>e[r],enumerable:!(i=ee(e,r))||i.enumerable});return t};var se=t=>ie(E({},"__esModule",{value:!0}),t);var Ae={};re(Ae,{audit:()=>d,auditFetch:()=>ve,captureNextError:()=>D,initNextDevInspector:()=>we,withAuditAction:()=>Ee,withAuditApi:()=>be});module.exports=se(Ae);var P="9.3.8",oe=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ae=new Set(["frontend","backend","fullstack","mobile"]),N="https://api.devinspector.com.br/api/ingest/track",O="https://api.devinspector.com.br/api/ingest/apm",L=50,b=1e4,de=5e4,A=4e3,Q=4e3,B=2e3,z=1e3,j=200,I=200,ce=100,ue=200,pe=100,he=6,G=1e4,V=5e3,$=3,le=1e3,fe=1e4,me=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ge(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return me.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>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>=he)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(ge(o)){r[o]="[REDACTED]";continue}r[o]=y(s,e+1,n)}return r}finally{n.delete(t)}}function M(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 C(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function H(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(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 l(t,e=b){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ye(t){return String(t??"").trim().slice(0,200)}function Te(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=I){return l(t,e)}function F(t){let e=w(t,50);if(e&&oe.has(e))return e}function X(t){let e=w(t,50);if(e&&ae.has(e))return e}function v(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 g(t){return y(t)}function Y(t){let e=Math.max(0,t-1);return Math.min(le*2**e,fe)}function Ie(t,e){return setTimeout(t,Math.max(0,e))}var k=class{constructor(){this.apiKey="";this.endpoint=N;this.apmEndpoint=O;this.environment="production";this.sdkVersion=P;this.slowThresholdMs=300;this.requestTimeoutMs=G;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()||O,this.environment=l(e.environment,ce)||"production",this.release=l(e.release,ue),this.technology=F(e.technology),this.category=X(e.category),this.installationId=w(e.installationId,I)||v("di"),this.sdkVersion=w(e.sdkVersion,pe)||P,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):G,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.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),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}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>L&&(this.breadcrumbs=this.breadcrumbs.slice(-L))}getBreadcrumbs(){return this.breadcrumbs.map(e=>g(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:g(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),c=n.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===n.origin&&s===c||o===i.origin&&s===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return v("req")}createTraceId(){return v("trace")}createSpanId(){return v("span")}async captureRequest(e){let n=C(e.method)||"GET",i=l(e.url,A);if(!i)return;let r=H(e.statusCode)??0,o=R(e.durationMs)??0,s=K(e.ip),c=l(e.path,Q),a=l(e.route,B),u=l(e.userAgent,z),h=l(e.contentType,j),f=e.query?y(e.query):void 0,p=e.requestBody!==void 0?y(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:o,...c?{path:c}:{},...a?{route:a}:{},...u?{userAgent:u}:{},...h?{contentType:h}:{},...s?{ip:s}:{},...f?{query:f}:{},...p!==void 0?{requestBody:p}:{},...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:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(m)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:l(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:l(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(r)})}captureMetric(e,n,i={},r={}){let o=ye(e);if(!o)return Promise.resolve();let s;try{s=Te(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},o=C(r.method),s=H(r.statusCode??r.status),c=R(r.durationMs),a=K(r.ip),u=l(r.url,A),h=l(r.path,Q),f=l(r.route,B),p=l(r.userAgent,z),m=l(r.contentType,j),T=l(r.requestId,I),_=l(r.traceId,I),x=l(r.spanId,I),S=r.query!==void 0?y(r.query):void 0,U=r.requestBody!==void 0?y(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,b),stackTrace:e?.stack?.slice(0,de)||"",...u?{url:u}:{},...h?{path:h}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...S?{query:S}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},..._?{traceId:_}:{},...x?{spanId:x}:{},environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(M(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...n,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},V)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<V){this.connectionTestExpiresAt&&n>=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 n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),c=w(s.connectionTestId??s.testId,I),a=w(s.installationId,I);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=F(s.technology)),s.category&&!this.category&&(this.category=X(s.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let u=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=u&&Number.isFinite(u)?u:void 0,await this.sendIntegrationTest(c)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let n={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,n)&&this.clearConnectionTest(e)}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 n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(M(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=v("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:g(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,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 n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,g(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=$){this.sendQueue.shift(),e.resolve();continue}let s=Y(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=$){this.sendQueue.shift(),e.resolve();continue}let i=Y(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 n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=Ie(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=y(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.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:o?.signal};c&&(a.keepalive=!0);let u=await i(e,a);if(!u.ok){let h="";try{h=await u.text()}catch{h=""}console.error(`[DevInspector] Falha ao enviar evento: ${u.status} ${u.statusText}`,h)}return u.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},J="__DEVINSPECT_AUDIT_CORE_INSTANCE__",W=typeof globalThis<"u"?globalThis:{},d=W[J]||new k;W[J]=d;async function Z(t,e,n={}){let i=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=C(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&d.isIngestUrl(r))return i(t,e);let s=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),u=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));u.set("x-devinspector-request-id",s),u.set("x-devinspector-trace-id",c),u.set("x-devinspector-span-id",a);let h={...e,headers:u},f=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,h),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=p.headers.get("content-type")||void 0;return d.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:s,traceId:c,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:c,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:c,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:c,spanId:a});let T=p instanceof Error?p:new Error(M(p));throw d.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:c,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),p}}function we(t){d.init(t)}function D(t,e={}){let n=t instanceof Error?t:new Error(String(t));d.captureError(n,{...e,framework:"Next.js"})}async function ve(t,e){return Z(t,e,{errorType:"nextjs_network_error"})}function be(t){return async function(...e){let n=typeof performance<"u"?performance.now():Date.now(),i=e[0],r=e[1],o=i?.method||"GET",s=i?.url||i?.nextUrl?.href||"/api",c=typeof i?.headers?.get=="function"?i.headers.get("user-agent")||"":i?.headers?.["user-agent"]||"",a=q(i,"x-devinspector-request-id")||d.createRequestId(),u=q(i,"x-devinspector-trace-id")||d.createTraceId(),h=q(i,"x-devinspector-span-id")||d.createSpanId();d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"start",requestId:a,traceId:u,spanId:h}});try{let f=await t(...e),p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n)),m=Number(f?.status??r?.statusCode??200)||200;return(m>=400||p>=d.getSlowThresholdMs())&&d.captureRequest({method:o,url:s,statusCode:m,durationMs:p,route:s,userAgent:c,requestId:a,traceId:u,spanId:h}),d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"complete",statusCode:m,durationMs:p,requestId:a,traceId:u,spanId:h}}),f}catch(f){let p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));throw d.captureRequest({method:o,url:s,statusCode:500,durationMs:p,route:s,userAgent:c,requestId:a,traceId:u,spanId:h}),d.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{framework:"Next.js",statusCode:500,durationMs:p,requestId:a,traceId:u,spanId:h}}),D(f,{url:s,method:o,type:"api_route_error",requestId:a,traceId:u,spanId:h}),f}}}function Ee(t,e){return(async(...n)=>{let i=typeof performance<"u"?performance.now():Date.now(),r=d.createRequestId(),o=d.createTraceId(),s=d.createSpanId();d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:r,traceId:o,spanId:s}});try{let c=await e(...n),a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));return a>=d.getSlowThresholdMs()&&d.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:a,requestId:r,traceId:o,spanId:s}}),c}catch(c){let a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));throw d.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:a,requestId:r,traceId:o,spanId:s}}),D(c,{actionName:t,type:"server_action_error",requestId:r,traceId:o,spanId:s}),c}})}function q(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let n=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(n)?n[0]:n?String(n):void 0}0&&(module.exports={audit,auditFetch,captureNextError,initNextDevInspector,withAuditAction,withAuditApi});
|