@sentry/node 8.34.0 → 8.35.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/index.js +21 -21
- package/build/cjs/integrations/anr/index.js +1 -1
- package/build/cjs/integrations/anr/index.js.map +1 -1
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js +264 -0
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -0
- package/build/cjs/integrations/http/index.js +167 -0
- package/build/cjs/integrations/http/index.js.map +1 -0
- package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
- package/build/cjs/integrations/local-variables/local-variables-async.js.map +1 -1
- package/build/cjs/integrations/tracing/index.js +2 -2
- package/build/cjs/integrations/tracing/index.js.map +1 -1
- package/build/cjs/sdk/index.js +8 -8
- package/build/cjs/sdk/index.js.map +1 -1
- package/build/esm/index.js +1 -1
- package/build/esm/integrations/anr/index.js +1 -1
- package/build/esm/integrations/anr/index.js.map +1 -1
- package/build/esm/integrations/anr/worker-script.js +2 -2
- package/build/esm/integrations/http/SentryHttpInstrumentation.js +262 -0
- package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -0
- package/build/esm/integrations/http/index.js +160 -0
- package/build/esm/integrations/http/index.js.map +1 -0
- package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
- package/build/esm/integrations/local-variables/local-variables-async.js.map +1 -1
- package/build/esm/integrations/local-variables/worker-script.js +2 -2
- package/build/esm/integrations/tracing/index.js +2 -2
- package/build/esm/integrations/tracing/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/sdk/index.js +1 -1
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts +39 -0
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -0
- package/build/types/integrations/{http.d.ts → http/index.d.ts} +21 -10
- package/build/types/integrations/http/index.d.ts.map +1 -0
- package/build/types-ts3.8/integrations/http/SentryHttpInstrumentation.d.ts +42 -0
- package/build/types-ts3.8/integrations/{http.d.ts → http/index.d.ts} +21 -10
- package/package.json +6 -6
- package/build/cjs/integrations/http.js +0 -248
- package/build/cjs/integrations/http.js.map +0 -1
- package/build/cjs/sdk/scope.js +0 -18
- package/build/cjs/sdk/scope.js.map +0 -1
- package/build/esm/integrations/http.js +0 -242
- package/build/esm/integrations/http.js.map +0 -1
- package/build/esm/sdk/scope.js +0 -16
- package/build/esm/sdk/scope.js.map +0 -1
- package/build/types/integrations/http.d.ts.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @sentry/node 8.
|
|
2
|
-
import{Session as t}from"node:inspector";import{parentPort as n,workerData as e}from"node:worker_threads";import{posix as r,sep as o}from"node:path";import*as s from"node:http";import*as i from"node:https";import{Readable as c}from"node:stream";import{createGzip as u}from"node:zlib";import*as a from"node:net";import*as f from"node:tls";const h=Object.prototype.toString;function p(t,n){return h.call(t)===`[object ${n}]`}function l(t){return p(t,"String")}function d(t){return p(t,"Object")}function m(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function y(t,n){try{return t instanceof n}catch(t){return!1}}const g="8.34.0",b=globalThis;function _(t,n,e){const r=e||b,o=r.__SENTRY__=r.__SENTRY__||{},s=o[g]=o[g]||{};return s[t]||(s[t]=n())}const v=b,w=80;function S(t,n){const e=t,r=[];if(!e||!e.tagName)return"";if(v.HTMLElement&&e instanceof HTMLElement&&e.dataset){if(e.dataset.sentryComponent)return e.dataset.sentryComponent;if(e.dataset.sentryElement)return e.dataset.sentryElement}r.push(e.tagName.toLowerCase());const o=n&&n.length?n.filter((t=>e.getAttribute(t))).map((t=>[t,e.getAttribute(t)])):null;if(o&&o.length)o.forEach((t=>{r.push(`[${t[0]}="${t[1]}"]`)}));else{e.id&&r.push(`#${e.id}`);const t=e.className;if(t&&l(t)){const n=t.split(/\s+/);for(const t of n)r.push(`.${t}`)}}const s=["aria-label","type","name","title","alt"];for(const t of s){const n=e.getAttribute(t);n&&r.push(`[${t}="${n}"]`)}return r.join("")}const $="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,E=["debug","info","warn","error","log","assert","trace"],x={};function N(t){if(!("console"in b))return t();const n=b.console,e={},r=Object.keys(x);r.forEach((t=>{const r=x[t];e[t]=n[t],n[t]=r}));try{return t()}finally{r.forEach((t=>{n[t]=e[t]}))}}const k=_("logger",(function(){let t=!1;const n={enable:()=>{t=!0},disable:()=>{t=!1},isEnabled:()=>t};return $?E.forEach((e=>{n[e]=(...n)=>{t&&N((()=>{b.console[e](`Sentry Logger [${e}]:`,...n)}))}})):E.forEach((t=>{n[t]=()=>{}})),n}));function C(t,n=!1){const{host:e,path:r,pass:o,port:s,projectId:i,protocol:c,publicKey:u}=t;return`${c}://${u}${n&&o?`:${o}`:""}@${e}${s?`:${s}`:""}/${r?`${r}/`:r}${i}`}class T extends Error{constructor(t,n="warn"){super(t),this.message=t,this.name=new.target.prototype.constructor.name,Object.setPrototypeOf(this,new.target.prototype),this.logLevel=n}}function R(t){if(function(t){switch(h.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return y(t,Error)}}(t))return{message:t.message,name:t.name,stack:t.stack,...j(t)};if(n=t,"undefined"!=typeof Event&&y(n,Event)){const n={type:t.type,target:D(t.target),currentTarget:D(t.currentTarget),...j(t)};return"undefined"!=typeof CustomEvent&&y(t,CustomEvent)&&(n.detail=t.detail),n}return t;var n}function D(t){try{return n=t,"undefined"!=typeof Element&&y(n,Element)?function(t,n={}){if(!t)return"<unknown>";try{let e=t;const r=5,o=[];let s=0,i=0;const c=" > ",u=c.length;let a;const f=Array.isArray(n)?n:n.keyAttrs,h=!Array.isArray(n)&&n.maxStringLength||w;for(;e&&s++<r&&(a=S(e,f),!("html"===a||s>1&&i+o.length*u+a.length>=h));)o.push(a),i+=a.length,e=e.parentNode;return o.reverse().join(c)}catch(t){return"<unknown>"}}(t):Object.prototype.toString.call(t)}catch(t){return"<unknown>"}var n}function j(t){if("object"==typeof t&&null!==t){const n={};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e]);return n}return{}}function O(t){return A(t,new Map)}function A(t,n){if(function(t){if(!d(t))return!1;try{const n=Object.getPrototypeOf(t).constructor.name;return!n||"Object"===n}catch(t){return!0}}(t)){const e=n.get(t);if(void 0!==e)return e;const r={};n.set(t,r);for(const e of Object.getOwnPropertyNames(t))void 0!==t[e]&&(r[e]=A(t[e],n));return r}if(Array.isArray(t)){const e=n.get(t);if(void 0!==e)return e;const r=[];return n.set(t,r),t.forEach((t=>{r.push(A(t,n))})),r}return t}const I=50,P="?",U=/captureMessage|captureException/;function M(t){return t[t.length-1]||{}}const L="<anonymous>";const B=1e3;function G(){return Date.now()/B}const J=function(){const{performance:t}=b;if(!t||!t.now)return G;const n=Date.now()-t.now(),e=null==t.timeOrigin?n:t.timeOrigin;return()=>(e+t.now())/B}();function Y(){const t=b,n=t.crypto||t.msCrypto;let e=()=>16*Math.random();try{if(n&&n.randomUUID)return n.randomUUID().replace(/-/g,"");n&&n.getRandomValues&&(e=()=>{const t=new Uint8Array(1);return n.getRandomValues(t),t[0]})}catch(t){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(t=>(t^(15&e())>>t/4).toString(16)))}function z(t,n=100,e=1/0){try{return H("",t,n,e)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function H(t,n,e=1/0,r=1/0,o=function(){const t="function"==typeof WeakSet,n=t?new WeakSet:[];return[function(e){if(t)return!!n.has(e)||(n.add(e),!1);for(let t=0;t<n.length;t++)if(n[t]===e)return!0;return n.push(e),!1},function(e){if(t)n.delete(e);else for(let t=0;t<n.length;t++)if(n[t]===e){n.splice(t,1);break}}]}()){const[s,i]=o;if(null==n||["boolean","string"].includes(typeof n)||"number"==typeof n&&Number.isFinite(n))return n;const c=function(t,n){try{if("domain"===t&&n&&"object"==typeof n&&n.t)return"[Domain]";if("domainEmitter"===t)return"[DomainEmitter]";if("undefined"!=typeof global&&n===global)return"[Global]";if("undefined"!=typeof window&&n===window)return"[Window]";if("undefined"!=typeof document&&n===document)return"[Document]";if("object"==typeof(e=n)&&null!==e&&(e.__isVue||e.o))return"[VueViewModel]";if(function(t){return d(t)&&"nativeEvent"in t&&"preventDefault"in t&&"stopPropagation"in t}(n))return"[SyntheticEvent]";if("number"==typeof n&&!Number.isFinite(n))return`[${n}]`;if("function"==typeof n)return`[Function: ${function(t){try{return t&&"function"==typeof t&&t.name||L}catch(t){return L}}(n)}]`;if("symbol"==typeof n)return`[${String(n)}]`;if("bigint"==typeof n)return`[BigInt: ${String(n)}]`;const r=function(t){const n=Object.getPrototypeOf(t);return n?n.constructor.name:"null prototype"}(n);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(t){return`**non-serializable** (${t})`}var e}(t,n);if(!c.startsWith("[object "))return c;if(n.__sentry_skip_normalization__)return n;const u="number"==typeof n.__sentry_override_normalization_depth__?n.__sentry_override_normalization_depth__:e;if(0===u)return c.replace("object ","");if(s(n))return"[Circular ~]";const a=n;if(a&&"function"==typeof a.toJSON)try{return H("",a.toJSON(),u-1,r,o)}catch(t){}const f=Array.isArray(n)?[]:{};let h=0;const p=R(n);for(const t in p){if(!Object.prototype.hasOwnProperty.call(p,t))continue;if(h>=r){f[t]="[MaxProperties ~]";break}const n=p[t];f[t]=H(t,n,u-1,r,o),h++}return i(n),f}function W(t,n){const e=n.replace(/\\/g,"/").replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");let r=t;try{r=decodeURI(t)}catch(t){}return r.replace(/\\/g,"/").replace(/webpack:\/?/g,"").replace(new RegExp(`(file://)?/*${e}/*`,"ig"),"app:///")}(()=>{const{performance:t}=b;if(!t||!t.now)return;const n=36e5,e=t.now(),r=Date.now(),o=t.timeOrigin?Math.abs(t.timeOrigin+e-r):n,s=o<n,i=t.timing&&t.timing.navigationStart,c="number"==typeof i?Math.abs(i+e-r):n;(s||c<n)&&(o<=c&&t.timeOrigin)})();const q=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function F(t){const n=function(t){const n=t.length>1024?`<truncated>${t.slice(-1024)}`:t,e=q.exec(n);return e?e.slice(1):[]}(t),e=n[0]||"";let r=n[1];return e||r?(r&&(r=r.slice(0,r.length-1)),e+r):"."}var K;function V(t){return new Z((n=>{n(t)}))}!function(t){t[t.PENDING=0]="PENDING";t[t.RESOLVED=1]="RESOLVED";t[t.REJECTED=2]="REJECTED"}(K||(K={}));class Z{constructor(t){Z.prototype.__init.call(this),Z.prototype.__init2.call(this),Z.prototype.__init3.call(this),Z.prototype.__init4.call(this),this.i=K.PENDING,this.u=[];try{t(this.h,this.p)}catch(t){this.p(t)}}then(t,n){return new Z(((e,r)=>{this.u.push([!1,n=>{if(t)try{e(t(n))}catch(t){r(t)}else e(n)},t=>{if(n)try{e(n(t))}catch(t){r(t)}else r(t)}]),this.l()}))}catch(t){return this.then((t=>t),t)}finally(t){return new Z(((n,e)=>{let r,o;return this.then((n=>{o=!1,r=n,t&&t()}),(n=>{o=!0,r=n,t&&t()})).then((()=>{o?e(r):n(r)}))}))}__init(){this.h=t=>{this.m(K.RESOLVED,t)}}__init2(){this.p=t=>{this.m(K.REJECTED,t)}}__init3(){this.m=(t,n)=>{this.i===K.PENDING&&(m(n)?n.then(this.h,this.p):(this.i=t,this._=n,this.l()))}}__init4(){this.l=()=>{if(this.i===K.PENDING)return;const t=this.u.slice();this.u=[],t.forEach((t=>{t[0]||(this.i===K.RESOLVED&&t[1](this._),this.i===K.REJECTED&&t[2](this._),t[0]=!0)}))}}}function Q(t){const n=[];function e(t){return n.splice(n.indexOf(t),1)[0]||Promise.resolve(void 0)}return{$:n,add:function(r){if(!(void 0===t||n.length<t))return o=new T("Not adding Promise because buffer limit was reached."),new Z(((t,n)=>{n(o)}));var o;const s=r();return-1===n.indexOf(s)&&n.push(s),s.then((()=>e(s))).then(null,(()=>e(s).then(null,(()=>{})))),s},drain:function(t){return new Z(((e,r)=>{let o=n.length;if(!o)return e(!0);const s=setTimeout((()=>{t&&t>0&&e(!1)}),t);n.forEach((t=>{V(t).then((()=>{--o||(clearTimeout(s),e(!0))}),r)}))}))}}}function X(t,n=!1){return!(n||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==t&&!t.includes("node_modules/")}const tt="sentry-",nt=/^sentry-/;function et(t){const n=function(t){if(!t||!l(t)&&!Array.isArray(t))return;if(Array.isArray(t))return t.reduce(((t,n)=>{const e=rt(n);return Object.entries(e).forEach((([n,e])=>{t[n]=e})),t}),{});return rt(t)}(t);if(!n)return;const e=Object.entries(n).reduce(((t,[n,e])=>{if(n.match(nt)){t[n.slice(tt.length)]=e}return t}),{});return Object.keys(e).length>0?e:void 0}function rt(t){return t.split(",").map((t=>t.split("=").map((t=>decodeURIComponent(t.trim()))))).reduce(((t,[n,e])=>(n&&e&&(t[n]=e),t)),{})}function ot(t,n=[]){return[t,n]}function st(t,n){const e=t[1];for(const t of e){if(n(t,t[0].type))return!0}return!1}function it(t){return b.__SENTRY__&&b.__SENTRY__.encodePolyfill?b.__SENTRY__.encodePolyfill(t):(new TextEncoder).encode(t)}function ct(t){const[n,e]=t;let r=JSON.stringify(n);function o(t){"string"==typeof r?r="string"==typeof t?r+t:[it(r),t]:r.push("string"==typeof t?it(t):t)}for(const t of e){const[n,e]=t;if(o(`\n${JSON.stringify(n)}\n`),"string"==typeof e||e instanceof Uint8Array)o(e);else{let t;try{t=JSON.stringify(e)}catch(n){t=JSON.stringify(z(e))}o(t)}}return"string"==typeof r?r:function(t){const n=t.reduce(((t,n)=>t+n.length),0),e=new Uint8Array(n);let r=0;for(const n of t)e.set(n,r),r+=n.length;return e}(r)}const ut={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket"};function at(t){return ut[t]}function ft(t){if(!t||!t.sdk)return;const{name:n,version:e}=t.sdk;return{name:n,version:e}}const ht=6e4;function pt(t,{statusCode:n,headers:e},r=Date.now()){const o={...t},s=e&&e["x-sentry-rate-limits"],i=e&&e["retry-after"];if(s)for(const t of s.trim().split(",")){const[n,e,,,s]=t.split(":",5),i=parseInt(n,10),c=1e3*(isNaN(i)?60:i);if(e)for(const t of e.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(o[t]=r+c);else o.all=r+c}else i?o.all=r+function(t,n=Date.now()){const e=parseInt(`${t}`,10);if(!isNaN(e))return 1e3*e;const r=Date.parse(`${t}`);return isNaN(r)?ht:r-n}(i,r):429===n&&(o.all=r+6e4);return o}function lt(){return{traceId:Y(),spanId:Y().substring(16)}}const dt="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function mt(){return yt(b),b}function yt(t){const n=t.__SENTRY__=t.__SENTRY__||{};return n.version=n.version||g,n[g]=n[g]||{}}function gt(t){const n=J(),e={sid:Y(),init:!0,timestamp:n,started:n,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return O({sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}})}(e)};return t&&bt(e,t),e}function bt(t,n={}){if(n.user&&(!t.ipAddress&&n.user.ip_address&&(t.ipAddress=n.user.ip_address),t.did||n.did||(t.did=n.user.id||n.user.email||n.user.username)),t.timestamp=n.timestamp||J(),n.abnormal_mechanism&&(t.abnormal_mechanism=n.abnormal_mechanism),n.ignoreDuration&&(t.ignoreDuration=n.ignoreDuration),n.sid&&(t.sid=32===n.sid.length?n.sid:Y()),void 0!==n.init&&(t.init=n.init),!t.did&&n.did&&(t.did=`${n.did}`),"number"==typeof n.started&&(t.started=n.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof n.duration)t.duration=n.duration;else{const n=t.timestamp-t.started;t.duration=n>=0?n:0}n.release&&(t.release=n.release),n.environment&&(t.environment=n.environment),!t.ipAddress&&n.ipAddress&&(t.ipAddress=n.ipAddress),!t.userAgent&&n.userAgent&&(t.userAgent=n.userAgent),"number"==typeof n.errors&&(t.errors=n.errors),n.status&&(t.status=n.status)}const _t="_sentrySpan";function vt(t,n){n?function(t,n,e){try{Object.defineProperty(t,n,{value:e,writable:!0,configurable:!0})}catch(e){$&&k.log(`Failed to add non-enumerable property "${n}" to object`,t)}}(t,_t,n):delete t[_t]}function wt(t){return t[_t]}class St{constructor(){this.v=!1,this.S=[],this.N=[],this.k=[],this.C=[],this.T={},this.R={},this.D={},this.j={},this.O={},this.A=lt()}clone(){const t=new St;return t.k=[...this.k],t.R={...this.R},t.D={...this.D},t.j={...this.j},t.T=this.T,t.I=this.I,t.P=this.P,t.U=this.U,t.M=this.M,t.N=[...this.N],t.L=this.L,t.C=[...this.C],t.O={...this.O},t.A={...this.A},t.B=this.B,t.G=this.G,vt(t,wt(this)),t}setClient(t){this.B=t}setLastEventId(t){this.G=t}getClient(){return this.B}lastEventId(){return this.G}addScopeListener(t){this.S.push(t)}addEventProcessor(t){return this.N.push(t),this}setUser(t){return this.T=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this.P&&bt(this.P,{user:t}),this.J(),this}getUser(){return this.T}getRequestSession(){return this.L}setRequestSession(t){return this.L=t,this}setTags(t){return this.R={...this.R,...t},this.J(),this}setTag(t,n){return this.R={...this.R,[t]:n},this.J(),this}setExtras(t){return this.D={...this.D,...t},this.J(),this}setExtra(t,n){return this.D={...this.D,[t]:n},this.J(),this}setFingerprint(t){return this.M=t,this.J(),this}setLevel(t){return this.I=t,this.J(),this}setTransactionName(t){return this.U=t,this.J(),this}setContext(t,n){return null===n?delete this.j[t]:this.j[t]=n,this.J(),this}setSession(t){return t?this.P=t:delete this.P,this.J(),this}getSession(){return this.P}update(t){if(!t)return this;const n="function"==typeof t?t(this):t,[e,r]=n instanceof $t?[n.getScopeData(),n.getRequestSession()]:d(n)?[t,t.requestSession]:[],{tags:o,extra:s,user:i,contexts:c,level:u,fingerprint:a=[],propagationContext:f}=e||{};return this.R={...this.R,...o},this.D={...this.D,...s},this.j={...this.j,...c},i&&Object.keys(i).length&&(this.T=i),u&&(this.I=u),a.length&&(this.M=a),f&&(this.A=f),r&&(this.L=r),this}clear(){return this.k=[],this.R={},this.D={},this.T={},this.j={},this.I=void 0,this.U=void 0,this.M=void 0,this.L=void 0,this.P=void 0,vt(this,void 0),this.C=[],this.A=lt(),this.J(),this}addBreadcrumb(t,n){const e="number"==typeof n?n:100;if(e<=0)return this;const r={timestamp:G(),...t},o=this.k;return o.push(r),this.k=o.length>e?o.slice(-e):o,this.J(),this}getLastBreadcrumb(){return this.k[this.k.length-1]}clearBreadcrumbs(){return this.k=[],this.J(),this}addAttachment(t){return this.C.push(t),this}clearAttachments(){return this.C=[],this}getScopeData(){return{breadcrumbs:this.k,attachments:this.C,contexts:this.j,tags:this.R,extra:this.D,user:this.T,level:this.I,fingerprint:this.M||[],eventProcessors:this.N,propagationContext:this.A,sdkProcessingMetadata:this.O,transactionName:this.U,span:wt(this)}}setSDKProcessingMetadata(t){return this.O={...this.O,...t},this}setPropagationContext(t){return this.A=t,this}getPropagationContext(){return this.A}captureException(t,n){const e=n&&n.event_id?n.event_id:Y();if(!this.B)return k.warn("No client configured on scope - will not capture exception!"),e;const r=new Error("Sentry syntheticException");return this.B.captureException(t,{originalException:t,syntheticException:r,...n,event_id:e},this),e}captureMessage(t,n,e){const r=e&&e.event_id?e.event_id:Y();if(!this.B)return k.warn("No client configured on scope - will not capture message!"),r;const o=new Error(t);return this.B.captureMessage(t,n,{originalException:t,syntheticException:o,...e,event_id:r},this),r}captureEvent(t,n){const e=n&&n.event_id?n.event_id:Y();return this.B?(this.B.captureEvent(t,{...n,event_id:e},this),e):(k.warn("No client configured on scope - will not capture event!"),e)}J(){this.v||(this.v=!0,this.S.forEach((t=>{t(this)})),this.v=!1)}}const $t=St;class Et{constructor(t,n){let e,r;e=t||new $t,r=n||new $t,this.Y=[{scope:e}],this.H=r}withScope(t){const n=this.W();let e;try{e=t(n)}catch(t){throw this.q(),t}return m(e)?e.then((t=>(this.q(),t)),(t=>{throw this.q(),t})):(this.q(),e)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this.H}getStackTop(){return this.Y[this.Y.length-1]}W(){const t=this.getScope().clone();return this.Y.push({client:this.getClient(),scope:t}),t}q(){return!(this.Y.length<=1)&&!!this.Y.pop()}}function xt(){const t=yt(mt());return t.stack=t.stack||new Et(_("defaultCurrentScope",(()=>new $t)),_("defaultIsolationScope",(()=>new $t)))}function Nt(t){return xt().withScope(t)}function kt(t,n){const e=xt();return e.withScope((()=>(e.getStackTop().scope=t,n(t))))}function Ct(t){return xt().withScope((()=>t(xt().getIsolationScope())))}function Tt(t){const n=yt(t);return n.acs?n.acs:{withIsolationScope:Ct,withScope:Nt,withSetScope:kt,withSetIsolationScope:(t,n)=>Ct(n),getCurrentScope:()=>xt().getScope(),getIsolationScope:()=>xt().getIsolationScope()}}function Rt(){return Tt(mt()).getCurrentScope().getClient()}const Dt="_sentryMetrics";function jt(t){const n=t[Dt];if(!n)return;const e={};for(const[,[t,r]]of n){(e[t]||(e[t]=[])).push(O(r))}return e}const Ot="sentry.source",At="sentry.sample_rate",It="sentry.op",Pt="sentry.origin",Ut=0,Mt=1,Lt=1;function Bt(t){const{spanId:n,traceId:e}=t.spanContext(),{parent_span_id:r}=Yt(t);return O({parent_span_id:r,span_id:n,trace_id:e})}function Gt(t){return"number"==typeof t?Jt(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?Jt(t.getTime()):J()}function Jt(t){return t>9999999999?t/1e3:t}function Yt(t){if(function(t){return"function"==typeof t.getSpanJSON}(t))return t.getSpanJSON();try{const{spanId:n,traceId:e}=t.spanContext();if(function(t){const n=t;return!!(n.attributes&&n.startTime&&n.name&&n.endTime&&n.status)}(t)){const{attributes:r,startTime:o,name:s,endTime:i,parentSpanId:c,status:u}=t;return O({span_id:n,trace_id:e,data:r,description:s,parent_span_id:c,start_timestamp:Gt(o),timestamp:Gt(i)||void 0,status:zt(u),op:r[It],origin:r[Pt],_metrics_summary:jt(t)})}return{span_id:n,trace_id:e}}catch(t){return{}}}function zt(t){if(t&&t.code!==Ut)return t.code===Mt?"ok":t.message||"unknown_error"}const Ht="_sentryRootSpan";function Wt(t){return t[Ht]||t}const qt="production",Ft="_frozenDsc";function Kt(t){const n=Rt();if(!n)return{};const e=function(t,n){const e=n.getOptions(),{publicKey:r}=n.getDsn()||{},o=O({environment:e.environment||qt,release:e.release,public_key:r,trace_id:t});return n.emit("createDsc",o),o}(Yt(t).trace_id||"",n),r=Wt(t),o=r[Ft];if(o)return o;const s=r.spanContext().traceState,i=s&&s.get("sentry.dsc"),c=i&&et(i);if(c)return c;const u=Yt(r),a=u.data||{},f=a[At];null!=f&&(e.sample_rate=`${f}`);const h=a[Ot],p=u.description;return"url"!==h&&p&&(e.transaction=p),function(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const n=Rt(),e=t||n&&n.getOptions();return!!e&&(e.enableTracing||"tracesSampleRate"in e||"tracesSampler"in e)}()&&(e.sampled=String(function(t){const{traceFlags:n}=t.spanContext();return n===Lt}(r))),n.emit("createDsc",e,r),e}function Vt(t,n,e,r){const o=ft(e),s=t.type&&"replay_event"!==t.type?t.type:"event";!function(t,n){n&&(t.sdk=t.sdk||{},t.sdk.name=t.sdk.name||n.name,t.sdk.version=t.sdk.version||n.version,t.sdk.integrations=[...t.sdk.integrations||[],...n.integrations||[]],t.sdk.packages=[...t.sdk.packages||[],...n.packages||[]])}(t,e&&e.sdk);const i=function(t,n,e,r){const o=t.sdkProcessingMetadata&&t.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:t.event_id,sent_at:(new Date).toISOString(),...n&&{sdk:n},...!!e&&r&&{dsn:C(r)},...o&&{trace:O({...o})}}}(t,o,r,n);delete t.sdkProcessingMetadata;return ot(i,[[{type:s},t]])}const Zt="__SENTRY_SUPPRESS_TRACING__";function Qt(t){const n=Tt(mt());return n.suppressTracing?n.suppressTracing(t):function(...t){const n=Tt(mt());if(2===t.length){const[e,r]=t;return e?n.withSetScope(e,r):n.withScope(r)}return n.withScope(t[0])}((n=>(n.setSDKProcessingMetadata({[Zt]:!0}),t())))}function Xt(t,n){const{fingerprint:e,span:r,breadcrumbs:o,sdkProcessingMetadata:s}=n;!function(t,n){const{extra:e,tags:r,user:o,contexts:s,level:i,transactionName:c}=n,u=O(e);u&&Object.keys(u).length&&(t.extra={...u,...t.extra});const a=O(r);a&&Object.keys(a).length&&(t.tags={...a,...t.tags});const f=O(o);f&&Object.keys(f).length&&(t.user={...f,...t.user});const h=O(s);h&&Object.keys(h).length&&(t.contexts={...h,...t.contexts});i&&(t.level=i);c&&"transaction"!==t.type&&(t.transaction=c)}(t,n),r&&function(t,n){t.contexts={trace:Bt(n),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:Kt(n),...t.sdkProcessingMetadata};const e=Wt(n),r=Yt(e).description;r&&!t.transaction&&"transaction"===t.type&&(t.transaction=r)}(t,r),function(t,n){t.fingerprint=t.fingerprint?function(t){return Array.isArray(t)?t:[t]}(t.fingerprint):[],n&&(t.fingerprint=t.fingerprint.concat(n));t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,e),function(t,n){const e=[...t.breadcrumbs||[],...n];t.breadcrumbs=e.length?e:void 0}(t,o),function(t,n){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...n}}(t,s)}const tn="7";function nn(t,n){return e={sentry_key:t.publicKey,sentry_version:tn,...n&&{sentry_client:`${n.name}/${n.version}`}},Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&");var e}const en=64;function rn(t,n,e=Q(t.bufferSize||en)){let r={};return{send:function(o){const s=[];if(st(o,((n,e)=>{const o=at(e);if(function(t,n,e=Date.now()){return function(t,n){return t[n]||t.all||0}(t,n)>e}(r,o)){const r=on(n,e);t.recordDroppedEvent("ratelimit_backoff",o,r)}else s.push(n)})),0===s.length)return V({});const i=ot(o[0],s),c=n=>{st(i,((e,r)=>{const o=on(e,r);t.recordDroppedEvent(n,at(r),o)}))};return e.add((()=>n({body:ct(i)}).then((t=>(void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&dt&&k.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=pt(r,t),t)),(t=>{throw c("network_error"),t})))).then((t=>t),(t=>{if(t instanceof T)return dt&&k.error("Skipped sending event because buffer is full."),c("queue_overflow"),V({});throw t}))},flush:t=>e.drain(t)}}function on(t,n){if("event"===n||"transaction"===n)return Array.isArray(t)?t[1]:void 0}const sn=Symbol("AgentBaseInternalState");class cn extends s.Agent{[sn];options;keepAlive;constructor(t){super(t),this[sn]={}}isSecureEndpoint(t){if(t){if("boolean"==typeof t.secureEndpoint)return t.secureEndpoint;if("string"==typeof t.protocol)return"https:"===t.protocol}const{stack:n}=new Error;return"string"==typeof n&&n.split("\n").some((t=>-1!==t.indexOf("(https.js:")||-1!==t.indexOf("node:https:")))}createSocket(t,n,e){const r={...n,secureEndpoint:this.isSecureEndpoint(n)};Promise.resolve().then((()=>this.connect(t,r))).then((o=>{if(o instanceof s.Agent)return o.addRequest(t,r);this[sn].currentSocket=o,super.createSocket(t,n,e)}),e)}createConnection(){const t=this[sn].currentSocket;if(this[sn].currentSocket=void 0,!t)throw new Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[sn].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(t){this[sn]&&(this[sn].defaultPort=t)}get protocol(){return this[sn].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){this[sn]&&(this[sn].protocol=t)}}function un(...t){k.log("[https-proxy-agent:parse-proxy-response]",...t)}function an(t){return new Promise(((n,e)=>{let r=0;const o=[];function s(){const c=t.read();c?function(c){o.push(c),r+=c.length;const u=Buffer.concat(o,r),a=u.indexOf("\r\n\r\n");if(-1===a)return un("have not received end of HTTP headers yet..."),void s();const f=u.slice(0,a).toString("ascii").split("\r\n"),h=f.shift();if(!h)return t.destroy(),e(new Error("No header received from proxy CONNECT response"));const p=h.split(" "),l=+(p[1]||0),d=p.slice(2).join(" "),m={};for(const n of f){if(!n)continue;const r=n.indexOf(":");if(-1===r)return t.destroy(),e(new Error(`Invalid header from proxy CONNECT response: "${n}"`));const o=n.slice(0,r).toLowerCase(),s=n.slice(r+1).trimStart(),i=m[o];"string"==typeof i?m[o]=[i,s]:Array.isArray(i)?i.push(s):m[o]=s}un("got proxy server response: %o %o",h,m),i(),n({connect:{statusCode:l,statusText:d,headers:m},buffered:u})}(c):t.once("readable",s)}function i(){t.removeListener("end",c),t.removeListener("error",u),t.removeListener("readable",s)}function c(){i(),un("onend"),e(new Error("Proxy connection ended before receiving CONNECT response"))}function u(t){i(),un("onerror %o",t),e(t)}t.on("error",u),t.on("end",c),s()}))}function fn(...t){k.log("[https-proxy-agent]",...t)}class hn extends cn{static protocols=["http","https"];proxy;proxyHeaders;connectOpts;constructor(t,n){super(n),this.options={},this.proxy="string"==typeof t?new URL(t):t,this.proxyHeaders=n?.headers??{},fn("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const e=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?ln(n,"headers"):null,host:e,port:r}}async connect(t,n){const{proxy:e}=this;if(!n.host)throw new TypeError('No "host" provided');let r;if("https:"===e.protocol){fn("Creating `tls.Socket`: %o",this.connectOpts);const t=this.connectOpts.servername||this.connectOpts.host;r=f.connect({...this.connectOpts,servername:t&&a.isIP(t)?void 0:t})}else fn("Creating `net.Socket`: %o",this.connectOpts),r=a.connect(this.connectOpts);const o="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},s=a.isIPv6(n.host)?`[${n.host}]`:n.host;let i=`CONNECT ${s}:${n.port} HTTP/1.1\r\n`;if(e.username||e.password){const t=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(t).toString("base64")}`}o.Host=`${s}:${n.port}`,o["Proxy-Connection"]||(o["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(o))i+=`${t}: ${o[t]}\r\n`;const c=an(r);r.write(`${i}\r\n`);const{connect:u,buffered:h}=await c;if(t.emit("proxyConnect",u),this.emit("proxyConnect",u,t),200===u.statusCode){if(t.once("socket",pn),n.secureEndpoint){fn("Upgrading socket connection to TLS");const t=n.servername||n.host;return f.connect({...ln(n,"host","path","port"),socket:r,servername:a.isIP(t)?void 0:t})}return r}r.destroy();const p=new a.Socket({writable:!1});return p.readable=!0,t.once("socket",(t=>{fn("Replaying proxy buffer for failed request"),t.push(h),t.push(null)})),p}}function pn(t){t.resume()}function ln(t,...n){const e={};let r;for(r in t)n.includes(r)||(e[r]=t[r]);return e}const dn=32768;function mn(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}const yn=e;let gn,bn=!1;function _n(t){yn.debug&&console.log(`[ANR Worker] ${t}`)}var vn,wn,Sn;const $n=function(t){let n;try{n=new URL(t.url)}catch(n){return N((()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")})),rn(t,(()=>Promise.resolve({})))}const e="https:"===n.protocol,r=function(t,n){const{no_proxy:e}=process.env;return e&&e.split(",").some((n=>t.host.endsWith(n)||t.hostname.endsWith(n)))?void 0:n}(n,t.proxy||(e?process.env.https_proxy:void 0)||process.env.http_proxy),o=e?i:s,a=void 0!==t.keepAlive&&t.keepAlive,f=r?new hn(r):new o.Agent({keepAlive:a,maxSockets:30,timeout:2e3}),h=function(t,n,e){const{hostname:r,pathname:o,port:s,protocol:i,search:a}=new URL(t.url);return function(f){return new Promise(((h,p)=>{Qt((()=>{let l=function(t){return new c({read(){this.push(t),this.push(null)}})}(f.body);const d={...t.headers};f.body.length>dn&&(d["content-encoding"]="gzip",l=l.pipe(u()));const m=n.request({method:"POST",agent:e,headers:d,hostname:r,path:`${o}${a}`,port:s,protocol:i,ca:t.caCerts},(t=>{t.on("data",(()=>{})),t.on("end",(()=>{})),t.setEncoding("utf8");const n=t.headers["retry-after"]??null,e=t.headers["x-sentry-rate-limits"]??null;h({statusCode:t.statusCode,headers:{"retry-after":n,"x-sentry-rate-limits":Array.isArray(e)?e[0]||null:e}})}));m.on("error",p),l.pipe(m)}))}))}}(t,t.httpModule??o,f);return rn(t,h)}({url:(vn=yn.dsn,wn=yn.tunnel,Sn=yn.sdkMetadata.sdk,wn||`${function(t){return`${function(t){const n=t.protocol?`${t.protocol}:`:"",e=t.port?`:${t.port}`:"";return`${n}//${t.host}${e}${t.path?`/${t.path}`:""}/api/`}(t)}${t.projectId}/envelope/`}(vn)}?${nn(vn,Sn)}`),recordDroppedEvent:()=>{}});async function En(){if(gn){_n("Sending abnormal session"),bt(gn,{status:"abnormal",abnormal_mechanism:"anr_foreground"});const t=function(t,n,e,r){const o=ft(e);return ot({sent_at:(new Date).toISOString(),...o&&{sdk:o},...!!r&&n&&{dsn:C(n)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}(gn,yn.dsn,yn.sdkMetadata,yn.tunnel);_n(JSON.stringify(t)),await $n.send(t);try{n?.postMessage("session-ended")}catch(t){}}}function xn(t){if(!t)return;const n=function(t){if(!t.length)return[];const n=Array.from(t);return/sentryWrapped/.test(M(n).function||"")&&n.pop(),n.reverse(),U.test(M(n).function||"")&&(n.pop(),U.test(M(n).function||"")&&n.pop()),n.slice(0,I).map((t=>({...t,filename:t.filename||M(n).filename,function:t.function||P})))}(t);if(yn.appRootPath)for(const t of n)t.filename&&(t.filename=W(t.filename,yn.appRootPath));return n}async function Nn(t,n){if(bn)return;bn=!0,await En(),_n("Sending event");const e={event_id:Y(),contexts:yn.contexts,release:yn.release,environment:yn.environment,dist:yn.dist,platform:"node",level:"error",exception:{values:[{type:"ApplicationNotResponding",value:`Application Not Responding for at least ${yn.anrThreshold} ms`,stacktrace:{frames:xn(t)},mechanism:{type:"ANR"}}]},tags:yn.staticTags};n&&function(t,n){if(Xt(t,n),!t.contexts?.trace){const{traceId:e,spanId:r,parentSpanId:o}=n.propagationContext;t.contexts={trace:{trace_id:e,span_id:r,parent_span_id:o},...t.contexts}}}(e,n);const r=Vt(e,yn.dsn,yn.sdkMetadata,yn.tunnel);_n(JSON.stringify(r)),await $n.send(r),await $n.flush(2e3),setTimeout((()=>{process.exit(0)}),5e3)}let kn;if(_n("Started"),yn.captureStackTrace){_n("Connecting to debugger");const n=new t;n.connectToMainThread(),_n("Connected to debugger");const e=new Map;n.on("Debugger.scriptParsed",(t=>{e.set(t.params.scriptId,t.params.url)})),n.on("Debugger.paused",(t=>{if("other"===t.params.reason)try{_n("Debugger paused");const s=[...t.params.callFrames],i=yn.appRootPath?function(t=(process.argv[1]?F(process.argv[1]):process.cwd()),n="\\"===o){const e=n?mn(t):t;return t=>{if(!t)return;const o=n?mn(t):t;let{dir:s,base:i,ext:c}=r.parse(o);".js"!==c&&".mjs"!==c&&".cjs"!==c||(i=i.slice(0,-1*c.length)),s||(s=".");const u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${i}`;if(s.startsWith(e)){let t=s.slice(e.length+1).replace(/\//g,".");return t&&(t+=":"),t+=i,t}return i}}(yn.appRootPath):()=>{},c=s.map((t=>function(t,n,e){const r=n?n.replace(/^file:\/\//,""):void 0,o=t.location.columnNumber?t.location.columnNumber+1:void 0,s=t.location.lineNumber?t.location.lineNumber+1:void 0;return O({filename:r,module:e(r),function:t.functionName||P,colno:o,lineno:s,in_app:r?X(r):void 0})}(t,e.get(t.location.scriptId),i))),u=setTimeout((()=>{Nn(c).then(null,(()=>{_n("Sending ANR event failed.")}))}),5e3);n.post("Runtime.evaluate",{expression:"global.__SENTRY_GET_SCOPES__();",silent:!0,returnByValue:!0},((t,e)=>{t&&_n(`Error executing script: '${t.message}'`),clearTimeout(u);const r=e&&e.result?e.result.value:void 0;n.post("Debugger.resume"),n.post("Debugger.disable"),Nn(c,r).then(null,(()=>{_n("Sending ANR event failed.")}))}))}catch(t){throw n.post("Debugger.resume"),n.post("Debugger.disable"),t}})),kn=()=>{try{n.post("Debugger.enable",(()=>{n.post("Debugger.pause")}))}catch(t){}}}const{poll:Cn}=function(t,n,e,r){const o=t();let s=!1,i=!0;return setInterval((()=>{const t=o.getTimeMs();!1===s&&t>n+e&&(s=!0,i&&r()),t<n+e&&(s=!1)}),20),{poll:()=>{o.reset()},enabled:t=>{i=t}}}((function(){let t=process.hrtime();return{getTimeMs:()=>{const[n,e]=process.hrtime(t);return Math.floor(1e3*n+e/1e6)},reset:()=>{t=process.hrtime()}}}),yn.pollInterval,yn.anrThreshold,(function(){_n("Watchdog timeout"),kn?(_n("Pausing debugger to capture stack trace"),kn()):(_n("Capturing event without a stack trace"),Nn().then(null,(()=>{_n("Sending ANR event failed on watchdog timeout.")})))}));n?.on("message",(t=>{t.session&&(gn=gt(t.session)),Cn()}));
|
|
1
|
+
/*! @sentry/node 8.35.0-alpha.0 (314f51d) | https://github.com/getsentry/sentry-javascript */
|
|
2
|
+
import{Session as t}from"node:inspector";import{parentPort as n,workerData as e}from"node:worker_threads";import{posix as r,sep as o}from"node:path";import*as s from"node:http";import*as i from"node:https";import{Readable as c}from"node:stream";import{createGzip as u}from"node:zlib";import*as a from"node:net";import*as f from"node:tls";const h=Object.prototype.toString;function p(t,n){return h.call(t)===`[object ${n}]`}function l(t){return p(t,"String")}function d(t){return p(t,"Object")}function m(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function y(t,n){try{return t instanceof n}catch(t){return!1}}const g="8.35.0-alpha.0",b=globalThis;function _(t,n,e){const r=e||b,o=r.__SENTRY__=r.__SENTRY__||{},s=o[g]=o[g]||{};return s[t]||(s[t]=n())}const v=b,w=80;function S(t,n){const e=t,r=[];if(!e||!e.tagName)return"";if(v.HTMLElement&&e instanceof HTMLElement&&e.dataset){if(e.dataset.sentryComponent)return e.dataset.sentryComponent;if(e.dataset.sentryElement)return e.dataset.sentryElement}r.push(e.tagName.toLowerCase());const o=n&&n.length?n.filter((t=>e.getAttribute(t))).map((t=>[t,e.getAttribute(t)])):null;if(o&&o.length)o.forEach((t=>{r.push(`[${t[0]}="${t[1]}"]`)}));else{e.id&&r.push(`#${e.id}`);const t=e.className;if(t&&l(t)){const n=t.split(/\s+/);for(const t of n)r.push(`.${t}`)}}const s=["aria-label","type","name","title","alt"];for(const t of s){const n=e.getAttribute(t);n&&r.push(`[${t}="${n}"]`)}return r.join("")}const $="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,E=["debug","info","warn","error","log","assert","trace"],x={};function N(t){if(!("console"in b))return t();const n=b.console,e={},r=Object.keys(x);r.forEach((t=>{const r=x[t];e[t]=n[t],n[t]=r}));try{return t()}finally{r.forEach((t=>{n[t]=e[t]}))}}const k=_("logger",(function(){let t=!1;const n={enable:()=>{t=!0},disable:()=>{t=!1},isEnabled:()=>t};return $?E.forEach((e=>{n[e]=(...n)=>{t&&N((()=>{b.console[e](`Sentry Logger [${e}]:`,...n)}))}})):E.forEach((t=>{n[t]=()=>{}})),n}));function C(t,n=!1){const{host:e,path:r,pass:o,port:s,projectId:i,protocol:c,publicKey:u}=t;return`${c}://${u}${n&&o?`:${o}`:""}@${e}${s?`:${s}`:""}/${r?`${r}/`:r}${i}`}class T extends Error{constructor(t,n="warn"){super(t),this.message=t,this.name=new.target.prototype.constructor.name,Object.setPrototypeOf(this,new.target.prototype),this.logLevel=n}}function R(t){if(function(t){switch(h.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return y(t,Error)}}(t))return{message:t.message,name:t.name,stack:t.stack,...j(t)};if(n=t,"undefined"!=typeof Event&&y(n,Event)){const n={type:t.type,target:D(t.target),currentTarget:D(t.currentTarget),...j(t)};return"undefined"!=typeof CustomEvent&&y(t,CustomEvent)&&(n.detail=t.detail),n}return t;var n}function D(t){try{return n=t,"undefined"!=typeof Element&&y(n,Element)?function(t,n={}){if(!t)return"<unknown>";try{let e=t;const r=5,o=[];let s=0,i=0;const c=" > ",u=c.length;let a;const f=Array.isArray(n)?n:n.keyAttrs,h=!Array.isArray(n)&&n.maxStringLength||w;for(;e&&s++<r&&(a=S(e,f),!("html"===a||s>1&&i+o.length*u+a.length>=h));)o.push(a),i+=a.length,e=e.parentNode;return o.reverse().join(c)}catch(t){return"<unknown>"}}(t):Object.prototype.toString.call(t)}catch(t){return"<unknown>"}var n}function j(t){if("object"==typeof t&&null!==t){const n={};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e]);return n}return{}}function O(t){return A(t,new Map)}function A(t,n){if(function(t){if(!d(t))return!1;try{const n=Object.getPrototypeOf(t).constructor.name;return!n||"Object"===n}catch(t){return!0}}(t)){const e=n.get(t);if(void 0!==e)return e;const r={};n.set(t,r);for(const e of Object.getOwnPropertyNames(t))void 0!==t[e]&&(r[e]=A(t[e],n));return r}if(Array.isArray(t)){const e=n.get(t);if(void 0!==e)return e;const r=[];return n.set(t,r),t.forEach((t=>{r.push(A(t,n))})),r}return t}const I=50,P="?",U=/captureMessage|captureException/;function M(t){return t[t.length-1]||{}}const L="<anonymous>";const B=1e3;function G(){return Date.now()/B}const J=function(){const{performance:t}=b;if(!t||!t.now)return G;const n=Date.now()-t.now(),e=null==t.timeOrigin?n:t.timeOrigin;return()=>(e+t.now())/B}();function Y(){const t=b,n=t.crypto||t.msCrypto;let e=()=>16*Math.random();try{if(n&&n.randomUUID)return n.randomUUID().replace(/-/g,"");n&&n.getRandomValues&&(e=()=>{const t=new Uint8Array(1);return n.getRandomValues(t),t[0]})}catch(t){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(t=>(t^(15&e())>>t/4).toString(16)))}function z(t,n=100,e=1/0){try{return H("",t,n,e)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function H(t,n,e=1/0,r=1/0,o=function(){const t="function"==typeof WeakSet,n=t?new WeakSet:[];return[function(e){if(t)return!!n.has(e)||(n.add(e),!1);for(let t=0;t<n.length;t++)if(n[t]===e)return!0;return n.push(e),!1},function(e){if(t)n.delete(e);else for(let t=0;t<n.length;t++)if(n[t]===e){n.splice(t,1);break}}]}()){const[s,i]=o;if(null==n||["boolean","string"].includes(typeof n)||"number"==typeof n&&Number.isFinite(n))return n;const c=function(t,n){try{if("domain"===t&&n&&"object"==typeof n&&n.t)return"[Domain]";if("domainEmitter"===t)return"[DomainEmitter]";if("undefined"!=typeof global&&n===global)return"[Global]";if("undefined"!=typeof window&&n===window)return"[Window]";if("undefined"!=typeof document&&n===document)return"[Document]";if("object"==typeof(e=n)&&null!==e&&(e.__isVue||e.o))return"[VueViewModel]";if(function(t){return d(t)&&"nativeEvent"in t&&"preventDefault"in t&&"stopPropagation"in t}(n))return"[SyntheticEvent]";if("number"==typeof n&&!Number.isFinite(n))return`[${n}]`;if("function"==typeof n)return`[Function: ${function(t){try{return t&&"function"==typeof t&&t.name||L}catch(t){return L}}(n)}]`;if("symbol"==typeof n)return`[${String(n)}]`;if("bigint"==typeof n)return`[BigInt: ${String(n)}]`;const r=function(t){const n=Object.getPrototypeOf(t);return n?n.constructor.name:"null prototype"}(n);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(t){return`**non-serializable** (${t})`}var e}(t,n);if(!c.startsWith("[object "))return c;if(n.__sentry_skip_normalization__)return n;const u="number"==typeof n.__sentry_override_normalization_depth__?n.__sentry_override_normalization_depth__:e;if(0===u)return c.replace("object ","");if(s(n))return"[Circular ~]";const a=n;if(a&&"function"==typeof a.toJSON)try{return H("",a.toJSON(),u-1,r,o)}catch(t){}const f=Array.isArray(n)?[]:{};let h=0;const p=R(n);for(const t in p){if(!Object.prototype.hasOwnProperty.call(p,t))continue;if(h>=r){f[t]="[MaxProperties ~]";break}const n=p[t];f[t]=H(t,n,u-1,r,o),h++}return i(n),f}function W(t,n){const e=n.replace(/\\/g,"/").replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");let r=t;try{r=decodeURI(t)}catch(t){}return r.replace(/\\/g,"/").replace(/webpack:\/?/g,"").replace(new RegExp(`(file://)?/*${e}/*`,"ig"),"app:///")}(()=>{const{performance:t}=b;if(!t||!t.now)return;const n=36e5,e=t.now(),r=Date.now(),o=t.timeOrigin?Math.abs(t.timeOrigin+e-r):n,s=o<n,i=t.timing&&t.timing.navigationStart,c="number"==typeof i?Math.abs(i+e-r):n;(s||c<n)&&(o<=c&&t.timeOrigin)})();const q=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function F(t){const n=function(t){const n=t.length>1024?`<truncated>${t.slice(-1024)}`:t,e=q.exec(n);return e?e.slice(1):[]}(t),e=n[0]||"";let r=n[1];return e||r?(r&&(r=r.slice(0,r.length-1)),e+r):"."}var K;function V(t){return new Z((n=>{n(t)}))}!function(t){t[t.PENDING=0]="PENDING";t[t.RESOLVED=1]="RESOLVED";t[t.REJECTED=2]="REJECTED"}(K||(K={}));class Z{constructor(t){Z.prototype.__init.call(this),Z.prototype.__init2.call(this),Z.prototype.__init3.call(this),Z.prototype.__init4.call(this),this.i=K.PENDING,this.u=[];try{t(this.h,this.p)}catch(t){this.p(t)}}then(t,n){return new Z(((e,r)=>{this.u.push([!1,n=>{if(t)try{e(t(n))}catch(t){r(t)}else e(n)},t=>{if(n)try{e(n(t))}catch(t){r(t)}else r(t)}]),this.l()}))}catch(t){return this.then((t=>t),t)}finally(t){return new Z(((n,e)=>{let r,o;return this.then((n=>{o=!1,r=n,t&&t()}),(n=>{o=!0,r=n,t&&t()})).then((()=>{o?e(r):n(r)}))}))}__init(){this.h=t=>{this.m(K.RESOLVED,t)}}__init2(){this.p=t=>{this.m(K.REJECTED,t)}}__init3(){this.m=(t,n)=>{this.i===K.PENDING&&(m(n)?n.then(this.h,this.p):(this.i=t,this._=n,this.l()))}}__init4(){this.l=()=>{if(this.i===K.PENDING)return;const t=this.u.slice();this.u=[],t.forEach((t=>{t[0]||(this.i===K.RESOLVED&&t[1](this._),this.i===K.REJECTED&&t[2](this._),t[0]=!0)}))}}}function Q(t){const n=[];function e(t){return n.splice(n.indexOf(t),1)[0]||Promise.resolve(void 0)}return{$:n,add:function(r){if(!(void 0===t||n.length<t))return o=new T("Not adding Promise because buffer limit was reached."),new Z(((t,n)=>{n(o)}));var o;const s=r();return-1===n.indexOf(s)&&n.push(s),s.then((()=>e(s))).then(null,(()=>e(s).then(null,(()=>{})))),s},drain:function(t){return new Z(((e,r)=>{let o=n.length;if(!o)return e(!0);const s=setTimeout((()=>{t&&t>0&&e(!1)}),t);n.forEach((t=>{V(t).then((()=>{--o||(clearTimeout(s),e(!0))}),r)}))}))}}}function X(t,n=!1){return!(n||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==t&&!t.includes("node_modules/")}const tt="sentry-",nt=/^sentry-/;function et(t){const n=function(t){if(!t||!l(t)&&!Array.isArray(t))return;if(Array.isArray(t))return t.reduce(((t,n)=>{const e=rt(n);return Object.entries(e).forEach((([n,e])=>{t[n]=e})),t}),{});return rt(t)}(t);if(!n)return;const e=Object.entries(n).reduce(((t,[n,e])=>{if(n.match(nt)){t[n.slice(tt.length)]=e}return t}),{});return Object.keys(e).length>0?e:void 0}function rt(t){return t.split(",").map((t=>t.split("=").map((t=>decodeURIComponent(t.trim()))))).reduce(((t,[n,e])=>(n&&e&&(t[n]=e),t)),{})}function ot(t,n=[]){return[t,n]}function st(t,n){const e=t[1];for(const t of e){if(n(t,t[0].type))return!0}return!1}function it(t){return b.__SENTRY__&&b.__SENTRY__.encodePolyfill?b.__SENTRY__.encodePolyfill(t):(new TextEncoder).encode(t)}function ct(t){const[n,e]=t;let r=JSON.stringify(n);function o(t){"string"==typeof r?r="string"==typeof t?r+t:[it(r),t]:r.push("string"==typeof t?it(t):t)}for(const t of e){const[n,e]=t;if(o(`\n${JSON.stringify(n)}\n`),"string"==typeof e||e instanceof Uint8Array)o(e);else{let t;try{t=JSON.stringify(e)}catch(n){t=JSON.stringify(z(e))}o(t)}}return"string"==typeof r?r:function(t){const n=t.reduce(((t,n)=>t+n.length),0),e=new Uint8Array(n);let r=0;for(const n of t)e.set(n,r),r+=n.length;return e}(r)}const ut={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket"};function at(t){return ut[t]}function ft(t){if(!t||!t.sdk)return;const{name:n,version:e}=t.sdk;return{name:n,version:e}}const ht=6e4;function pt(t,{statusCode:n,headers:e},r=Date.now()){const o={...t},s=e&&e["x-sentry-rate-limits"],i=e&&e["retry-after"];if(s)for(const t of s.trim().split(",")){const[n,e,,,s]=t.split(":",5),i=parseInt(n,10),c=1e3*(isNaN(i)?60:i);if(e)for(const t of e.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(o[t]=r+c);else o.all=r+c}else i?o.all=r+function(t,n=Date.now()){const e=parseInt(`${t}`,10);if(!isNaN(e))return 1e3*e;const r=Date.parse(`${t}`);return isNaN(r)?ht:r-n}(i,r):429===n&&(o.all=r+6e4);return o}function lt(){return{traceId:Y(),spanId:Y().substring(16)}}const dt="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function mt(){return yt(b),b}function yt(t){const n=t.__SENTRY__=t.__SENTRY__||{};return n.version=n.version||g,n[g]=n[g]||{}}function gt(t){const n=J(),e={sid:Y(),init:!0,timestamp:n,started:n,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return O({sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}})}(e)};return t&&bt(e,t),e}function bt(t,n={}){if(n.user&&(!t.ipAddress&&n.user.ip_address&&(t.ipAddress=n.user.ip_address),t.did||n.did||(t.did=n.user.id||n.user.email||n.user.username)),t.timestamp=n.timestamp||J(),n.abnormal_mechanism&&(t.abnormal_mechanism=n.abnormal_mechanism),n.ignoreDuration&&(t.ignoreDuration=n.ignoreDuration),n.sid&&(t.sid=32===n.sid.length?n.sid:Y()),void 0!==n.init&&(t.init=n.init),!t.did&&n.did&&(t.did=`${n.did}`),"number"==typeof n.started&&(t.started=n.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof n.duration)t.duration=n.duration;else{const n=t.timestamp-t.started;t.duration=n>=0?n:0}n.release&&(t.release=n.release),n.environment&&(t.environment=n.environment),!t.ipAddress&&n.ipAddress&&(t.ipAddress=n.ipAddress),!t.userAgent&&n.userAgent&&(t.userAgent=n.userAgent),"number"==typeof n.errors&&(t.errors=n.errors),n.status&&(t.status=n.status)}const _t="_sentrySpan";function vt(t,n){n?function(t,n,e){try{Object.defineProperty(t,n,{value:e,writable:!0,configurable:!0})}catch(e){$&&k.log(`Failed to add non-enumerable property "${n}" to object`,t)}}(t,_t,n):delete t[_t]}function wt(t){return t[_t]}class St{constructor(){this.v=!1,this.S=[],this.N=[],this.k=[],this.C=[],this.T={},this.R={},this.D={},this.j={},this.O={},this.A=lt()}clone(){const t=new St;return t.k=[...this.k],t.R={...this.R},t.D={...this.D},t.j={...this.j},t.T=this.T,t.I=this.I,t.P=this.P,t.U=this.U,t.M=this.M,t.N=[...this.N],t.L=this.L,t.C=[...this.C],t.O={...this.O},t.A={...this.A},t.B=this.B,t.G=this.G,vt(t,wt(this)),t}setClient(t){this.B=t}setLastEventId(t){this.G=t}getClient(){return this.B}lastEventId(){return this.G}addScopeListener(t){this.S.push(t)}addEventProcessor(t){return this.N.push(t),this}setUser(t){return this.T=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this.P&&bt(this.P,{user:t}),this.J(),this}getUser(){return this.T}getRequestSession(){return this.L}setRequestSession(t){return this.L=t,this}setTags(t){return this.R={...this.R,...t},this.J(),this}setTag(t,n){return this.R={...this.R,[t]:n},this.J(),this}setExtras(t){return this.D={...this.D,...t},this.J(),this}setExtra(t,n){return this.D={...this.D,[t]:n},this.J(),this}setFingerprint(t){return this.M=t,this.J(),this}setLevel(t){return this.I=t,this.J(),this}setTransactionName(t){return this.U=t,this.J(),this}setContext(t,n){return null===n?delete this.j[t]:this.j[t]=n,this.J(),this}setSession(t){return t?this.P=t:delete this.P,this.J(),this}getSession(){return this.P}update(t){if(!t)return this;const n="function"==typeof t?t(this):t,[e,r]=n instanceof $t?[n.getScopeData(),n.getRequestSession()]:d(n)?[t,t.requestSession]:[],{tags:o,extra:s,user:i,contexts:c,level:u,fingerprint:a=[],propagationContext:f}=e||{};return this.R={...this.R,...o},this.D={...this.D,...s},this.j={...this.j,...c},i&&Object.keys(i).length&&(this.T=i),u&&(this.I=u),a.length&&(this.M=a),f&&(this.A=f),r&&(this.L=r),this}clear(){return this.k=[],this.R={},this.D={},this.T={},this.j={},this.I=void 0,this.U=void 0,this.M=void 0,this.L=void 0,this.P=void 0,vt(this,void 0),this.C=[],this.A=lt(),this.J(),this}addBreadcrumb(t,n){const e="number"==typeof n?n:100;if(e<=0)return this;const r={timestamp:G(),...t},o=this.k;return o.push(r),this.k=o.length>e?o.slice(-e):o,this.J(),this}getLastBreadcrumb(){return this.k[this.k.length-1]}clearBreadcrumbs(){return this.k=[],this.J(),this}addAttachment(t){return this.C.push(t),this}clearAttachments(){return this.C=[],this}getScopeData(){return{breadcrumbs:this.k,attachments:this.C,contexts:this.j,tags:this.R,extra:this.D,user:this.T,level:this.I,fingerprint:this.M||[],eventProcessors:this.N,propagationContext:this.A,sdkProcessingMetadata:this.O,transactionName:this.U,span:wt(this)}}setSDKProcessingMetadata(t){return this.O={...this.O,...t},this}setPropagationContext(t){return this.A=t,this}getPropagationContext(){return this.A}captureException(t,n){const e=n&&n.event_id?n.event_id:Y();if(!this.B)return k.warn("No client configured on scope - will not capture exception!"),e;const r=new Error("Sentry syntheticException");return this.B.captureException(t,{originalException:t,syntheticException:r,...n,event_id:e},this),e}captureMessage(t,n,e){const r=e&&e.event_id?e.event_id:Y();if(!this.B)return k.warn("No client configured on scope - will not capture message!"),r;const o=new Error(t);return this.B.captureMessage(t,n,{originalException:t,syntheticException:o,...e,event_id:r},this),r}captureEvent(t,n){const e=n&&n.event_id?n.event_id:Y();return this.B?(this.B.captureEvent(t,{...n,event_id:e},this),e):(k.warn("No client configured on scope - will not capture event!"),e)}J(){this.v||(this.v=!0,this.S.forEach((t=>{t(this)})),this.v=!1)}}const $t=St;class Et{constructor(t,n){let e,r;e=t||new $t,r=n||new $t,this.Y=[{scope:e}],this.H=r}withScope(t){const n=this.W();let e;try{e=t(n)}catch(t){throw this.q(),t}return m(e)?e.then((t=>(this.q(),t)),(t=>{throw this.q(),t})):(this.q(),e)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this.H}getStackTop(){return this.Y[this.Y.length-1]}W(){const t=this.getScope().clone();return this.Y.push({client:this.getClient(),scope:t}),t}q(){return!(this.Y.length<=1)&&!!this.Y.pop()}}function xt(){const t=yt(mt());return t.stack=t.stack||new Et(_("defaultCurrentScope",(()=>new $t)),_("defaultIsolationScope",(()=>new $t)))}function Nt(t){return xt().withScope(t)}function kt(t,n){const e=xt();return e.withScope((()=>(e.getStackTop().scope=t,n(t))))}function Ct(t){return xt().withScope((()=>t(xt().getIsolationScope())))}function Tt(t){const n=yt(t);return n.acs?n.acs:{withIsolationScope:Ct,withScope:Nt,withSetScope:kt,withSetIsolationScope:(t,n)=>Ct(n),getCurrentScope:()=>xt().getScope(),getIsolationScope:()=>xt().getIsolationScope()}}function Rt(){return Tt(mt()).getCurrentScope().getClient()}const Dt="_sentryMetrics";function jt(t){const n=t[Dt];if(!n)return;const e={};for(const[,[t,r]]of n){(e[t]||(e[t]=[])).push(O(r))}return e}const Ot="sentry.source",At="sentry.sample_rate",It="sentry.op",Pt="sentry.origin",Ut=0,Mt=1,Lt=1;function Bt(t){const{spanId:n,traceId:e}=t.spanContext(),{parent_span_id:r}=Yt(t);return O({parent_span_id:r,span_id:n,trace_id:e})}function Gt(t){return"number"==typeof t?Jt(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?Jt(t.getTime()):J()}function Jt(t){return t>9999999999?t/1e3:t}function Yt(t){if(function(t){return"function"==typeof t.getSpanJSON}(t))return t.getSpanJSON();try{const{spanId:n,traceId:e}=t.spanContext();if(function(t){const n=t;return!!(n.attributes&&n.startTime&&n.name&&n.endTime&&n.status)}(t)){const{attributes:r,startTime:o,name:s,endTime:i,parentSpanId:c,status:u}=t;return O({span_id:n,trace_id:e,data:r,description:s,parent_span_id:c,start_timestamp:Gt(o),timestamp:Gt(i)||void 0,status:zt(u),op:r[It],origin:r[Pt],_metrics_summary:jt(t)})}return{span_id:n,trace_id:e}}catch(t){return{}}}function zt(t){if(t&&t.code!==Ut)return t.code===Mt?"ok":t.message||"unknown_error"}const Ht="_sentryRootSpan";function Wt(t){return t[Ht]||t}const qt="production",Ft="_frozenDsc";function Kt(t){const n=Rt();if(!n)return{};const e=function(t,n){const e=n.getOptions(),{publicKey:r}=n.getDsn()||{},o=O({environment:e.environment||qt,release:e.release,public_key:r,trace_id:t});return n.emit("createDsc",o),o}(Yt(t).trace_id||"",n),r=Wt(t),o=r[Ft];if(o)return o;const s=r.spanContext().traceState,i=s&&s.get("sentry.dsc"),c=i&&et(i);if(c)return c;const u=Yt(r),a=u.data||{},f=a[At];null!=f&&(e.sample_rate=`${f}`);const h=a[Ot],p=u.description;return"url"!==h&&p&&(e.transaction=p),function(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const n=Rt(),e=t||n&&n.getOptions();return!!e&&(e.enableTracing||"tracesSampleRate"in e||"tracesSampler"in e)}()&&(e.sampled=String(function(t){const{traceFlags:n}=t.spanContext();return n===Lt}(r))),n.emit("createDsc",e,r),e}function Vt(t,n,e,r){const o=ft(e),s=t.type&&"replay_event"!==t.type?t.type:"event";!function(t,n){n&&(t.sdk=t.sdk||{},t.sdk.name=t.sdk.name||n.name,t.sdk.version=t.sdk.version||n.version,t.sdk.integrations=[...t.sdk.integrations||[],...n.integrations||[]],t.sdk.packages=[...t.sdk.packages||[],...n.packages||[]])}(t,e&&e.sdk);const i=function(t,n,e,r){const o=t.sdkProcessingMetadata&&t.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:t.event_id,sent_at:(new Date).toISOString(),...n&&{sdk:n},...!!e&&r&&{dsn:C(r)},...o&&{trace:O({...o})}}}(t,o,r,n);delete t.sdkProcessingMetadata;return ot(i,[[{type:s},t]])}const Zt="__SENTRY_SUPPRESS_TRACING__";function Qt(t){const n=Tt(mt());return n.suppressTracing?n.suppressTracing(t):function(...t){const n=Tt(mt());if(2===t.length){const[e,r]=t;return e?n.withSetScope(e,r):n.withScope(r)}return n.withScope(t[0])}((n=>(n.setSDKProcessingMetadata({[Zt]:!0}),t())))}function Xt(t,n){const{fingerprint:e,span:r,breadcrumbs:o,sdkProcessingMetadata:s}=n;!function(t,n){const{extra:e,tags:r,user:o,contexts:s,level:i,transactionName:c}=n,u=O(e);u&&Object.keys(u).length&&(t.extra={...u,...t.extra});const a=O(r);a&&Object.keys(a).length&&(t.tags={...a,...t.tags});const f=O(o);f&&Object.keys(f).length&&(t.user={...f,...t.user});const h=O(s);h&&Object.keys(h).length&&(t.contexts={...h,...t.contexts});i&&(t.level=i);c&&"transaction"!==t.type&&(t.transaction=c)}(t,n),r&&function(t,n){t.contexts={trace:Bt(n),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:Kt(n),...t.sdkProcessingMetadata};const e=Wt(n),r=Yt(e).description;r&&!t.transaction&&"transaction"===t.type&&(t.transaction=r)}(t,r),function(t,n){t.fingerprint=t.fingerprint?function(t){return Array.isArray(t)?t:[t]}(t.fingerprint):[],n&&(t.fingerprint=t.fingerprint.concat(n));t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,e),function(t,n){const e=[...t.breadcrumbs||[],...n];t.breadcrumbs=e.length?e:void 0}(t,o),function(t,n){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...n}}(t,s)}const tn="7";function nn(t,n){return e={sentry_key:t.publicKey,sentry_version:tn,...n&&{sentry_client:`${n.name}/${n.version}`}},Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&");var e}const en=64;function rn(t,n,e=Q(t.bufferSize||en)){let r={};return{send:function(o){const s=[];if(st(o,((n,e)=>{const o=at(e);if(function(t,n,e=Date.now()){return function(t,n){return t[n]||t.all||0}(t,n)>e}(r,o)){const r=on(n,e);t.recordDroppedEvent("ratelimit_backoff",o,r)}else s.push(n)})),0===s.length)return V({});const i=ot(o[0],s),c=n=>{st(i,((e,r)=>{const o=on(e,r);t.recordDroppedEvent(n,at(r),o)}))};return e.add((()=>n({body:ct(i)}).then((t=>(void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&dt&&k.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=pt(r,t),t)),(t=>{throw c("network_error"),t})))).then((t=>t),(t=>{if(t instanceof T)return dt&&k.error("Skipped sending event because buffer is full."),c("queue_overflow"),V({});throw t}))},flush:t=>e.drain(t)}}function on(t,n){if("event"===n||"transaction"===n)return Array.isArray(t)?t[1]:void 0}const sn=Symbol("AgentBaseInternalState");class cn extends s.Agent{[sn];options;keepAlive;constructor(t){super(t),this[sn]={}}isSecureEndpoint(t){if(t){if("boolean"==typeof t.secureEndpoint)return t.secureEndpoint;if("string"==typeof t.protocol)return"https:"===t.protocol}const{stack:n}=new Error;return"string"==typeof n&&n.split("\n").some((t=>-1!==t.indexOf("(https.js:")||-1!==t.indexOf("node:https:")))}createSocket(t,n,e){const r={...n,secureEndpoint:this.isSecureEndpoint(n)};Promise.resolve().then((()=>this.connect(t,r))).then((o=>{if(o instanceof s.Agent)return o.addRequest(t,r);this[sn].currentSocket=o,super.createSocket(t,n,e)}),e)}createConnection(){const t=this[sn].currentSocket;if(this[sn].currentSocket=void 0,!t)throw new Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[sn].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(t){this[sn]&&(this[sn].defaultPort=t)}get protocol(){return this[sn].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){this[sn]&&(this[sn].protocol=t)}}function un(...t){k.log("[https-proxy-agent:parse-proxy-response]",...t)}function an(t){return new Promise(((n,e)=>{let r=0;const o=[];function s(){const c=t.read();c?function(c){o.push(c),r+=c.length;const u=Buffer.concat(o,r),a=u.indexOf("\r\n\r\n");if(-1===a)return un("have not received end of HTTP headers yet..."),void s();const f=u.slice(0,a).toString("ascii").split("\r\n"),h=f.shift();if(!h)return t.destroy(),e(new Error("No header received from proxy CONNECT response"));const p=h.split(" "),l=+(p[1]||0),d=p.slice(2).join(" "),m={};for(const n of f){if(!n)continue;const r=n.indexOf(":");if(-1===r)return t.destroy(),e(new Error(`Invalid header from proxy CONNECT response: "${n}"`));const o=n.slice(0,r).toLowerCase(),s=n.slice(r+1).trimStart(),i=m[o];"string"==typeof i?m[o]=[i,s]:Array.isArray(i)?i.push(s):m[o]=s}un("got proxy server response: %o %o",h,m),i(),n({connect:{statusCode:l,statusText:d,headers:m},buffered:u})}(c):t.once("readable",s)}function i(){t.removeListener("end",c),t.removeListener("error",u),t.removeListener("readable",s)}function c(){i(),un("onend"),e(new Error("Proxy connection ended before receiving CONNECT response"))}function u(t){i(),un("onerror %o",t),e(t)}t.on("error",u),t.on("end",c),s()}))}function fn(...t){k.log("[https-proxy-agent]",...t)}class hn extends cn{static protocols=["http","https"];proxy;proxyHeaders;connectOpts;constructor(t,n){super(n),this.options={},this.proxy="string"==typeof t?new URL(t):t,this.proxyHeaders=n?.headers??{},fn("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const e=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?ln(n,"headers"):null,host:e,port:r}}async connect(t,n){const{proxy:e}=this;if(!n.host)throw new TypeError('No "host" provided');let r;if("https:"===e.protocol){fn("Creating `tls.Socket`: %o",this.connectOpts);const t=this.connectOpts.servername||this.connectOpts.host;r=f.connect({...this.connectOpts,servername:t&&a.isIP(t)?void 0:t})}else fn("Creating `net.Socket`: %o",this.connectOpts),r=a.connect(this.connectOpts);const o="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},s=a.isIPv6(n.host)?`[${n.host}]`:n.host;let i=`CONNECT ${s}:${n.port} HTTP/1.1\r\n`;if(e.username||e.password){const t=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(t).toString("base64")}`}o.Host=`${s}:${n.port}`,o["Proxy-Connection"]||(o["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(o))i+=`${t}: ${o[t]}\r\n`;const c=an(r);r.write(`${i}\r\n`);const{connect:u,buffered:h}=await c;if(t.emit("proxyConnect",u),this.emit("proxyConnect",u,t),200===u.statusCode){if(t.once("socket",pn),n.secureEndpoint){fn("Upgrading socket connection to TLS");const t=n.servername||n.host;return f.connect({...ln(n,"host","path","port"),socket:r,servername:a.isIP(t)?void 0:t})}return r}r.destroy();const p=new a.Socket({writable:!1});return p.readable=!0,t.once("socket",(t=>{fn("Replaying proxy buffer for failed request"),t.push(h),t.push(null)})),p}}function pn(t){t.resume()}function ln(t,...n){const e={};let r;for(r in t)n.includes(r)||(e[r]=t[r]);return e}const dn=32768;function mn(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}const yn=e;let gn,bn=!1;function _n(t){yn.debug&&console.log(`[ANR Worker] ${t}`)}var vn,wn,Sn;const $n=function(t){let n;try{n=new URL(t.url)}catch(n){return N((()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")})),rn(t,(()=>Promise.resolve({})))}const e="https:"===n.protocol,r=function(t,n){const{no_proxy:e}=process.env;return e&&e.split(",").some((n=>t.host.endsWith(n)||t.hostname.endsWith(n)))?void 0:n}(n,t.proxy||(e?process.env.https_proxy:void 0)||process.env.http_proxy),o=e?i:s,a=void 0!==t.keepAlive&&t.keepAlive,f=r?new hn(r):new o.Agent({keepAlive:a,maxSockets:30,timeout:2e3}),h=function(t,n,e){const{hostname:r,pathname:o,port:s,protocol:i,search:a}=new URL(t.url);return function(f){return new Promise(((h,p)=>{Qt((()=>{let l=function(t){return new c({read(){this.push(t),this.push(null)}})}(f.body);const d={...t.headers};f.body.length>dn&&(d["content-encoding"]="gzip",l=l.pipe(u()));const m=n.request({method:"POST",agent:e,headers:d,hostname:r,path:`${o}${a}`,port:s,protocol:i,ca:t.caCerts},(t=>{t.on("data",(()=>{})),t.on("end",(()=>{})),t.setEncoding("utf8");const n=t.headers["retry-after"]??null,e=t.headers["x-sentry-rate-limits"]??null;h({statusCode:t.statusCode,headers:{"retry-after":n,"x-sentry-rate-limits":Array.isArray(e)?e[0]||null:e}})}));m.on("error",p),l.pipe(m)}))}))}}(t,t.httpModule??o,f);return rn(t,h)}({url:(vn=yn.dsn,wn=yn.tunnel,Sn=yn.sdkMetadata.sdk,wn||`${function(t){return`${function(t){const n=t.protocol?`${t.protocol}:`:"",e=t.port?`:${t.port}`:"";return`${n}//${t.host}${e}${t.path?`/${t.path}`:""}/api/`}(t)}${t.projectId}/envelope/`}(vn)}?${nn(vn,Sn)}`),recordDroppedEvent:()=>{}});async function En(){if(gn){_n("Sending abnormal session"),bt(gn,{status:"abnormal",abnormal_mechanism:"anr_foreground"});const t=function(t,n,e,r){const o=ft(e);return ot({sent_at:(new Date).toISOString(),...o&&{sdk:o},...!!r&&n&&{dsn:C(n)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}(gn,yn.dsn,yn.sdkMetadata,yn.tunnel);_n(JSON.stringify(t)),await $n.send(t);try{n?.postMessage("session-ended")}catch(t){}}}function xn(t){if(!t)return;const n=function(t){if(!t.length)return[];const n=Array.from(t);return/sentryWrapped/.test(M(n).function||"")&&n.pop(),n.reverse(),U.test(M(n).function||"")&&(n.pop(),U.test(M(n).function||"")&&n.pop()),n.slice(0,I).map((t=>({...t,filename:t.filename||M(n).filename,function:t.function||P})))}(t);if(yn.appRootPath)for(const t of n)t.filename&&(t.filename=W(t.filename,yn.appRootPath));return n}async function Nn(t,n){if(bn)return;bn=!0,await En(),_n("Sending event");const e={event_id:Y(),contexts:yn.contexts,release:yn.release,environment:yn.environment,dist:yn.dist,platform:"node",level:"error",exception:{values:[{type:"ApplicationNotResponding",value:`Application Not Responding for at least ${yn.anrThreshold} ms`,stacktrace:{frames:xn(t)},mechanism:{type:"ANR"}}]},tags:yn.staticTags};n&&function(t,n){if(Xt(t,n),!t.contexts?.trace){const{traceId:e,spanId:r,parentSpanId:o}=n.propagationContext;t.contexts={trace:{trace_id:e,span_id:r,parent_span_id:o},...t.contexts}}}(e,n);const r=Vt(e,yn.dsn,yn.sdkMetadata,yn.tunnel);_n(JSON.stringify(r)),await $n.send(r),await $n.flush(2e3),setTimeout((()=>{process.exit(0)}),5e3)}let kn;if(_n("Started"),yn.captureStackTrace){_n("Connecting to debugger");const n=new t;n.connectToMainThread(),_n("Connected to debugger");const e=new Map;n.on("Debugger.scriptParsed",(t=>{e.set(t.params.scriptId,t.params.url)})),n.on("Debugger.paused",(t=>{if("other"===t.params.reason)try{_n("Debugger paused");const s=[...t.params.callFrames],i=yn.appRootPath?function(t=(process.argv[1]?F(process.argv[1]):process.cwd()),n="\\"===o){const e=n?mn(t):t;return t=>{if(!t)return;const o=n?mn(t):t;let{dir:s,base:i,ext:c}=r.parse(o);".js"!==c&&".mjs"!==c&&".cjs"!==c||(i=i.slice(0,-1*c.length)),s||(s=".");const u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${i}`;if(s.startsWith(e)){let t=s.slice(e.length+1).replace(/\//g,".");return t&&(t+=":"),t+=i,t}return i}}(yn.appRootPath):()=>{},c=s.map((t=>function(t,n,e){const r=n?n.replace(/^file:\/\//,""):void 0,o=t.location.columnNumber?t.location.columnNumber+1:void 0,s=t.location.lineNumber?t.location.lineNumber+1:void 0;return O({filename:r,module:e(r),function:t.functionName||P,colno:o,lineno:s,in_app:r?X(r):void 0})}(t,e.get(t.location.scriptId),i))),u=setTimeout((()=>{Nn(c).then(null,(()=>{_n("Sending ANR event failed.")}))}),5e3);n.post("Runtime.evaluate",{expression:"global.__SENTRY_GET_SCOPES__();",silent:!0,returnByValue:!0},((t,e)=>{t&&_n(`Error executing script: '${t.message}'`),clearTimeout(u);const r=e&&e.result?e.result.value:void 0;n.post("Debugger.resume"),n.post("Debugger.disable"),Nn(c,r).then(null,(()=>{_n("Sending ANR event failed.")}))}))}catch(t){throw n.post("Debugger.resume"),n.post("Debugger.disable"),t}})),kn=()=>{try{n.post("Debugger.enable",(()=>{n.post("Debugger.pause")}))}catch(t){}}}const{poll:Cn}=function(t,n,e,r){const o=t();let s=!1,i=!0;return setInterval((()=>{const t=o.getTimeMs();!1===s&&t>n+e&&(s=!0,i&&r()),t<n+e&&(s=!1)}),20),{poll:()=>{o.reset()},enabled:t=>{i=t}}}((function(){let t=process.hrtime();return{getTimeMs:()=>{const[n,e]=process.hrtime(t);return Math.floor(1e3*n+e/1e6)},reset:()=>{t=process.hrtime()}}}),yn.pollInterval,yn.anrThreshold,(function(){_n("Watchdog timeout"),kn?(_n("Pausing debugger to capture stack trace"),kn()):(_n("Capturing event without a stack trace"),Nn().then(null,(()=>{_n("Sending ANR event failed on watchdog timeout.")})))}));n?.on("message",(t=>{t.session&&(gn=gt(t.session)),Cn()}));
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { VERSION } from '@opentelemetry/core';
|
|
2
|
+
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
|
|
3
|
+
import { getIsolationScope, getClient, withIsolationScope, addBreadcrumb } from '@sentry/core';
|
|
4
|
+
import { stripUrlQueryAndFragment, getBreadcrumbLogLevelFromHttpStatusCode, parseUrl, getSanitizedUrlString } from '@sentry/utils';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* This custom HTTP instrumentation is used to isolate incoming requests and annotate them with additional information.
|
|
8
|
+
* It does not emit any spans.
|
|
9
|
+
*
|
|
10
|
+
* The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,
|
|
11
|
+
* which would lead to Sentry not working as expected.
|
|
12
|
+
*
|
|
13
|
+
* Important note: Contrary to other OTEL instrumentation, this one cannot be unwrapped.
|
|
14
|
+
* It only does minimal things though and does not emit any spans.
|
|
15
|
+
*
|
|
16
|
+
* This is heavily inspired & adapted from:
|
|
17
|
+
* https://github.com/open-telemetry/opentelemetry-js/blob/f8ab5592ddea5cba0a3b33bf8d74f27872c0367f/experimental/packages/opentelemetry-instrumentation-http/src/http.ts
|
|
18
|
+
*/
|
|
19
|
+
class SentryHttpInstrumentation extends InstrumentationBase {
|
|
20
|
+
constructor(config = {}) {
|
|
21
|
+
super('@sentry/instrumentation-http', VERSION, config);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @inheritdoc */
|
|
25
|
+
init() {
|
|
26
|
+
return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Get the instrumentation for the http module. */
|
|
30
|
+
_getHttpInstrumentation() {
|
|
31
|
+
return new InstrumentationNodeModuleDefinition(
|
|
32
|
+
'http',
|
|
33
|
+
['*'],
|
|
34
|
+
(moduleExports) => {
|
|
35
|
+
// Patch incoming requests for request isolation
|
|
36
|
+
stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());
|
|
37
|
+
|
|
38
|
+
// Patch outgoing requests for breadcrumbs
|
|
39
|
+
const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());
|
|
40
|
+
stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));
|
|
41
|
+
|
|
42
|
+
return moduleExports;
|
|
43
|
+
},
|
|
44
|
+
() => {
|
|
45
|
+
// no unwrap here
|
|
46
|
+
},
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Get the instrumentation for the https module. */
|
|
51
|
+
_getHttpsInstrumentation() {
|
|
52
|
+
return new InstrumentationNodeModuleDefinition(
|
|
53
|
+
'https',
|
|
54
|
+
['*'],
|
|
55
|
+
(moduleExports) => {
|
|
56
|
+
// Patch incoming requests for request isolation
|
|
57
|
+
stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());
|
|
58
|
+
|
|
59
|
+
// Patch outgoing requests for breadcrumbs
|
|
60
|
+
const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());
|
|
61
|
+
stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));
|
|
62
|
+
|
|
63
|
+
return moduleExports;
|
|
64
|
+
},
|
|
65
|
+
() => {
|
|
66
|
+
// no unwrap here
|
|
67
|
+
},
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Patch the incoming request function for request isolation.
|
|
73
|
+
*/
|
|
74
|
+
_getPatchIncomingRequestFunction()
|
|
75
|
+
|
|
76
|
+
{
|
|
77
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
78
|
+
const instrumentation = this;
|
|
79
|
+
|
|
80
|
+
return (
|
|
81
|
+
original,
|
|
82
|
+
) => {
|
|
83
|
+
return function incomingRequest( event, ...args) {
|
|
84
|
+
// Only traces request events
|
|
85
|
+
if (event !== 'request') {
|
|
86
|
+
return original.apply(this, [event, ...args]);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
instrumentation._diag.debug('http instrumentation for incoming request');
|
|
90
|
+
|
|
91
|
+
const request = args[0] ;
|
|
92
|
+
|
|
93
|
+
const isolationScope = getIsolationScope().clone();
|
|
94
|
+
|
|
95
|
+
// Update the isolation scope, isolate this request
|
|
96
|
+
isolationScope.setSDKProcessingMetadata({ request });
|
|
97
|
+
|
|
98
|
+
const client = getClient();
|
|
99
|
+
if (client && client.getOptions().autoSessionTracking) {
|
|
100
|
+
isolationScope.setRequestSession({ status: 'ok' });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// attempt to update the scope's `transactionName` based on the request URL
|
|
104
|
+
// Ideally, framework instrumentations coming after the HttpInstrumentation
|
|
105
|
+
// update the transactionName once we get a parameterized route.
|
|
106
|
+
const httpMethod = (request.method || 'GET').toUpperCase();
|
|
107
|
+
const httpTarget = stripUrlQueryAndFragment(request.url || '/');
|
|
108
|
+
|
|
109
|
+
const bestEffortTransactionName = `${httpMethod} ${httpTarget}`;
|
|
110
|
+
|
|
111
|
+
isolationScope.setTransactionName(bestEffortTransactionName);
|
|
112
|
+
|
|
113
|
+
return withIsolationScope(isolationScope, () => {
|
|
114
|
+
return original.apply(this, [event, ...args]);
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Patch the outgoing request function for breadcrumbs.
|
|
122
|
+
*/
|
|
123
|
+
_getPatchOutgoingRequestFunction()
|
|
124
|
+
|
|
125
|
+
{
|
|
126
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
127
|
+
const instrumentation = this;
|
|
128
|
+
|
|
129
|
+
return (original) => {
|
|
130
|
+
return function outgoingRequest( ...args) {
|
|
131
|
+
instrumentation._diag.debug('http instrumentation for outgoing requests');
|
|
132
|
+
|
|
133
|
+
const request = original.apply(this, args) ;
|
|
134
|
+
|
|
135
|
+
request.prependListener('response', (response) => {
|
|
136
|
+
const breadcrumbs = instrumentation.getConfig().breadcrumbs;
|
|
137
|
+
const _breadcrumbs = typeof breadcrumbs === 'undefined' ? true : breadcrumbs;
|
|
138
|
+
if (_breadcrumbs) {
|
|
139
|
+
addRequestBreadcrumb(request, response);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
return request;
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Path the outgoing get function for breadcrumbs. */
|
|
149
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
150
|
+
_getPatchOutgoingGetFunction(clientRequest) {
|
|
151
|
+
return (_original) => {
|
|
152
|
+
// Re-implement http.get. This needs to be done (instead of using
|
|
153
|
+
// getPatchOutgoingRequestFunction to patch it) because we need to
|
|
154
|
+
// set the trace context header before the returned http.ClientRequest is
|
|
155
|
+
// ended. The Node.js docs state that the only differences between
|
|
156
|
+
// request and get are that (1) get defaults to the HTTP GET method and
|
|
157
|
+
// (2) the returned request object is ended immediately. The former is
|
|
158
|
+
// already true (at least in supported Node versions up to v10), so we
|
|
159
|
+
// simply follow the latter. Ref:
|
|
160
|
+
// https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback
|
|
161
|
+
// https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198
|
|
162
|
+
return function outgoingGetRequest(...args) {
|
|
163
|
+
const req = clientRequest(...args);
|
|
164
|
+
req.end();
|
|
165
|
+
return req;
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* This is a minimal version of `wrap` from shimmer:
|
|
173
|
+
* https://github.com/othiym23/shimmer/blob/master/index.js
|
|
174
|
+
*
|
|
175
|
+
* In contrast to the original implementation, this version does not allow to unwrap,
|
|
176
|
+
* and does not make it clear that the method is wrapped.
|
|
177
|
+
* This is necessary because we want to wrap the http module with our own code,
|
|
178
|
+
* while still allowing to use the HttpInstrumentation from OTEL.
|
|
179
|
+
*
|
|
180
|
+
* Without this, if we'd just use `wrap` from shimmer, the OTEL instrumentation would remove our wrapping,
|
|
181
|
+
* because it only allows any module to be wrapped a single time.
|
|
182
|
+
*/
|
|
183
|
+
function stealthWrap(
|
|
184
|
+
nodule,
|
|
185
|
+
name,
|
|
186
|
+
wrapper,
|
|
187
|
+
) {
|
|
188
|
+
const original = nodule[name];
|
|
189
|
+
const wrapped = wrapper(original);
|
|
190
|
+
|
|
191
|
+
defineProperty(nodule, name, wrapped);
|
|
192
|
+
return wrapped;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Sets a property on an object, preserving its enumerability.
|
|
196
|
+
function defineProperty(
|
|
197
|
+
obj,
|
|
198
|
+
name,
|
|
199
|
+
value,
|
|
200
|
+
) {
|
|
201
|
+
const enumerable = !!obj[name] && Object.prototype.propertyIsEnumerable.call(obj, name);
|
|
202
|
+
|
|
203
|
+
Object.defineProperty(obj, name, {
|
|
204
|
+
configurable: true,
|
|
205
|
+
enumerable: enumerable,
|
|
206
|
+
writable: true,
|
|
207
|
+
value: value,
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Add a breadcrumb for outgoing requests. */
|
|
212
|
+
function addRequestBreadcrumb(request, response) {
|
|
213
|
+
const data = getBreadcrumbData(request);
|
|
214
|
+
|
|
215
|
+
const statusCode = response.statusCode;
|
|
216
|
+
const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);
|
|
217
|
+
|
|
218
|
+
addBreadcrumb(
|
|
219
|
+
{
|
|
220
|
+
category: 'http',
|
|
221
|
+
data: {
|
|
222
|
+
status_code: statusCode,
|
|
223
|
+
...data,
|
|
224
|
+
},
|
|
225
|
+
type: 'http',
|
|
226
|
+
level,
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
event: 'response',
|
|
230
|
+
request,
|
|
231
|
+
response,
|
|
232
|
+
},
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function getBreadcrumbData(request) {
|
|
237
|
+
try {
|
|
238
|
+
// `request.host` does not contain the port, but the host header does
|
|
239
|
+
const host = request.getHeader('host') || request.host;
|
|
240
|
+
const url = new URL(request.path, `${request.protocol}//${host}`);
|
|
241
|
+
const parsedUrl = parseUrl(url.toString());
|
|
242
|
+
|
|
243
|
+
const data = {
|
|
244
|
+
url: getSanitizedUrlString(parsedUrl),
|
|
245
|
+
'http.method': request.method || 'GET',
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
if (parsedUrl.search) {
|
|
249
|
+
data['http.query'] = parsedUrl.search;
|
|
250
|
+
}
|
|
251
|
+
if (parsedUrl.hash) {
|
|
252
|
+
data['http.fragment'] = parsedUrl.hash;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return data;
|
|
256
|
+
} catch (e) {
|
|
257
|
+
return {};
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export { SentryHttpInstrumentation };
|
|
262
|
+
//# sourceMappingURL=SentryHttpInstrumentation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SentryHttpInstrumentation.js","sources":["../../../../src/integrations/http/SentryHttpInstrumentation.ts"],"sourcesContent":["import type * as http from 'node:http';\nimport type * as https from 'node:https';\nimport { VERSION } from '@opentelemetry/core';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';\nimport { addBreadcrumb, getClient, getIsolationScope, withIsolationScope } from '@sentry/core';\nimport type { SanitizedRequestData } from '@sentry/types';\nimport {\n getBreadcrumbLogLevelFromHttpStatusCode,\n getSanitizedUrlString,\n parseUrl,\n stripUrlQueryAndFragment,\n} from '@sentry/utils';\nimport type { NodeClient } from '../../sdk/client';\n\ntype Http = typeof http;\ntype Https = typeof https;\n\ntype SentryHttpInstrumentationOptions = InstrumentationConfig & {\n breadcrumbs?: boolean;\n};\n\n/**\n * This custom HTTP instrumentation is used to isolate incoming requests and annotate them with additional information.\n * It does not emit any spans.\n *\n * The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,\n * which would lead to Sentry not working as expected.\n *\n * Important note: Contrary to other OTEL instrumentation, this one cannot be unwrapped.\n * It only does minimal things though and does not emit any spans.\n *\n * This is heavily inspired & adapted from:\n * https://github.com/open-telemetry/opentelemetry-js/blob/f8ab5592ddea5cba0a3b33bf8d74f27872c0367f/experimental/packages/opentelemetry-instrumentation-http/src/http.ts\n */\nexport class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpInstrumentationOptions> {\n public constructor(config: SentryHttpInstrumentationOptions = {}) {\n super('@sentry/instrumentation-http', VERSION, config);\n }\n\n /** @inheritdoc */\n public init(): [InstrumentationNodeModuleDefinition, InstrumentationNodeModuleDefinition] {\n return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];\n }\n\n /** Get the instrumentation for the http module. */\n private _getHttpInstrumentation(): InstrumentationNodeModuleDefinition {\n return new InstrumentationNodeModuleDefinition(\n 'http',\n ['*'],\n (moduleExports: Http): Http => {\n // Patch incoming requests for request isolation\n stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());\n\n // Patch outgoing requests for breadcrumbs\n const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());\n stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));\n\n return moduleExports;\n },\n () => {\n // no unwrap here\n },\n );\n }\n\n /** Get the instrumentation for the https module. */\n private _getHttpsInstrumentation(): InstrumentationNodeModuleDefinition {\n return new InstrumentationNodeModuleDefinition(\n 'https',\n ['*'],\n (moduleExports: Https): Https => {\n // Patch incoming requests for request isolation\n stealthWrap(moduleExports.Server.prototype, 'emit', this._getPatchIncomingRequestFunction());\n\n // Patch outgoing requests for breadcrumbs\n const patchedRequest = stealthWrap(moduleExports, 'request', this._getPatchOutgoingRequestFunction());\n stealthWrap(moduleExports, 'get', this._getPatchOutgoingGetFunction(patchedRequest));\n\n return moduleExports;\n },\n () => {\n // no unwrap here\n },\n );\n }\n\n /**\n * Patch the incoming request function for request isolation.\n */\n private _getPatchIncomingRequestFunction(): (\n original: (event: string, ...args: unknown[]) => boolean,\n ) => (this: unknown, event: string, ...args: unknown[]) => boolean {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const instrumentation = this;\n\n return (\n original: (event: string, ...args: unknown[]) => boolean,\n ): ((this: unknown, event: string, ...args: unknown[]) => boolean) => {\n return function incomingRequest(this: unknown, event: string, ...args: unknown[]): boolean {\n // Only traces request events\n if (event !== 'request') {\n return original.apply(this, [event, ...args]);\n }\n\n instrumentation._diag.debug('http instrumentation for incoming request');\n\n const request = args[0] as http.IncomingMessage;\n\n const isolationScope = getIsolationScope().clone();\n\n // Update the isolation scope, isolate this request\n isolationScope.setSDKProcessingMetadata({ request });\n\n const client = getClient<NodeClient>();\n if (client && client.getOptions().autoSessionTracking) {\n isolationScope.setRequestSession({ status: 'ok' });\n }\n\n // attempt to update the scope's `transactionName` based on the request URL\n // Ideally, framework instrumentations coming after the HttpInstrumentation\n // update the transactionName once we get a parameterized route.\n const httpMethod = (request.method || 'GET').toUpperCase();\n const httpTarget = stripUrlQueryAndFragment(request.url || '/');\n\n const bestEffortTransactionName = `${httpMethod} ${httpTarget}`;\n\n isolationScope.setTransactionName(bestEffortTransactionName);\n\n return withIsolationScope(isolationScope, () => {\n return original.apply(this, [event, ...args]);\n });\n };\n };\n }\n\n /**\n * Patch the outgoing request function for breadcrumbs.\n */\n private _getPatchOutgoingRequestFunction(): (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n original: (...args: any[]) => http.ClientRequest,\n ) => (...args: unknown[]) => http.ClientRequest {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const instrumentation = this;\n\n return (original: (...args: unknown[]) => http.ClientRequest): ((...args: unknown[]) => http.ClientRequest) => {\n return function outgoingRequest(this: unknown, ...args: unknown[]): http.ClientRequest {\n instrumentation._diag.debug('http instrumentation for outgoing requests');\n\n const request = original.apply(this, args) as ReturnType<typeof http.request>;\n\n request.prependListener('response', (response: http.IncomingMessage) => {\n const breadcrumbs = instrumentation.getConfig().breadcrumbs;\n const _breadcrumbs = typeof breadcrumbs === 'undefined' ? true : breadcrumbs;\n if (_breadcrumbs) {\n addRequestBreadcrumb(request, response);\n }\n });\n\n return request;\n };\n };\n }\n\n /** Path the outgoing get function for breadcrumbs. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _getPatchOutgoingGetFunction(clientRequest: (...args: any[]) => http.ClientRequest) {\n return (_original: unknown): ((...args: unknown[]) => http.ClientRequest) => {\n // Re-implement http.get. This needs to be done (instead of using\n // getPatchOutgoingRequestFunction to patch it) because we need to\n // set the trace context header before the returned http.ClientRequest is\n // ended. The Node.js docs state that the only differences between\n // request and get are that (1) get defaults to the HTTP GET method and\n // (2) the returned request object is ended immediately. The former is\n // already true (at least in supported Node versions up to v10), so we\n // simply follow the latter. Ref:\n // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback\n // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198\n return function outgoingGetRequest(...args: unknown[]): http.ClientRequest {\n const req = clientRequest(...args);\n req.end();\n return req;\n };\n };\n }\n}\n\n/**\n * This is a minimal version of `wrap` from shimmer:\n * https://github.com/othiym23/shimmer/blob/master/index.js\n *\n * In contrast to the original implementation, this version does not allow to unwrap,\n * and does not make it clear that the method is wrapped.\n * This is necessary because we want to wrap the http module with our own code,\n * while still allowing to use the HttpInstrumentation from OTEL.\n *\n * Without this, if we'd just use `wrap` from shimmer, the OTEL instrumentation would remove our wrapping,\n * because it only allows any module to be wrapped a single time.\n */\nfunction stealthWrap<Nodule extends object, FieldName extends keyof Nodule>(\n nodule: Nodule,\n name: FieldName,\n wrapper: (original: Nodule[FieldName]) => Nodule[FieldName],\n): Nodule[FieldName] {\n const original = nodule[name];\n const wrapped = wrapper(original);\n\n defineProperty(nodule, name, wrapped);\n return wrapped;\n}\n\n// Sets a property on an object, preserving its enumerability.\nfunction defineProperty<Nodule extends object, FieldName extends keyof Nodule>(\n obj: Nodule,\n name: FieldName,\n value: Nodule[FieldName],\n): void {\n const enumerable = !!obj[name] && Object.prototype.propertyIsEnumerable.call(obj, name);\n\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable: enumerable,\n writable: true,\n value: value,\n });\n}\n\n/** Add a breadcrumb for outgoing requests. */\nfunction addRequestBreadcrumb(request: http.ClientRequest, response: http.IncomingMessage): void {\n const data = getBreadcrumbData(request);\n\n const statusCode = response.statusCode;\n const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);\n\n addBreadcrumb(\n {\n category: 'http',\n data: {\n status_code: statusCode,\n ...data,\n },\n type: 'http',\n level,\n },\n {\n event: 'response',\n request,\n response,\n },\n );\n}\n\nfunction getBreadcrumbData(request: http.ClientRequest): Partial<SanitizedRequestData> {\n try {\n // `request.host` does not contain the port, but the host header does\n const host = request.getHeader('host') || request.host;\n const url = new URL(request.path, `${request.protocol}//${host}`);\n const parsedUrl = parseUrl(url.toString());\n\n const data: Partial<SanitizedRequestData> = {\n url: getSanitizedUrlString(parsedUrl),\n 'http.method': request.method || 'GET',\n };\n\n if (parsedUrl.search) {\n data['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n data['http.fragment'] = parsedUrl.hash;\n }\n\n return data;\n } catch {\n return {};\n }\n}\n"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { _optionalChain } from '@sentry/utils';
|
|
2
|
+
import { diag } from '@opentelemetry/api';
|
|
3
|
+
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
|
|
4
|
+
import { defineIntegration } from '@sentry/core';
|
|
5
|
+
import { getClient } from '@sentry/opentelemetry';
|
|
6
|
+
import { generateInstrumentOnce } from '../../otel/instrument.js';
|
|
7
|
+
import { addOriginToSpan } from '../../utils/addOriginToSpan.js';
|
|
8
|
+
import { getRequestUrl } from '../../utils/getRequestUrl.js';
|
|
9
|
+
import { SentryHttpInstrumentation } from './SentryHttpInstrumentation.js';
|
|
10
|
+
|
|
11
|
+
const INTEGRATION_NAME = 'Http';
|
|
12
|
+
|
|
13
|
+
const INSTRUMENTATION_NAME = '@opentelemetry_sentry-patched/instrumentation-http';
|
|
14
|
+
|
|
15
|
+
const instrumentSentryHttp = generateInstrumentOnce(
|
|
16
|
+
`${INTEGRATION_NAME}.sentry`,
|
|
17
|
+
options => {
|
|
18
|
+
return new SentryHttpInstrumentation({ breadcrumbs: _optionalChain([options, 'optionalAccess', _ => _.breadcrumbs]) });
|
|
19
|
+
},
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
const instrumentOtelHttp = generateInstrumentOnce(INTEGRATION_NAME, config => {
|
|
23
|
+
const instrumentation = new HttpInstrumentation(config);
|
|
24
|
+
|
|
25
|
+
// We want to update the logger namespace so we can better identify what is happening here
|
|
26
|
+
try {
|
|
27
|
+
instrumentation['_diag'] = diag.createComponentLogger({
|
|
28
|
+
namespace: INSTRUMENTATION_NAME,
|
|
29
|
+
});
|
|
30
|
+
// @ts-expect-error We are writing a read-only property here...
|
|
31
|
+
instrumentation.instrumentationName = INSTRUMENTATION_NAME;
|
|
32
|
+
} catch (e) {
|
|
33
|
+
// ignore errors here...
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return instrumentation;
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Instrument the HTTP and HTTPS modules.
|
|
41
|
+
*/
|
|
42
|
+
const instrumentHttp = (options = {}) => {
|
|
43
|
+
// This is the "regular" OTEL instrumentation that emits spans
|
|
44
|
+
if (options.spans !== false) {
|
|
45
|
+
const instrumentationConfig = getConfigWithDefaults(options);
|
|
46
|
+
instrumentOtelHttp(instrumentationConfig);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// This is the Sentry-specific instrumentation that isolates requests & creates breadcrumbs
|
|
50
|
+
// Note that this _has_ to be wrapped after the OTEL instrumentation,
|
|
51
|
+
// otherwise the isolation will not work correctly
|
|
52
|
+
instrumentSentryHttp(options);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const _httpIntegration = ((options = {}) => {
|
|
56
|
+
return {
|
|
57
|
+
name: INTEGRATION_NAME,
|
|
58
|
+
setupOnce() {
|
|
59
|
+
instrumentHttp(options);
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}) ;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The http integration instruments Node's internal http and https modules.
|
|
66
|
+
* It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.
|
|
67
|
+
*/
|
|
68
|
+
const httpIntegration = defineIntegration(_httpIntegration);
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Determines if @param req is a ClientRequest, meaning the request was created within the express app
|
|
72
|
+
* and it's an outgoing request.
|
|
73
|
+
* Checking for properties instead of using `instanceOf` to avoid importing the request classes.
|
|
74
|
+
*/
|
|
75
|
+
function _isClientRequest(req) {
|
|
76
|
+
return 'outputData' in req && 'outputSize' in req && !('client' in req) && !('statusCode' in req);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Detects if an incoming request is a prefetch request.
|
|
81
|
+
*/
|
|
82
|
+
function isKnownPrefetchRequest(req) {
|
|
83
|
+
// Currently only handles Next.js prefetch requests but may check other frameworks in the future.
|
|
84
|
+
return req.headers['next-router-prefetch'] === '1';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function getConfigWithDefaults(options = {}) {
|
|
88
|
+
const instrumentationConfig = {
|
|
89
|
+
..._optionalChain([options, 'access', _2 => _2.instrumentation, 'optionalAccess', _3 => _3._experimentalConfig]),
|
|
90
|
+
|
|
91
|
+
disableIncomingRequestInstrumentation: options.disableIncomingRequestSpans,
|
|
92
|
+
|
|
93
|
+
ignoreOutgoingRequestHook: request => {
|
|
94
|
+
const url = getRequestUrl(request);
|
|
95
|
+
|
|
96
|
+
if (!url) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const _ignoreOutgoingRequests = options.ignoreOutgoingRequests;
|
|
101
|
+
if (_ignoreOutgoingRequests && _ignoreOutgoingRequests(url, request)) {
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return false;
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
ignoreIncomingRequestHook: request => {
|
|
109
|
+
// request.url is the only property that holds any information about the url
|
|
110
|
+
// it only consists of the URL path and query string (if any)
|
|
111
|
+
const urlPath = request.url;
|
|
112
|
+
|
|
113
|
+
const method = _optionalChain([request, 'access', _4 => _4.method, 'optionalAccess', _5 => _5.toUpperCase, 'call', _6 => _6()]);
|
|
114
|
+
// We do not capture OPTIONS/HEAD requests as transactions
|
|
115
|
+
if (method === 'OPTIONS' || method === 'HEAD') {
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const _ignoreIncomingRequests = options.ignoreIncomingRequests;
|
|
120
|
+
if (urlPath && _ignoreIncomingRequests && _ignoreIncomingRequests(urlPath, request)) {
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return false;
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
requireParentforOutgoingSpans: false,
|
|
128
|
+
requireParentforIncomingSpans: false,
|
|
129
|
+
requestHook: (span, req) => {
|
|
130
|
+
addOriginToSpan(span, 'auto.http.otel.http');
|
|
131
|
+
if (!_isClientRequest(req) && isKnownPrefetchRequest(req)) {
|
|
132
|
+
span.setAttribute('sentry.http.prefetch', true);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
_optionalChain([options, 'access', _7 => _7.instrumentation, 'optionalAccess', _8 => _8.requestHook, 'optionalCall', _9 => _9(span, req)]);
|
|
136
|
+
},
|
|
137
|
+
responseHook: (span, res) => {
|
|
138
|
+
const client = getClient();
|
|
139
|
+
if (client && client.getOptions().autoSessionTracking) {
|
|
140
|
+
setImmediate(() => {
|
|
141
|
+
client['_captureRequestSession']();
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
_optionalChain([options, 'access', _10 => _10.instrumentation, 'optionalAccess', _11 => _11.responseHook, 'optionalCall', _12 => _12(span, res)]);
|
|
146
|
+
},
|
|
147
|
+
applyCustomAttributesOnSpan: (
|
|
148
|
+
span,
|
|
149
|
+
request,
|
|
150
|
+
response,
|
|
151
|
+
) => {
|
|
152
|
+
_optionalChain([options, 'access', _13 => _13.instrumentation, 'optionalAccess', _14 => _14.applyCustomAttributesOnSpan, 'optionalCall', _15 => _15(span, request, response)]);
|
|
153
|
+
},
|
|
154
|
+
} ;
|
|
155
|
+
|
|
156
|
+
return instrumentationConfig;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export { httpIntegration, instrumentOtelHttp, instrumentSentryHttp };
|
|
160
|
+
//# sourceMappingURL=index.js.map
|