hud-sdk 1.7.8 → 1.7.9

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/api.d.ts CHANGED
@@ -4,5 +4,6 @@ export type UserContext = {
4
4
  [key: string]: string | number | boolean | string[] | number[];
5
5
  };
6
6
  export declare function setContext(context: UserContext): void;
7
+ export declare function setFailure(error: string, context?: UserContext): void;
7
8
 
8
9
  export {};
package/dist/cjs/api.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},5809:e=>{e.exports=require("./config")},7131:e=>{e.exports=require("./wrap")}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,r),i.exports}var o={};return(()=>{var e=o;Object.defineProperty(e,"__esModule",{value:!0}),e.setContext=function(e){try{const r=(0,a.getInvestigationStorage)();if(void 0===r)return void(c||(i.app_logger.warning("HudContext warning: No Storage"),i.customer_logger.logEntry(n.UserErrorLogs.SetContextBeforeRegister()),c=!0));if(!t.hudConfig.dynamicConfig.enableInvestigation)return;const o=r.getStore();if(void 0===o)return void(s||(i.app_logger.warning("HudContext warning: setContext called not inside async context. Skipping."),i.customer_logger.logEntry(n.UserErrorLogs.SetContextNoAsyncContext()),s=!0));const g=(0,n.validateContext)(e);o.userContext={...o.userContext,...g}}catch(e){if(e instanceof n.HudContextValidationError)return void(p||(i.app_logger.warning("HudContext warning: failed to validate context. Skipping.",{error:e,stack:e instanceof Error&&null!==e?e.stack:void 0}),p=!0));g||(i.app_logger.warning("HudContext warning: failed to set context. Skipping.",{error:e,stack:e instanceof Error&&null!==e?e.stack:void 0}),g=!0)}};const t=r(5809),n=r(2546),i=r(523),a=r(7131);let s=!1,g=!1,c=!1,p=!1})(),o})());
1
+ !function(r,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t=e();for(var o in t)("object"==typeof exports?exports:r)[o]=t[o]}}(global,()=>(()=>{"use strict";var r={523:r=>{r.exports=require("./logger")},2546:r=>{r.exports=require("./lib")},5809:r=>{r.exports=require("./config")},7131:r=>{r.exports=require("./wrap")}},e={};function t(o){var n=e[o];if(void 0!==n)return n.exports;var i=e[o]={exports:{}};return r[o](i,i.exports,t),i.exports}var o={};return(()=>{var r=o;Object.defineProperty(r,"__esModule",{value:!0}),r.setContext=f,r.setFailure=function(r,t){try{const o=(0,g.getInvestigationStorage)();if(void 0===o)return void(c||(i.app_logger.warning("setFailure - No Storage"),i.customer_logger.logEntry(n.UserErrorLogs.SetFailureBeforeRegister()),c=!0));if(!e.hudConfig.dynamicConfig.enableInvestigation)return;const s=o.getStore();if(void 0===s)return void(d||(i.app_logger.warning("setFailure called not inside async context. Skipping."),i.customer_logger.logEntry(n.UserErrorLogs.SetFailureNoAsyncContext()),d=!0));if("string"!=typeof r)return void i.customer_logger.logEntry(n.UserErrorLogs.SetFailureErrorNotString());if(0===r.length)return void i.customer_logger.logEntry(n.UserErrorLogs.SetFailureErrorEmpty());let a=r;r.length>p&&(i.customer_logger.logEntry(n.UserErrorLogs.SetFailureErrorTooLong()),a=r.substring(0,p)),s.userDefinedError=a,void 0!==t&&f(t)}catch(r){i.app_logger.warning("failed to set failure. Skipping.",{error:r,stack:r instanceof Error&&null!==r?r.stack:void 0})}};const e=t(5809),n=t(2546),i=t(523),g=t(7131);let s=!1,a=!1,l=!1,u=!1,c=!1,d=!1;const p=1024;function f(r){try{const t=(0,g.getInvestigationStorage)();if(void 0===t)return void(l||(i.app_logger.warning("HudContext warning: No Storage"),i.customer_logger.logEntry(n.UserErrorLogs.SetContextBeforeRegister()),l=!0));if(!e.hudConfig.dynamicConfig.enableInvestigation)return;const o=t.getStore();if(void 0===o)return void(s||(i.app_logger.warning("HudContext warning: setContext called not inside async context. Skipping."),i.customer_logger.logEntry(n.UserErrorLogs.SetContextNoAsyncContext()),s=!0));const a=(0,n.validateContext)(r);o.userContext={...o.userContext,...a}}catch(r){if(r instanceof n.HudContextValidationError)return void(u||(i.app_logger.warning("HudContext warning: failed to validate context. Skipping.",{error:r,stack:r instanceof Error&&null!==r?r.stack:void 0}),u=!0));a||(i.app_logger.warning("HudContext warning: failed to set context. Skipping.",{error:r,stack:r instanceof Error&&null!==r?r.stack:void 0}),a=!0)}}})(),o})());
2
2
  //# sourceMappingURL=api.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var r in s)("object"==typeof exports?exports:e)[r]=s[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2312:function(e,t,s){var r,n=this&&this.__createBinding||(Object.create?function(e,t,s,r){void 0===r&&(r=s);var n=Object.getOwnPropertyDescriptor(t,s);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,r,n)}:function(e,t,s,r){void 0===r&&(r=s),e[r]=t[s]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[t.length]=s);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudClient=void 0;const a=s(5809),l=s(2546),u=s(523),d=i(s(8938)),c=s(6982),g=s(6261),f=s(9561),p=s(9023),h=s(3106),_=(0,p.promisify)(h.gzip),m="node-sdk",w=(0,c.randomUUID)();class y{sessionId;httpClient;extensionEventEmitter;static config={baseURL:a.hudConfig.sink.url,timeout:a.hudConfig.sink.timeout,headers:{"Content-Type":"application/json"}};static defaultRequest={version:"1.0.0",source:m,event_version:"1.0.0"};constructor(e){this.httpClient=d.default.create(y.config),this.extensionEventEmitter=e}setSession(e){const{sessionId:t,extraHeaders:s}=e;this.sessionId=t,this.httpClient.defaults.headers.common[a.hudConfig.sink.session_attr]=t;try{for(const[e,t]of Object.entries(s))try{this.httpClient.defaults.headers.common[e]=t}catch(s){u.worker_logger.error("Failed to set extra header",{msg:s instanceof Error?s.message:void 0,stack:s instanceof Error?s.stack:void 0,key:e,value:t})}}catch(e){u.worker_logger.error("Failed to set extra headers",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}setExtensionEventEmitter(e){this.extensionEventEmitter=e}async logs(e){const t={logs:e,send_time:(new Date).toISOString()};await this._requestRelentless(a.hudConfig.endpoints.logs,t,"logs"),u.worker_logger.debug("sent logs successfully",{size:e.length})}async sessionslessLogs(e,t,s,r){const n={logs:e,send_time:(new Date).toISOString(),token:t,sdk_version:a.SDK_VERSION,sdk_type:m,sdk_runtime_type:r??"sdk",run_id:s??w};await this._requestRelentless(a.hudConfig.endpoints.sessionslessLogs,n,"sessionslessLogs"),u.worker_logger.debug("sent logs successfully",{size:e.length})}async send(e,t,s={}){const r={...y.defaultRequest,type:e,raw:t,send_time:(new Date).toISOString(),...s};await this._requestRelentless(a.hudConfig.endpoints.send,r,e),u.worker_logger.debug("sent event successfully",{type:e})}async batch(e,t,s={}){const r={...y.defaultRequest,type:e,arr:t,send_time:(new Date).toISOString(),...s};await this._requestRelentless(a.hudConfig.endpoints.batch,r,e),u.worker_logger.debug("sent batched events successfully",{type:e})}async getRemoteConfig(){const e=await this._requestDataRelentless(a.hudConfig.endpoints.getRemoteConfig,{},"getRemoteConfig");return u.worker_logger.info("Received remote configuration from server",{remoteConfiguration:e}),e}async getMode(e){const t={extra:e,send_time:(new Date).toISOString()},s=await this._requestDataRelentless(a.hudConfig.endpoints.getMode,t,"getMode");return u.worker_logger.info("Received mode from server "+s),s}async storeObject(e,t){const s={key:e,value:t.toString("base64")},r=await this._requestDataRelentless(a.hudConfig.endpoints.storeObject,s,"storeObject");if("reference"in r)return u.worker_logger.debug("Stored object successfully",{reference:r.reference}),r.reference;u.worker_logger.error("Failed to store object",{key:e,response:r})}async validateToken(e){const t={...y.defaultRequest,token:e,send_time:(new Date).toISOString()};try{return await this._requestRelentless(a.hudConfig.endpoints.validateToken,t,"validateToken"),!0}catch(e){if(e instanceof l.HudClientUnauthorizedError)return!1}return!1}async getUploadUrls(e,t,s){const r={...y.defaultRequest,send_time:(new Date).toISOString(),build_id:e,token:t,num_urls:s};return(await this._requestRelentless(a.hudConfig.endpoints.getUploadUrls,r,"getUploadUrls")).data.urls}async triggerReingest(e){const t={...y.defaultRequest,type:"triggerReingest",send_time:(new Date).toISOString(),build_id:e};await this._requestRelentless(a.hudConfig.endpoints.triggerReingest,t,"triggerReingest")}async completed(e,t){const s={...y.defaultRequest,build_id:e,token:t,send_time:(new Date).toISOString()};await this._requestRelentless(a.hudConfig.endpoints.completed,s,"completed")}async sendFileDeclarationsCi(e,t){u.worker_logger.debug("Sending file declarations request",{count:t.length});const s={...e,files:t},r=await this._requestRelentless(a.hudConfig.endpoints.fileDeclarationsCi,s,"fileDeclarations");return{files:r.data.files,send_all:r.data.send_all}}async sendFileDeclarations(e){u.worker_logger.debug("Sending file declarations request",{count:e.length});const t={files:e},s=await this._requestRelentless(a.hudConfig.endpoints.fileDeclarations,t,"fileDeclarations");return{files:s.data.files,send_all:s.data.send_all}}async getEndpointsDurationsInvestigationThresholds(){return await this._requestDataRelentless(a.hudConfig.endpoints.endpointsDurationsInvestigationThresholds,{},"endpointsDurationsInvestigationThresholds","get")}async _requestRelentless(e,t,s,r="post",n=3){const o={"X-Hud-Type":s,"X-Hud-Request-ID":(0,c.randomUUID)()},i=[];let a;for(let c=0;c<n;c++)try{const n=await this._request(e,t,s,o,r);return(0,l.incrementSentEventsCount)(s),n}catch(t){if(t instanceof Error&&(a=t),t instanceof d.AxiosError){if(401===t.response?.status)throw u.worker_logger.error("Unauthorized request",{endpoint:e,requestType:s}),new l.HudClientUnauthorizedError(`Unauthorized request for ${e}`);const{code:r,name:n,status:o,message:a}=t;i.push({code:r,name:n,status:o,message:a})}else if(t instanceof Error){const{name:e,message:s}=t;i.push({name:e,message:s})}await new Promise(e=>setTimeout(e,1))}throw u.worker_logger.error("Exceeded max retries to request",{endpoint:e,requestType:s,failures:i,retries:n}),new l.HudClientError(`Exceeded max retries for ${e}`,a instanceof d.AxiosError?a.code:void 0)}async _requestDataRelentless(e,t,s,r="post",n=3){return(await this._requestRelentless(e,t,s,r,n)).data}async _request(e,t,s,r,n="post"){try{this.extensionEventEmitter&&await(0,g.once)(this.extensionEventEmitter,"eventloop");const s="get"===n?void 0:await this._gzipCompress(JSON.stringify(t));return r={...r,"Content-Encoding":"gzip","Content-Type":"application/json"},await(0,l.suppressTraces)(async()=>await this.httpClient.request({url:e,method:n,data:s,headers:r}))()}catch(t){if(t instanceof d.AxiosError){const{code:r,name:n,status:o,cause:i,message:a}=t;u.worker_logger.error(`${e} request failed`,{requestType:s,code:r,name:n,status:o,cause:i,msg:a})}else u.worker_logger.error("Caught an unexpected error",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0});throw t}}async _gzipCompress(e){return _(e)}async initSession(e,t,s,r){const n={token:e,service:t,start_time:s.toISOString(),type:m,version:"1.0.0",sdk_version:a.SDK_VERSION,tags:r};u.worker_logger.debug("Requesting init",{data:n});const o=await this._requestRelentless(a.hudConfig.endpoints.init,n,"init");if(o.status===a.hudConfig.throttleStatusCode)throw u.worker_logger.debug("Init request throttled"),new l.HudSessionThrottle;const i=o.data.sessionId,d=o.data.extraHeaders??{};return u.worker_logger.info("Succesfuly created session with backend",{host:y.config.baseURL,service:t,sessionId:i,extraHeaders:d,tags:r}),{sessionId:i,extraHeaders:d}}async uploadDeclarationsToS3(e,t,s,r){const n=await(0,f.buffer)(e);let o=(await this.getUploadUrls(t,s,1))[0];r(`Got upload url ${o}`);for(let e=1;e<=3;e++)try{return await d.default.put(o,n,{headers:{"Content-Encoding":"gzip","Content-Type":"application/x-ndjson"}}),void r(`Uploaded requests to ${o}`)}catch(n){if(!(d.default.isAxiosError(n)&&405===n.response?.status&&e<3))throw n;r(`Upload failed with 405 status, retrying attempt ${e+1}/3, current upload url: ${o}`),o=(await this.getUploadUrls(t,s,1))[0]}}}t.HudClient=y},2546:e=>{e.exports=require("./lib")},3106:e=>{e.exports=require("zlib")},5809:e=>{e.exports=require("./config")},6261:e=>{e.exports=require("events")},6982:e=>{e.exports=require("crypto")},8938:e=>{e.exports=require("axios")},9023:e=>{e.exports=require("util")},9561:e=>{e.exports=require("stream/consumers")}},t={};return function s(r){var n=t[r];if(void 0!==n)return n.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,s),o.exports}(2312)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var n in s)("object"==typeof exports?exports:e)[n]=s[n]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2312:function(e,t,s){var n,r=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var r=Object.getOwnPropertyDescriptor(t,s);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,r)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[t.length]=s);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s=n(e),i=0;i<s.length;i++)"default"!==s[i]&&r(t,e,s[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudClient=void 0;const a=s(5809),u=s(2546),d=s(523),l=i(s(8938)),c=s(6982),g=s(6261),f=s(9561),h=s(9023),p=s(3106),_=(0,h.promisify)(p.gzip),w="node-sdk",m=(0,c.randomUUID)();class y{sessionId;httpClient;extensionEventEmitter;static config={baseURL:a.hudConfig.sink.url,timeout:a.hudConfig.sink.timeout,headers:{"Content-Type":"application/json"}};static defaultRequest={version:"1.0.0",source:w,event_version:"1.0.0"};constructor(e){this.httpClient=l.default.create(y.config),this.extensionEventEmitter=e}setSession(e){const{sessionId:t,extraHeaders:s}=e;this.sessionId=t,this.httpClient.defaults.headers.common[a.hudConfig.sink.session_attr]=t;try{for(const[e,t]of Object.entries(s))try{this.httpClient.defaults.headers.common[e]=t}catch(s){d.worker_logger.error("Failed to set extra header",{msg:s instanceof Error?s.message:void 0,stack:s instanceof Error?s.stack:void 0,key:e,value:t})}}catch(e){d.worker_logger.error("Failed to set extra headers",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}setExtensionEventEmitter(e){this.extensionEventEmitter=e}async logs(e){const t={logs:e,send_time:(new Date).toISOString()};await this._requestRelentless(a.hudConfig.endpoints.logs,t,"logs"),d.worker_logger.debug("sent logs successfully",{size:e.length})}async sessionslessLogs(e,t,s,n){const r={logs:e,send_time:(new Date).toISOString(),token:t,sdk_version:a.SDK_VERSION,sdk_type:w,sdk_runtime_type:n??"sdk",run_id:s??m};await this._requestRelentless(a.hudConfig.endpoints.sessionslessLogs,r,"sessionslessLogs"),d.worker_logger.debug("sent logs successfully",{size:e.length})}async send(e,t,s={}){const n={...y.defaultRequest,type:e,raw:t,send_time:(new Date).toISOString(),...s};await this._requestRelentless(a.hudConfig.endpoints.send,n,e),d.worker_logger.debug("sent event successfully",{type:e})}async batch(e,t,s={}){const n={...y.defaultRequest,type:e,arr:t,send_time:(new Date).toISOString(),...s};await this._requestRelentless(a.hudConfig.endpoints.batch,n,e),d.worker_logger.debug("sent batched events successfully",{type:e})}async getRemoteConfig(){const e=await this._requestDataRelentless(a.hudConfig.endpoints.getRemoteConfig,{},"getRemoteConfig");return d.worker_logger.info("Received remote configuration from server",{remoteConfiguration:e}),e}async getMode(e){const t={extra:e,send_time:(new Date).toISOString()},s=await this._requestDataRelentless(a.hudConfig.endpoints.getMode,t,"getMode");return d.worker_logger.info("Received mode from server "+s),s}async getKnownDetachedFunctions(){const e={...y.defaultRequest,send_time:(new Date).toISOString()},t=await this._requestDataRelentless(a.hudConfig.endpoints.getKnownDetachedFunctions,e,"getKnownDetachedFunctions");return t?.knownDetachedFunctions||[]}async setDetachedFunctions(e){if(0===e.length)return;const t={...y.defaultRequest,arr:e,send_time:(new Date).toISOString()};await this._requestRelentless(a.hudConfig.endpoints.setDetachedFunctions,t,"setDetachedFunctions"),d.worker_logger.debug("Sent detached functions successfully",{count:e.length})}async storeObject(e,t){const s={key:e,value:t.toString("base64")},n=await this._requestDataRelentless(a.hudConfig.endpoints.storeObject,s,"storeObject");if("reference"in n)return d.worker_logger.debug("Stored object successfully",{reference:n.reference}),n.reference;d.worker_logger.error("Failed to store object",{key:e,response:n})}async validateToken(e){const t={...y.defaultRequest,token:e,send_time:(new Date).toISOString()};try{return await this._requestRelentless(a.hudConfig.endpoints.validateToken,t,"validateToken"),!0}catch(e){if(e instanceof u.HudClientUnauthorizedError)return!1}return!1}async getUploadUrls(e,t,s){const n={...y.defaultRequest,send_time:(new Date).toISOString(),build_id:e,token:t,num_urls:s};return(await this._requestRelentless(a.hudConfig.endpoints.getUploadUrls,n,"getUploadUrls")).data.urls}async triggerReingest(e){const t={...y.defaultRequest,type:"triggerReingest",send_time:(new Date).toISOString(),build_id:e};await this._requestRelentless(a.hudConfig.endpoints.triggerReingest,t,"triggerReingest")}async completed(e,t){const s={...y.defaultRequest,build_id:e,token:t,send_time:(new Date).toISOString()};await this._requestRelentless(a.hudConfig.endpoints.completed,s,"completed")}async sendFileDeclarationsCi(e,t){d.worker_logger.debug("Sending file declarations request",{count:t.length});const s={...e,files:t},n=await this._requestRelentless(a.hudConfig.endpoints.fileDeclarationsCi,s,"fileDeclarations");return{files:n.data.files,send_all:n.data.send_all}}async sendFileDeclarations(e){d.worker_logger.debug("Sending file declarations request",{count:e.length});const t={files:e},s=await this._requestRelentless(a.hudConfig.endpoints.fileDeclarations,t,"fileDeclarations");return{files:s.data.files,send_all:s.data.send_all}}async getEndpointsDurationsInvestigationThresholds(){return await this._requestDataRelentless(a.hudConfig.endpoints.endpointsDurationsInvestigationThresholds,{},"endpointsDurationsInvestigationThresholds","get")}async _requestRelentless(e,t,s,n="post",r=3){const o={"X-Hud-Type":s,"X-Hud-Request-ID":(0,c.randomUUID)()},i=[];let a;for(let c=0;c<r;c++)try{const r=await this._request(e,t,s,o,n);return(0,u.incrementSentEventsCount)(s),r}catch(t){if(t instanceof Error&&(a=t),t instanceof l.AxiosError){if(401===t.response?.status)throw d.worker_logger.error("Unauthorized request",{endpoint:e,requestType:s}),new u.HudClientUnauthorizedError(`Unauthorized request for ${e}`);const{code:n,name:r,status:o,message:a}=t;i.push({code:n,name:r,status:o,message:a})}else if(t instanceof Error){const{name:e,message:s}=t;i.push({name:e,message:s})}await new Promise(e=>setTimeout(e,1))}throw d.worker_logger.error("Exceeded max retries to request",{endpoint:e,requestType:s,failures:i,retries:r}),new u.HudClientError(`Exceeded max retries for ${e}`,a instanceof l.AxiosError?a.code:void 0)}async _requestDataRelentless(e,t,s,n="post",r=3){return(await this._requestRelentless(e,t,s,n,r)).data}async _request(e,t,s,n,r="post"){try{this.extensionEventEmitter&&await(0,g.once)(this.extensionEventEmitter,"eventloop");const s="get"===r?void 0:await this._gzipCompress(JSON.stringify(t));return n={...n,"Content-Encoding":"gzip","Content-Type":"application/json"},await(0,u.suppressTraces)(async()=>await this.httpClient.request({url:e,method:r,data:s,headers:n}))()}catch(t){if(t instanceof l.AxiosError){const{code:n,name:r,status:o,cause:i,message:a}=t;d.worker_logger.error(`${e} request failed`,{requestType:s,code:n,name:r,status:o,cause:i,msg:a})}else d.worker_logger.error("Caught an unexpected error",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0});throw t}}async _gzipCompress(e){return _(e)}async initSession(e,t,s,n){const r={token:e,service:t,start_time:s.toISOString(),type:w,version:"1.0.0",sdk_version:a.SDK_VERSION,tags:n};d.worker_logger.debug("Requesting init",{data:r});const o=await this._requestRelentless(a.hudConfig.endpoints.init,r,"init");if(o.status===a.hudConfig.throttleStatusCode)throw d.worker_logger.debug("Init request throttled"),new u.HudSessionThrottle;const i=o.data.sessionId,l=o.data.extraHeaders??{};return d.worker_logger.info("Succesfuly created session with backend",{host:y.config.baseURL,service:t,sessionId:i,extraHeaders:l,tags:n}),{sessionId:i,extraHeaders:l}}async uploadDeclarationsToS3(e,t,s,n){const r=await(0,f.buffer)(e);let o=(await this.getUploadUrls(t,s,1))[0];n(`Got upload url ${o}`);for(let e=1;e<=3;e++)try{return await l.default.put(o,r,{headers:{"Content-Encoding":"gzip","Content-Type":"application/x-ndjson"}}),void n(`Uploaded requests to ${o}`)}catch(r){if(!(l.default.isAxiosError(r)&&405===r.response?.status&&e<3))throw r;n(`Upload failed with 405 status, retrying attempt ${e+1}/3, current upload url: ${o}`),o=(await this.getUploadUrls(t,s,1))[0]}}}t.HudClient=y},2546:e=>{e.exports=require("./lib")},3106:e=>{e.exports=require("zlib")},5809:e=>{e.exports=require("./config")},6261:e=>{e.exports=require("events")},6982:e=>{e.exports=require("crypto")},8938:e=>{e.exports=require("axios")},9023:e=>{e.exports=require("util")},9561:e=>{e.exports=require("stream/consumers")}},t={};return function s(n){var r=t[n];if(void 0!==r)return r.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,s),o.exports}(2312)})());
2
2
  //# sourceMappingURL=client.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={1569:e=>{e.exports=require("zod")},2210:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_MODULE_NAME=void 0,t.SDK_MODULE_NAME="hud-sdk"},2509:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,a)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),a=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=t.SDK_MODULE_NAME=void 0,a(n(2887),t),a(n(2570),t);var o=n(2210);Object.defineProperty(t,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return o.SDK_MODULE_NAME}}),a(n(7089),t);var r=n(5453);Object.defineProperty(t,"SDK_VERSION",{enumerable:!0,get:function(){return r.SDK_VERSION}})},2570:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateDynamicConfig=function(e,t,n){const o=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!o.success)return n.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:o,remoteConfig:e}),t.dynamicConfig;const r=a(t.dynamicConfig,o.data);return void 0!==r.enableInvestigation&&r.enableInvestigation!==t.dynamicConfig.enableInvestigation&&(n.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:r.enableInvestigation}),t.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=r.enableInvestigation)),void 0!==r.enableInvestigationArgsSending&&r.enableInvestigationArgsSending!==t.dynamicConfig.enableInvestigationArgsSending&&(n.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:r.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=r.enableInvestigationArgsSending),void 0!==r?.investigationRateLimits?.executionFlowMaxLength&&r?.investigationRateLimits?.executionFlowMaxLength!==t.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=r.investigationRateLimits.executionFlowMaxLength),void 0!==r?.investigationRateLimits?.exceptionMaxLength&&r?.investigationRateLimits?.exceptionMaxLength!==t.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=r.investigationRateLimits.exceptionMaxLength),r};const i=n(2887);function a(e,t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(e)&&Array.isArray(t))return t;const n={...e};for(const i in t){const o=e[i],r=t[i];n[i]=a(o,r)}return n}},2887:function(e,t,n){var i,a=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,a)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),r=0;r<n.length;r++)"default"!==n[r]&&a(t,e,n[r]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudFailedReadConfigError=t.loggerConfig=t.hudConfig=t.HudDynamicConfigSchema=void 0,t.functionUuidToBase64=c,t.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},t.getExcludeDirsFromEnv=function(){const e=process.env.HUD_EXCLUDE_DIRS;if(e)return e.split(",")},t.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let t;if(e)try{t=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{t=new Map}return t},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=t.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=t.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(t.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(t.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)};const s=n(8528),l=r(n(6928)),u=n(3903),d=n(1569);function c(e){return Buffer.from((0,u.parse)(e)).toString("base64").slice(0,22)}const m="globalThis._hudMark";t.HudDynamicConfigSchema=d.z.object({aggregationInterval:d.z.number(),aggregationFirstSendTimeout:d.z.number(),investigationInterval:d.z.number(),investigationFirstSendTimeout:d.z.number(),enableInvestigation:d.z.boolean(),enableInvestigationArgsSending:d.z.boolean(),investigationRateLimits:d.z.object({maxSameInvestigations:d.z.number().int().positive(),sameInvestigationTimeWindowMs:d.z.number().int().positive(),maxTotalInvestigations:d.z.number().int().positive(),maxTotalInvestigationsErrorBased:d.z.number().int().positive(),maxTotalInvestigationsDurationBased:d.z.number().int().positive(),totalInvestigationTimeWindowMs:d.z.number().int().positive(),maxUniqLogs:d.z.number().int().positive(),maxStringLength:d.z.number().int().positive(),maxArrayLength:d.z.number().int().positive(),maxObjectDepth:d.z.number().int().positive(),maxKeyLength:d.z.number().int().positive(),executionFlowMaxLength:d.z.number().int().positive(),exceptionMaxLength:d.z.number().int().positive()}),machineMetricsInterval:d.z.number().int().positive(),blacklistParams:d.z.array(d.z.string()),forensicsBlacklistFields:d.z.array(d.z.string()),forensicsWhitelistFields:d.z.array(d.z.string()),censorshipRegexes:d.z.array(d.z.object({regex:d.z.string(),replacement:d.z.string()})),reingestInterval:d.z.number().int().positive(),extraHeaders:d.z.array(d.z.string()),performanceMetricsInterval:d.z.number().int().positive(),enableOutboundData:d.z.boolean(),maxTotalOutbounds:d.z.number().int().positive(),maxOutboundCountWithData:d.z.number().int().positive(),maxHTTPRequestBodySize:d.z.number().int().positive(),maxHTTPResponseBodySize:d.z.number().int().positive()});const g=process.env.HUD_ENABLE_INVESTIGATION,p="_HUD",v="94a210f3-861c-4e18-ab27-6b6c19437c9d",b={sink:{url:process.env.HUD_HOST||"https://api-prod.hud.io",timeout:5e3,session_attr:"X-Session-ID"},endpoints:{init:"sink/init",send:"sink/send",batch:"sink/batch",logs:"sink/logs",sessionslessLogs:"sink/sessionless-logs",fatalError:"sink/redline",getMode:"sink/getMode",getRemoteConfig:"sink/remote-config/get",fileDeclarations:"sink/file-declarations",sourceMap:"sink/sourcemap",storeObject:"sink/objects/store",getUploadUrls:"sink/registry/get-upload-urls",triggerReingest:"sink/registry/reingest",validateToken:"sink/registry/validate",fileDeclarationsCi:"sink/registry/file-declarations",completed:"sink/registry/completed",endpointsDurationsInvestigationThresholds:"sink/endpoint-configuration"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.2",store:{type:"s3"}},userConfig:{minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},excludeDirs:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"},enableVarHoisting:{value:!1,source:"DEFAULT"},instrumentOneLiners:{value:!0,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:process.env.HUD_LOG_DIR,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,workerStateCollectionDelay:6e5,workerGrace:6e4,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:v,wrapVarPrefix:p,functionInitFunctionName:`${p}i`,functionCatchFunctionName:`${p}c`,functionFinallyFunctionName:`${p}n`,callContextVarName:`${p}x`,fixStackFunctionName:`${p}s`,asyncIteratorWrapperFunctionName:`${p}w`,wrapperUserCatchFunctionName:`${p}u`,beforeYieldFunctionName:`${p}b`,afterYieldFunctionName:`${p}a`,internalBeforeYieldFunctionName:`${p}j`,internalAfterYieldFunctionName:`${p}k`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[l.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(l.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[l.join("serverless-http","lib","framework","get-framework.js"),{framework:s.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}],["axios",{framework:s.availableFrameworks.axios,enable:!0,version:">0.18.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs",extraInfo:{isOutbound:!0}}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js",extraInfo:{isOutbound:!0}}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request",extraInfo:{isOutbound:!0}}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg",extraInfo:{isOutbound:!0}}],["ioredis",{framework:s.availableFrameworks.ioredis,enable:!0,version:"^4.0.0 || ^5.0.0",patcher:"outbound/ioredis",extraInfo:{isOutbound:!0}}],["p-limit",{framework:"p-limit",enable:!0,version:"^3.0.0",patcher:"internal/pLimit"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===g,enableInvestigationArgsSending:!0,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2,executionFlowMaxLength:20,exceptionMaxLength:20,maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:"true"!==process.env.HUD_DISABLE_SUPPRESS_TRACES,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:c((0,u.v5)("axios",v)),nodeFetchFunctionId:c((0,u.v5)("node-fetch",v)),nodeFetchBodiesFunctionIds:{json:c((0,u.v5)("node-fetch-body-json",v)),text:c((0,u.v5)("node-fetch-body-text",v)),arrayBuffer:c((0,u.v5)("node-fetch-body-arrayBuffer",v)),blob:c((0,u.v5)("node-fetch-body-blob",v))},requestFunctionId:c((0,u.v5)("request-request",v)),requestMethodFunctionIds:{get:c((0,u.v5)("request-get",v)),head:c((0,u.v5)("request-head",v)),options:c((0,u.v5)("request-options",v)),post:c((0,u.v5)("request-post",v)),put:c((0,u.v5)("request-put",v)),patch:c((0,u.v5)("request-patch",v)),del:c((0,u.v5)("request-del",v)),delete:c((0,u.v5)("request-delete",v))},pgConnectFunctionId:c((0,u.v5)("pg-connect",v)),pgQueryFunctionId:c((0,u.v5)("pg-query",v)),pgEndFunctionId:c((0,u.v5)("pg-end",v)),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[l.join(l.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildFunctionIdVar:"hudFI",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:m,nextJsMarkStatement:`${m} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};t.hudConfig=function(e={}){return{...b,...e}}({logger:{default:{levels:{app:"info",worker:"info",instrument:"info"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},deleteLogsAfterSending:!1,communicationKeepalive:!0}),t.default=t.hudConfig;const f=process.env.HUD_DEBUG?t.hudConfig.logger.debug:t.hudConfig.logger.default;t.loggerConfig={...f,console:"true"===process.env.HUD_VERBOSE};class h extends Error{path;code;constructor(e,t){super(),this.path=e,this.code=t}}t.HudFailedReadConfigError=h},3903:e=>{e.exports=require("uuid")},5453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=void 0,t.SDK_VERSION="1.7.8"},6928:e=>{e.exports=require("path")},7089:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectStoreConfigSchema=void 0;const i=n(1569),a=i.z.object({type:i.z.literal("s3")}),o=i.z.object({type:i.z.literal("disk"),path:i.z.string()});t.ObjectStoreConfigSchema=i.z.union([a,o])},8528:e=>{e.exports=require("./dto")}},t={};return function n(i){var a=t[i];if(void 0!==a)return a.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}(2509)})());
1
+ !function(e,n){if("object"==typeof exports&&"object"==typeof module)module.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{var t=n();for(var i in t)("object"==typeof exports?exports:e)[i]=t[i]}}(global,()=>(()=>{"use strict";var e={1569:e=>{e.exports=require("zod")},2210:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_MODULE_NAME=void 0,n.SDK_MODULE_NAME="hud-sdk"},2509:function(e,n,t){var i=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),a=this&&this.__exportStar||function(e,n){for(var t in e)"default"===t||Object.prototype.hasOwnProperty.call(n,t)||i(n,e,t)};Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=n.SDK_MODULE_NAME=void 0,a(t(2887),n),a(t(2570),n);var o=t(2210);Object.defineProperty(n,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return o.SDK_MODULE_NAME}}),a(t(7089),n);var r=t(5453);Object.defineProperty(n,"SDK_VERSION",{enumerable:!0,get:function(){return r.SDK_VERSION}})},2570:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateDynamicConfig=function(e,n,t){const o=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!o.success)return t.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:o,remoteConfig:e}),n.dynamicConfig;const r=a(n.dynamicConfig,o.data);return void 0!==r.enableInvestigation&&r.enableInvestigation!==n.dynamicConfig.enableInvestigation&&(t.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:r.enableInvestigation}),n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=r.enableInvestigation)),void 0!==r.enableInvestigationArgsSending&&r.enableInvestigationArgsSending!==n.dynamicConfig.enableInvestigationArgsSending&&(t.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:r.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=r.enableInvestigationArgsSending),void 0!==r?.investigationRateLimits?.executionFlowMaxLength&&r?.investigationRateLimits?.executionFlowMaxLength!==n.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=r.investigationRateLimits.executionFlowMaxLength),void 0!==r?.investigationRateLimits?.exceptionMaxLength&&r?.investigationRateLimits?.exceptionMaxLength!==n.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=r.investigationRateLimits.exceptionMaxLength),r};const i=t(2887);function a(e,n){if(null===n||"object"!=typeof n)return n;if(Array.isArray(e)&&Array.isArray(n))return n;const t={...e};for(const i in n){const o=e[i],r=n[i];t[i]=a(o,r)}return t}},2887:function(e,n,t){var i,a=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),o=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),r=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var n=[];for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[n.length]=t);return n},i(e)},function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var t=i(e),r=0;r<t.length;r++)"default"!==t[r]&&a(n,e,t[r]);return o(n,e),n});Object.defineProperty(n,"__esModule",{value:!0}),n.HudFailedReadConfigError=n.loggerConfig=n.hudConfig=n.HudDynamicConfigSchema=void 0,n.functionUuidToBase64=c,n.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},n.getExcludeDirsFromEnv=function(){const e=process.env.HUD_EXCLUDE_DIRS;if(e)return e.split(",")},n.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let n;if(e)try{n=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{n=new Map}return n},n.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},n.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)};const s=t(8528),l=r(t(6928)),u=t(3903),d=t(1569);function c(e){return Buffer.from((0,u.parse)(e)).toString("base64").slice(0,22)}const m="globalThis._hudMark";n.HudDynamicConfigSchema=d.z.object({aggregationInterval:d.z.number(),aggregationFirstSendTimeout:d.z.number(),investigationInterval:d.z.number(),investigationFirstSendTimeout:d.z.number(),enableInvestigation:d.z.boolean(),enableInvestigationArgsSending:d.z.boolean(),investigationRateLimits:d.z.object({maxSameInvestigations:d.z.number().int().positive(),sameInvestigationTimeWindowMs:d.z.number().int().positive(),maxTotalInvestigations:d.z.number().int().positive(),maxTotalInvestigationsErrorBased:d.z.number().int().positive(),maxTotalInvestigationsDurationBased:d.z.number().int().positive(),totalInvestigationTimeWindowMs:d.z.number().int().positive(),maxUniqLogs:d.z.number().int().positive(),maxStringLength:d.z.number().int().positive(),maxArrayLength:d.z.number().int().positive(),maxObjectDepth:d.z.number().int().positive(),maxKeyLength:d.z.number().int().positive(),executionFlowMaxLength:d.z.number().int().positive(),exceptionMaxLength:d.z.number().int().positive(),maxUniqueSetFailureErrors:d.z.number().int().positive()}),machineMetricsInterval:d.z.number().int().positive(),blacklistParams:d.z.array(d.z.string()),forensicsBlacklistFields:d.z.array(d.z.string()),forensicsWhitelistFields:d.z.array(d.z.string()),censorshipRegexes:d.z.array(d.z.object({regex:d.z.string(),replacement:d.z.string()})),reingestInterval:d.z.number().int().positive(),extraHeaders:d.z.array(d.z.string()),performanceMetricsInterval:d.z.number().int().positive(),enableOutboundData:d.z.boolean(),maxTotalOutbounds:d.z.number().int().positive(),maxOutboundCountWithData:d.z.number().int().positive(),maxHTTPRequestBodySize:d.z.number().int().positive(),maxHTTPResponseBodySize:d.z.number().int().positive(),functionDetachEnabled:d.z.boolean(),functionDetachThresholdPerSecond:d.z.number().int().positive()});const g=process.env.HUD_ENABLE_INVESTIGATION,p="_HUD",v="94a210f3-861c-4e18-ab27-6b6c19437c9d",b={sink:{url:process.env.HUD_HOST||"https://api-prod.hud.io",timeout:5e3,session_attr:"X-Session-ID"},endpoints:{init:"sink/init",send:"sink/send",batch:"sink/batch",logs:"sink/logs",sessionslessLogs:"sink/sessionless-logs",fatalError:"sink/redline",getMode:"sink/getMode",getRemoteConfig:"sink/remote-config/get",fileDeclarations:"sink/file-declarations",sourceMap:"sink/sourcemap",storeObject:"sink/objects/store",getUploadUrls:"sink/registry/get-upload-urls",triggerReingest:"sink/registry/reingest",validateToken:"sink/registry/validate",fileDeclarationsCi:"sink/registry/file-declarations",completed:"sink/registry/completed",endpointsDurationsInvestigationThresholds:"sink/endpoint-configuration",getKnownDetachedFunctions:"sink/known-detached-functions/get",setDetachedFunctions:"sink/known-detached-functions/set"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.2",store:{type:"s3"}},userConfig:{minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},excludeDirs:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"},disableDetachedFunctions:{value:!1,source:"DEFAULT"},enableVarHoisting:{value:!1,source:"DEFAULT"},instrumentOneLiners:{value:!0,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:process.env.HUD_LOG_DIR,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,workerStateCollectionDelay:6e5,workerGrace:6e4,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:v,wrapVarPrefix:p,functionInitFunctionName:`${p}i`,functionCatchFunctionName:`${p}c`,functionFinallyFunctionName:`${p}n`,callContextVarName:`${p}x`,fixStackFunctionName:`${p}s`,asyncIteratorWrapperFunctionName:`${p}w`,wrapperUserCatchFunctionName:`${p}u`,beforeYieldFunctionName:`${p}b`,afterYieldFunctionName:`${p}a`,internalBeforeYieldFunctionName:`${p}j`,internalAfterYieldFunctionName:`${p}k`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[l.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(l.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[l.join("serverless-http","lib","framework","get-framework.js"),{framework:s.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}],["axios",{framework:s.availableFrameworks.axios,enable:!0,version:">0.18.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs",extraInfo:{isOutbound:!0}}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js",extraInfo:{isOutbound:!0}}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request",extraInfo:{isOutbound:!0}}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg",extraInfo:{isOutbound:!0}}],["ioredis",{framework:s.availableFrameworks.ioredis,enable:!0,version:"^4.0.0 || ^5.0.0",patcher:"outbound/ioredis",extraInfo:{isOutbound:!0}}],["p-limit",{framework:"p-limit",enable:!0,version:"^3.0.0",patcher:"internal/pLimit"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===g,enableInvestigationArgsSending:!1,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2,executionFlowMaxLength:20,exceptionMaxLength:20,maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30,maxUniqueSetFailureErrors:100},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20,functionDetachEnabled:!1,functionDetachThresholdPerSecond:5833},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:"true"!==process.env.HUD_DISABLE_SUPPRESS_TRACES,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:c((0,u.v5)("axios",v)),nodeFetchFunctionId:c((0,u.v5)("node-fetch",v)),nodeFetchBodiesFunctionIds:{json:c((0,u.v5)("node-fetch-body-json",v)),text:c((0,u.v5)("node-fetch-body-text",v)),arrayBuffer:c((0,u.v5)("node-fetch-body-arrayBuffer",v)),blob:c((0,u.v5)("node-fetch-body-blob",v))},requestFunctionId:c((0,u.v5)("request-request",v)),requestMethodFunctionIds:{get:c((0,u.v5)("request-get",v)),head:c((0,u.v5)("request-head",v)),options:c((0,u.v5)("request-options",v)),post:c((0,u.v5)("request-post",v)),put:c((0,u.v5)("request-put",v)),patch:c((0,u.v5)("request-patch",v)),del:c((0,u.v5)("request-del",v)),delete:c((0,u.v5)("request-delete",v))},pgConnectFunctionId:c((0,u.v5)("pg-connect",v)),pgQueryFunctionId:c((0,u.v5)("pg-query",v)),pgEndFunctionId:c((0,u.v5)("pg-end",v)),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[l.join(l.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildFunctionIdVar:"hudFI",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:m,nextJsMarkStatement:`${m} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};n.hudConfig=function(e={}){return{...b,...e}}({logger:{default:{levels:{app:"info",worker:"info",instrument:"info"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},deleteLogsAfterSending:!1,communicationKeepalive:!0}),n.default=n.hudConfig;const f=process.env.HUD_DEBUG?n.hudConfig.logger.debug:n.hudConfig.logger.default;n.loggerConfig={...f,console:"true"===process.env.HUD_VERBOSE};class h extends Error{path;code;constructor(e,n){super(),this.path=e,this.code=n}}n.HudFailedReadConfigError=h},3903:e=>{e.exports=require("uuid")},5453:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=void 0,n.SDK_VERSION="1.7.9"},6928:e=>{e.exports=require("path")},7089:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ObjectStoreConfigSchema=void 0;const i=t(1569),a=i.z.object({type:i.z.literal("s3")}),o=i.z.object({type:i.z.literal("disk"),path:i.z.string()});n.ObjectStoreConfigSchema=i.z.union([a,o])},8528:e=>{e.exports=require("./dto")}},n={};return function t(i){var a=n[i];if(void 0!==a)return a.exports;var o=n[i]={exports:{}};return e[i].call(o.exports,o,o.exports,t),o.exports}(2509)})());
2
2
  //# sourceMappingURL=config.js.map
package/dist/cjs/core.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(i(523)),d=i(8528),c=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==d.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){c.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=s(i(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const n=i(8167),o=i(2546),s=i(5809),a=i(8269),d=i(523),c=i(6281),g=r(i(7320));function l(){globalThis.hudInstrumentationOccured&&d.customer_logger.logEntry(o.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,i,r){this.apiKey=e,this.service=t,this.startTime=i,this.tags=r,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof o.HudSessionThrottle?(d.customer_logger.logEntry(o.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1,!0)):e instanceof o.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.logEntry((0,o.getNetworkError)(e.originalAxiosErrorCode)),d.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,c._detachAndTerminate)(!1,!1,!0)):(d.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,o.setFirstError)(e.code),(0,c._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,o.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.logEntry(o.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(n.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();d.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,o.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{d.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new o.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(l,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof o.HudSessionThrottle)throw e;throw d.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=o.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),i={...process.env};delete i.NODE_OPTIONS;const r=new n.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:s.hudConfig.userConfig},execArgv:[],env:i});let a;try{a=new g.default(r),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof o.HudSessionThrottle)throw d.app_logger.info("Worker started in idle mode - session throttled"),e;throw d.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{r.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(d.app_logger.info("Remote configuration exists"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,d.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),d.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):d.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:s.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,i){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void n.app_logger.warning("Already ran init!");globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),(0,r.updateUserConfigFromInit)(e,t,i);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void n.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(n.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new o.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.safeCall)(n.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;n.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof c.HudSessionThrottle)return;n.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{n.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.tryFlushPendingLogs=async function(e,t){(0,d.getShouldFlushOnInit)()&&((0,d.markShouldFlushOnInit)(!1),await f(e,t))};const r=i(2546),n=i(523),o=i(5994),s=i(5809),a=i(8528),d=i(8269),c=i(2546),g=i(7274);let l,u=!1;function h(e=!0,t=!1,i=!1){(0,d.detachHud)(e,t),i&&(0,c.safeCall)(n.app_logger,f()),l&&(0,c.safeCall)(n.app_logger,l.terminateMessenger());const o=(0,d.getLambdaExtensionId)();o&&!u&&(u=!0,(0,c.safeCall)(n.app_logger,(0,r.nextLoopDummy)(o))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const r=(0,d.getSessionInfo)(),o=(0,d.getStoredApiKey)(),s=(0,d.getStoredService)();try{const a=e||o;if(!a||"string"!=typeof a)return;const d=t||s||"unknown",c=(0,n.getSavedLogs)();for(const e of c){const{HudClient:t}=i(4672),o=new t;r?(n.app_logger.info("Flushing logs with session",{size:e.length,sessionId:r.sessionId,service:d}),o.setSession(r),await o.logs(e)):(n.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:d}),await o.sessionslessLogs(e,a)),n.app_logger.info("Successfully flushed logs")}}catch(e){try{n.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==r})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const i=(new Date).toISOString(),o=[];return Object.entries(hudCalls).map(([r,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const n={function_id:r,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:i,timeslice:e,exceptions:s(c.exceptions),count:c.count,sampled_count:c.sampledCount,sum_duration:c.sum,sum_squared_duration:c.squareSum,sketch:c.sketch?t.encode(c.sketch):void 0,is_linked_function:c.isLinkedFunction};o.push(n),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){n.app_logger.error("Failed preparing invocation, skipping",{func:r,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),o.length>0&&(0,r.clearMetricsIndicator)(),o},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const i in globalThis.hudCalls[e][t])o(globalThis.hudCalls[e][t][i])};const r=i(8269),n=i(523);function o(e){e.samplingCounter=0}function s(e){const t={};for(const i in e)t[i]=[{count:e[i]}];return t}},7320:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(i(523)),d=s(i(6460)),c=i(5809),g=i(2546),l=i(8528),u=i(2546),h=i(7131),f=i(8269),m=i(2546),p=i(7274),v=i(2702),y=i(8269),w=i(2546),k=i(6281),C=i(8269),b=i(2546),E=i(6261),_=a.app_logger,T=m.safeCall.bind(m.safeCall,_);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new E.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,E.setMaxListeners)(20,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,_.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,c.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&_.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.logEntry(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),_.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,k._detachAndTerminate)(!0,!1,!0)}catch(e){_.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),_.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const i={msg:e,content:t};this.worker.postMessage(i)}async checkWorker(e){const t=["started"];let i;try{i=await this.getMessageFromWorker(t,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;i=await this.getMessageFromWorker(t,e/2,!1)}if(!i)throw new m.HudInitError("Worker not started");return i}async checkWorkerInitialized(e){let t;const i=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(i,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;t=await this.getMessageFromWorker(i,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw _.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:_.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),T(this.delayedStateCollection()),T(this.periodicSendEndpoints()),T(this.periodicSendOutbounds()),T(this.periodicSendLazyEndpoints()),T(this.periodicSendKafkaJS()),T(this.periodicSendSqs()),T(this.periodicSendGraphQL()),T(this.sendStaticNextJsEndpointsOnce()),T(this.periodicSaveMachineMetrics()),T(this.periodicSendReingest()),T(this.resetCallerCounters()),T(this.periodicResetGlobalInvestigationCounter()),T(this.periodicResetInvestigationDedupingCache()),T(this.sendLogsPeriodically(c.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:_.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:_.info("Detached"),(0,k._detachAndTerminate)(!1,!1),this.stop();break;default:_.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,i=!1,r){let n;e=Array.isArray(e)?e:[e];const o=this.consumeMessageFromQueue(e);if(o)return _.info("Found message in queue",{msg:o.msg}),o;const s=new AbortController,a=()=>{s.abort()};this.abortController.signal.addEventListener("abort",a);const c=d.setTimeout(t,void 0,{signal:s.signal,ref:i}),g=t=>{try{e.includes(t.msg)&&(n=t,s.abort(),this.consumeMessageFromQueue([t.msg]),_.info("Received message from worker (canceling timeout)",t))}catch(e){_.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),r&&this.worker.postMessage(r);try{throw await c,_.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return n}async getMode(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,c.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){_.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){_.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,c.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){_.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=c.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting caller",{interval:e}),(0,p.resetCallers)()}catch(e){_.error("Failed reseting caller counters",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const i=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,!1,e);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);(0,f.setInvestigationDurationThresholds)(i?.content),_.debug("Endpoints durations investigation thresholds updated",{thresholds:i?.content})}catch(e){_.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async delayedStateCollection(){await this.setupPeriodicTask(0,c.hudConfig.workerStateCollectionDelay,()=>{try{this._updateTsNodeConfig()&&_.info("ts-node config updated from delayed task")}catch(e){_.error("Failed collecting state from delayed task",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"delayedStateCollecgtion",!0)}async periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,y.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,y.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,y.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,i=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,i,t=>{try{this.refreshInvestigations()}catch(e){_.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const i=(0,p.prepCalls)(t,e);i.length>0&&this._sendArray("Invocations",i)}catch(e){_.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=(0,f.getFlowMetrics)(t);Object.keys(e).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:e})}catch(e){_.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async highFrequencySendInvestigations(){if(!c.hudConfig.dynamicConfig.enableInvestigation)return;const e=c.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=c.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,y.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,y.getExpressEndpointDeclarations)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendEndpoints(){const e=(0,f.getEndpointDeclarationsFromStorage)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,C.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e);const t=(0,C.getIoredisCommandsFromStorage)();t.length>0&&this._sendArray("IoredisCommands",t)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw _.critical("Unexpected error during worker termination",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),await this.worker.terminate(),e;_.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}_.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:i.c[i.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):_.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=c.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,m.collectThreadPerformance)(t,_,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(w.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void _.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,i,r,n=!1){function o(e){let t=!0;try{t=i(e)}catch(e){_.error("Failed in periodic task",{taskName:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),o(e)){if(!n)for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!o(t))return void _.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:r})}else _.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:r})}async periodicResetGlobalInvestigationCounter(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting global investigation counter",{interval:e}),(0,y.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){_.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting investigation deduping cache",{interval:e}),(0,y.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){_.error("Failed resetting investigation deduping cache",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,b.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,_.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,k._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let i=0;for await(const r of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(i++,_.debug("Attempting to send static next.js endpoints",{attemptCount:i}),(0,y.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){_.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,y.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,y.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(i>t){_.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,y.isNextConfigExtracted)(),attemptCount:i});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.reingestInterval,void 0,{signal:this.abortController.signal})){const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,i),o.exports}return i.c=t,i(i.s=5119)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(n(523)),c=n(8528),d=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==c.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){d.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=s(n(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const o=n(8167),r=n(2546),s=n(5809),a=n(8269),c=n(523),d=n(7274),g=n(6281),l=i(n(7320));function u(){globalThis.hudInstrumentationOccured&&c.customer_logger.logEntry(r.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,n,i){this.apiKey=e,this.service=t,this.startTime=n,this.tags=i,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof r.HudSessionThrottle?(c.customer_logger.logEntry(r.UserLogs.InitIdleMode()),(0,g._detachAndTerminate)(!1,!1,!0)):e instanceof r.HudInitNetworkError&&e.originalAxiosErrorCode?(c.customer_logger.logEntry((0,r.getNetworkError)(e.originalAxiosErrorCode)),c.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,g._detachAndTerminate)(!1,!1,!0)):(c.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,r.setFirstError)(e.code),(0,g._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,r.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),c.customer_logger.logEntry(r.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(o.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();c.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,r.next)(e).then(async()=>{c.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{c.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new r.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;if(t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),s.hudConfig.dynamicConfig.functionDetachEnabled&&!s.hudConfig.userConfig.disableDetachedFunctions?.value){const e=await(this.messenger?.getKnownDetachedFunctions(!0));e&&(0,d.applyKnownDetachedFunctions)(e)}globalThis.hudMetricsIndicator=setTimeout(u,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof r.HudSessionThrottle)throw e;throw c.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=r.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),n={...process.env};delete n.NODE_OPTIONS;const i=new o.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:s.hudConfig.userConfig},execArgv:[],env:n});let a;try{a=new l.default(i),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof r.HudSessionThrottle)throw c.app_logger.info("Worker started in idle mode - session throttled"),e;throw c.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{i.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(c.app_logger.info("Remote configuration exists"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,c.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),c.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):c.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:s.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,n){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void o.app_logger.warning("Already ran init!");globalThis.hudRunMutex=!0,(0,c.clearInitGuard)(),(0,i.updateUserConfigFromInit)(e,t,n);const g=(0,c.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void o.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(o.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new r.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,d.safeCall)(o.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;o.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof d.HudSessionThrottle)return;o.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{o.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.tryFlushPendingLogs=async function(e,t){(0,c.getShouldFlushOnInit)()&&((0,c.markShouldFlushOnInit)(!1),await f(e,t))};const i=n(2546),o=n(523),r=n(5994),s=n(5809),a=n(8528),c=n(8269),d=n(2546),g=n(7274);let l,u=!1;function h(e=!0,t=!1,n=!1){(0,c.detachHud)(e,t),n&&(0,d.safeCall)(o.app_logger,f()),l&&(0,d.safeCall)(o.app_logger,l.terminateMessenger());const r=(0,c.getLambdaExtensionId)();r&&!u&&(u=!0,(0,d.safeCall)(o.app_logger,(0,i.nextLoopDummy)(r))),(0,c.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const i=(0,c.getSessionInfo)(),r=(0,c.getStoredApiKey)(),s=(0,c.getStoredService)();try{const a=e||r;if(!a||"string"!=typeof a)return;const c=t||s||"unknown",d=(0,o.getSavedLogs)();for(const e of d){const{HudClient:t}=n(4672),r=new t;i?(o.app_logger.info("Flushing logs with session",{size:e.length,sessionId:i.sessionId,service:c}),r.setSession(i),await r.logs(e)):(o.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:c}),await r.sessionslessLogs(e,a)),o.app_logger.info("Successfully flushed logs")}}catch(e){try{o.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==i})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._setLastPrepCallsTimestamp=c,t._liftExceptions=g,t.prepCalls=function(e,t){let n=null;if(i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){const e=process.hrtime.bigint();let t;t=null===a?i.hudConfig.dynamicConfig.aggregationInterval:Number(e-a)/1e6,c(e),n=i.hudConfig.dynamicConfig.functionDetachThresholdPerSecond*(t/1e3)}const d=(new Date).toISOString(),l=[];return Object.entries(hudCalls).map(([o,a])=>{const c=a.shouldDetach;let u=0;var h;Object.entries(a).forEach(([n,s])=>{"shouldDetach"!==n&&Object.entries(s).forEach(([s,a])=>{try{if(!i.hudConfig.dynamicConfig.functionDetachEnabled||i.hudConfig.userConfig.disableDetachedFunctions?.value||c||(u+=a.count),0===a.sampledCount)return;const r={function_id:o,wrapped_flow_id:s||void 0,wrapped_caller_id:n||void 0,timestamp:d,timeslice:e,exceptions:g(a.exceptions),count:a.count,sampled_count:a.sampledCount,sum_duration:a.sum,sum_squared_duration:a.squareSum,sketch:a.sketch?t.encode(a.sketch):void 0,is_linked_function:a.isLinkedFunction};l.push(r),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(a)}catch(e){r.app_logger.error("Failed preparing invocation, skipping",{func:o,wrappedCaller:n,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}),i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&null!==n&&u>n&&(hudCalls[o].shouldDetach=!0,h=o,s.push(h),r.app_logger.info("Detaching function",{func:o,totalFunctionCalls:u}))}),l.length>0&&(0,o.clearMetricsIndicator)(),l},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])if("shouldDetach"!==t)for(const n in globalThis.hudCalls[e][t])d(globalThis.hudCalls[e][t][n])},t.getAndClearDetachedFunctions=function(){const e=s;return s=[],e},t.applyKnownDetachedFunctions=function(e){if(e&&0!==e.length&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){l!==e.length&&(r.app_logger.info("Applying known detached functions from host",{count:e.length}),l=e.length);for(const t of e)try{globalThis.hudCalls[t]?globalThis.hudCalls[t].shouldDetach=!0:globalThis.hudCalls[t]={shouldDetach:!0}}catch(e){r.app_logger.error("Failed to apply detached function, skipping",{rawFunctionId:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const i=n(5809),o=n(8269),r=n(523);let s=[],a=null;function c(e){a=e}function d(e){e.samplingCounter=0}function g(e){const t={};for(const n in e)t[n]=[{count:e[n]}];return t}let l=0},7320:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(n(523)),c=s(n(6460)),d=n(5809),g=n(2546),l=n(8528),u=n(2546),h=n(7131),f=n(8269),m=n(2546),p=n(7274),v=n(2702),y=n(8269),w=n(2546),C=n(6281),k=n(8269),b=n(2546),E=n(6261),_=a.app_logger,T=m.safeCall.bind(m.safeCall,_);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new E.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,E.setMaxListeners)(25,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,_.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,d.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&_.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.logEntry(m.UserErrorLogs.ApiKeyDenied(d.hudConfig.userConfig.key?.source)),_.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,C._detachAndTerminate)(!0,!1,!0)}catch(e){_.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),_.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const n={msg:e,content:t};this.worker.postMessage(n)}async checkWorker(e){const t=["started"];let n;try{n=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;n=await this.getMessageFromWorker(t,e/2,!1)}if(!n)throw new m.HudInitError("Worker not started");return n}async checkWorkerInitialized(e){let t;const n=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(n,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(n,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw _.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:_.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.periodicSendDetachedFunctions()),T(this.periodicFetchKnownDetachedFunctions()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),T(this.delayedStateCollection()),T(this.periodicSendEndpoints()),T(this.periodicSendOutbounds()),T(this.periodicSendLazyEndpoints()),T(this.periodicSendKafkaJS()),T(this.periodicSendSqs()),T(this.periodicSendGraphQL()),T(this.sendStaticNextJsEndpointsOnce()),T(this.periodicSaveMachineMetrics()),T(this.periodicSendReingest()),T(this.resetCallerCounters()),T(this.periodicResetGlobalInvestigationCounter()),T(this.periodicResetInvestigationDedupingCache()),T(this.sendLogsPeriodically(d.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:_.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:_.info("Detached"),(0,C._detachAndTerminate)(!1,!1),this.stop();break;default:_.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,n=!1,i){let o;e=Array.isArray(e)?e:[e];const r=this.consumeMessageFromQueue(e);if(r)return _.info("Found message in queue",{msg:r.msg}),r;const s=new AbortController,a=()=>{s.abort()};this.abortController.signal.addEventListener("abort",a);const d=c.setTimeout(t,void 0,{signal:s.signal,ref:n}),g=t=>{try{e.includes(t.msg)&&(o=t,s.abort(),this.consumeMessageFromQueue([t.msg]),_.info("Received message from worker (canceling timeout)",t))}catch(e){_.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),i&&this.worker.postMessage(i);try{throw await d,_.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return o}async getMode(){for await(const e of(0,u.unrefSetInterval)(d.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,d.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){_.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){_.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){_.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getKnownDetachedFunctions(e=!1){const t="KnownDetachedFunctions",n={msg:"GetKnownDetachedFunctions",content:{}};try{const i=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,e,n);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);return i?.content}catch(e){return _.error("Failed getting known detached functions from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(d.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=d.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting caller",{interval:e}),(0,p.resetCallers)()}catch(e){_.error("Failed reseting caller counters",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const n=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,!1,e);if(n?.msg!==t||void 0===n?.content)throw new Error(`Unexpected message from worker: ${n}`);(0,f.setInvestigationDurationThresholds)(n?.content),_.debug("Endpoints durations investigation thresholds updated",{thresholds:n?.content})}catch(e){_.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds();for await(const e of(0,u.unrefSetInterval)(d.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async delayedStateCollection(){await this.setupPeriodicTask(0,d.hudConfig.workerStateCollectionDelay,()=>{try{this._updateTsNodeConfig()&&_.info("ts-node config updated from delayed task")}catch(e){_.error("Failed collecting state from delayed task",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"delayedStateCollecgtion",!0)}async periodicSendProcessedFiles(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,y.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,y.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,y.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(d.hudConfig.huddBinWidth),t=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,n=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,n,t=>{try{this.refreshInvestigations()}catch(e){_.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const n=(0,p.prepCalls)(t,e);n.length>0&&this._sendArray("Invocations",n)}catch(e){_.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=(0,f.getFlowMetrics)(t);Object.keys(e).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:e})}catch(e){_.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async periodicSendDetachedFunctions(){if(!d.hudConfig.dynamicConfig.functionDetachEnabled||d.hudConfig.userConfig.disableDetachedFunctions?.value)return;const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{try{const e=(0,p.getAndClearDetachedFunctions)();e.length>0&&this._sendArray("DetachedFunctions",e)}catch(e){_.error("Failed sending detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendDetachedFunctions")}async fetchKnownDetachedFunctions(){try{const e=await this.getKnownDetachedFunctions();e&&e.length>0&&(0,p.applyKnownDetachedFunctions)(e)}catch(e){_.error("Failed fetching known detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicFetchKnownDetachedFunctions(){if(d.hudConfig.dynamicConfig.functionDetachEnabled&&!d.hudConfig.userConfig.disableDetachedFunctions?.value)for await(const e of(0,u.unrefSetInterval)(d.hudConfig.dynamicConfig.aggregationInterval,void 0,{signal:this.abortController.signal}))await this.fetchKnownDetachedFunctions()}async highFrequencySendInvestigations(){if(!d.hudConfig.dynamicConfig.enableInvestigation)return;const e=d.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=d.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,y.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,y.getExpressEndpointDeclarations)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendEndpoints(){const e=(0,f.getEndpointDeclarationsFromStorage)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,k.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e);const t=(0,k.getIoredisCommandsFromStorage)();t.length>0&&this._sendArray("IoredisCommands",t)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",d.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:d.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw _.critical("Unexpected error during worker termination",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),await this.worker.terminate(),e;_.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}_.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:n.c[n.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):_.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=d.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const n of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,m.collectThreadPerformance)(t,_,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(w.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void _.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,n,i,o=!1){function r(e){let t=!0;try{t=n(e)}catch(e){_.error("Failed in periodic task",{taskName:i,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),r(e)){if(!o)for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!r(t))return void _.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:i})}else _.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:i})}async periodicResetGlobalInvestigationCounter(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting global investigation counter",{interval:e}),(0,y.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){_.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting investigation deduping cache",{interval:e}),(0,y.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){_.error("Failed resetting investigation deduping cache",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,b.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,_.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,C._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=d.hudConfig.staticNextJsEndpointsInterval,t=d.hudConfig.staticNextJsEndpointsMaxAttempts;let n=0;for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(n++,_.debug("Attempting to send static next.js endpoints",{attemptCount:n}),(0,y.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){_.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,y.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,y.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(n>t){_.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,y.isNextConfigExtracted)(),attemptCount:n});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(d.hudConfig.dynamicConfig.reingestInterval,void 0,{signal:this.abortController.signal})){const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function n(i){var o=t[i];if(void 0!==o)return o.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}return n.c=t,n(n.s=5119)})());
2
2
  //# sourceMappingURL=core.js.map
package/dist/cjs/dto.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,()=>(()=>{"use strict";var e={765:(e,t)=>{var o,r;Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionInitStatus=t.HudRunningMode=t.KeepAliveMessage=void 0,t.KeepAliveMessage={msg:"keep-alive"},function(e){e[e.detached=0]="detached",e[e.disabled=1]="disabled",e[e.enabled=2]="enabled"}(o||(t.HudRunningMode=o={})),function(e){e[e.success=0]="success",e[e.throttled=1]="throttled"}(r||(t.HudSessionInitStatus=r={}))},878:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLSupportedOperations=void 0,function(e){e.query="query",e.mutation="mutation",e.subscription="subscription"}(o||(t.GraphQLSupportedOperations=o={}))},1569:e=>{e.exports=require("zod")},2176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3487:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var n=Object.getOwnPropertyDescriptor(t,o);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,n)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=t[o]}),n=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||r(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),n(o(7789),t),n(o(8086),t),n(o(7935),t),n(o(6910),t),n(o(2176),t),n(o(9107),t),n(o(7022),t),n(o(6604),t),n(o(4909),t),n(o(878),t),n(o(8377),t),n(o(8054),t),n(o(6328),t),n(o(6413),t),n(o(6364),t),n(o(765),t)},4909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionOptionsSchema=t.HudOptionsSchema=void 0;const r=o(1569),n=o(7789);t.HudOptionsSchema=r.z.object({includeModules:r.z.array(r.z.string()).optional(),excludeDirs:r.z.array(r.z.string()).optional(),enableFrameworks:n.availableFrameworksSchema.optional(),maxMappedFunctions:r.z.number().optional(),minPodMemoryMB:r.z.number().optional(),maxFileSizeBytes:r.z.number().optional(),maxTimeUntilInitSessionMs:r.z.number().optional(),verbose:r.z.boolean().optional(),disableSourceMapsResolution:r.z.boolean().optional(),disableRuntimeInstrumentation:r.z.boolean().optional(),disableParametersExtraction:r.z.boolean().optional(),customOptions:r.z.record(r.z.string(),r.z.string()).optional()}),t.HudSessionOptionsSchema=r.z.object({tags:r.z.record(r.z.string(),r.z.string()).optional()})},6413:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6604:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6910:(e,t)=>{var o,r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.EntityType=t.ArgumentTypes=t.ParameterTypes=void 0,function(e){e.Identifier="Identifier",e.RestElement="RestElement",e.ArrayPattern="ArrayPattern",e.AssignmentPattern="AssignmentPattern",e.ObjectPattern="ObjectPattern",e.ObjectProperty="ObjectProperty"}(o||(t.ParameterTypes=o={})),function(e){e.StringLiteral="StringLiteral",e.Identifier="Identifier",e.TemplateString="TemplateString"}(r||(t.ArgumentTypes=r={})),function(e){e.FunctionDeclaration="functionDeclaration",e.FunctionExpression="functionExpression",e.FunctionArrow="functionArrow",e.ClassMethod="classMethod",e.ObjectMethod="objectMethod",e.ClassPrivateMethod="classPrivateMethod",e.ClassDeclaration="classDeclaration",e.ClassExpression="classExpression",e.ObjectExpression="objectExpression",e.Program="program",e.ForLoop="forLoop",e.ForBlock="forBlock",e.ForTest="forTest",e.Block="block",e.While="while",e.DoWhile="doWhile",e.Do="Do",e.WhileTest="whileTest",e.Switch="switch",e.SwitchCase="switchCase",e.Catch="catch",e.With="with",e.If="if",e.IfTest="ifTest",e.IfConsequent="ifConsequent",e.IfAlternate="ifAlternate",e.TryCatch="tryCatch",e.Try="try",e.Finally="finally",e.Other="other",e.File="file"}(n||(t.EntityType=n={}))},7022:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.Format=t.FUNCTION_DECLARATION_VERSION=void 0,t.isSupportedFormat=function(e){return Object.values(o).includes(e)},t.FUNCTION_DECLARATION_VERSION="1.1.3",function(e){e.cjs="commonjs",e.esm="module",e.ts="typescript",e.moduleTypescript="module-typescript",e.commonjsTypescript="commonjs-typescript"}(o||(t.Format=o={}))},7789:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.availableFrameworksSchema=t.availableFrameworks=void 0;const r=o(1569);t.availableFrameworks={axios:"axios",pg:"pg",ioredis:"ioredis",nodeFetch:"nodeFetch",request:"request",express:"express",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp"},t.availableFrameworksSchema=r.z.union([r.z.map(r.z.nativeEnum(t.availableFrameworks),r.z.boolean()),r.z.record(r.z.nativeEnum(t.availableFrameworks),r.z.boolean())]).transform(e=>e instanceof Map?e:new Map(Object.entries(e)))},7935:(e,t)=>{function o(e,t){return t?t instanceof RegExp?e+t.toString():("/"===t[t.length-1]&&t.length>1&&(t=t.slice(0,-1)),(t=e+t).replace(/\/{2,}/g,"/")):t}Object.defineProperty(t,"__esModule",{value:!0}),t.EndpointDeclaration=void 0,t.EndpointDeclaration=class{flow_id;methods;framework;partial_path;path;constructor(e,t,r,n,i,s){this.flow_id=e,this.methods=t,this.framework=r,this.partial_path=s,n||(n=""),this.path=o(n,i),this.partial_path=o(n,s)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8086:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o,r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.OutboundType=t.InvestigationType=t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(o||(t.InvestigationStatus=o={})),function(e){e.HTTP="http",e.SQS="sqs",e.Kafka="kafka",e.GraphQL="graphql"}(r||(t.InvestigationType=r={})),function(e){e.HTTP="http",e.DB="db",e.REDIS="redis"}(n||(t.OutboundType=n={}))},9107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})}},t={};return function o(r){var n=t[r];if(void 0!==n)return n.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,o),i.exports}(3487)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,()=>(()=>{"use strict";var e={765:(e,t)=>{var o,r;Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionInitStatus=t.HudRunningMode=t.KeepAliveMessage=void 0,t.KeepAliveMessage={msg:"keep-alive"},function(e){e[e.detached=0]="detached",e[e.disabled=1]="disabled",e[e.enabled=2]="enabled"}(o||(t.HudRunningMode=o={})),function(e){e[e.success=0]="success",e[e.throttled=1]="throttled"}(r||(t.HudSessionInitStatus=r={}))},878:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLSupportedOperations=void 0,function(e){e.query="query",e.mutation="mutation",e.subscription="subscription"}(o||(t.GraphQLSupportedOperations=o={}))},1569:e=>{e.exports=require("zod")},2176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3487:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var n=Object.getOwnPropertyDescriptor(t,o);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,n)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=t[o]}),n=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||r(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),n(o(7789),t),n(o(8086),t),n(o(7935),t),n(o(6910),t),n(o(2176),t),n(o(9107),t),n(o(7022),t),n(o(6604),t),n(o(4909),t),n(o(878),t),n(o(8377),t),n(o(8054),t),n(o(6328),t),n(o(6413),t),n(o(6364),t),n(o(765),t)},4909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionOptionsSchema=t.HudOptionsSchema=void 0;const r=o(1569),n=o(7789);t.HudOptionsSchema=r.z.object({includeModules:r.z.array(r.z.string()).optional(),excludeDirs:r.z.array(r.z.string()).optional(),enableFrameworks:n.availableFrameworksSchema.optional(),maxMappedFunctions:r.z.number().optional(),minPodMemoryMB:r.z.number().optional(),maxFileSizeBytes:r.z.number().optional(),maxTimeUntilInitSessionMs:r.z.number().optional(),verbose:r.z.boolean().optional(),disableSourceMapsResolution:r.z.boolean().optional(),disableRuntimeInstrumentation:r.z.boolean().optional(),disableParametersExtraction:r.z.boolean().optional(),disableDetachedFunctions:r.z.boolean().optional(),customOptions:r.z.record(r.z.string(),r.z.string()).optional()}),t.HudSessionOptionsSchema=r.z.object({tags:r.z.record(r.z.string(),r.z.string()).optional()})},6413:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6604:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6910:(e,t)=>{var o,r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.EntityType=t.ArgumentTypes=t.ParameterTypes=void 0,function(e){e.Identifier="Identifier",e.RestElement="RestElement",e.ArrayPattern="ArrayPattern",e.AssignmentPattern="AssignmentPattern",e.ObjectPattern="ObjectPattern",e.ObjectProperty="ObjectProperty"}(o||(t.ParameterTypes=o={})),function(e){e.StringLiteral="StringLiteral",e.Identifier="Identifier",e.TemplateString="TemplateString"}(r||(t.ArgumentTypes=r={})),function(e){e.FunctionDeclaration="functionDeclaration",e.FunctionExpression="functionExpression",e.FunctionArrow="functionArrow",e.ClassMethod="classMethod",e.ObjectMethod="objectMethod",e.ClassPrivateMethod="classPrivateMethod",e.ClassDeclaration="classDeclaration",e.ClassExpression="classExpression",e.ObjectExpression="objectExpression",e.Program="program",e.ForLoop="forLoop",e.ForBlock="forBlock",e.ForTest="forTest",e.Block="block",e.While="while",e.DoWhile="doWhile",e.Do="Do",e.WhileTest="whileTest",e.Switch="switch",e.SwitchCase="switchCase",e.Catch="catch",e.With="with",e.If="if",e.IfTest="ifTest",e.IfConsequent="ifConsequent",e.IfAlternate="ifAlternate",e.TryCatch="tryCatch",e.Try="try",e.Finally="finally",e.Other="other",e.File="file"}(n||(t.EntityType=n={}))},7022:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.Format=t.FUNCTION_DECLARATION_VERSION=void 0,t.isSupportedFormat=function(e){return Object.values(o).includes(e)},t.FUNCTION_DECLARATION_VERSION="1.1.3",function(e){e.cjs="commonjs",e.esm="module",e.ts="typescript",e.moduleTypescript="module-typescript",e.commonjsTypescript="commonjs-typescript"}(o||(t.Format=o={}))},7789:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.availableFrameworksSchema=t.availableFrameworks=void 0;const r=o(1569);t.availableFrameworks={axios:"axios",pg:"pg",ioredis:"ioredis",nodeFetch:"nodeFetch",request:"request",express:"express",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp"},t.availableFrameworksSchema=r.z.union([r.z.map(r.z.nativeEnum(t.availableFrameworks),r.z.boolean()),r.z.record(r.z.nativeEnum(t.availableFrameworks),r.z.boolean())]).transform(e=>e instanceof Map?e:new Map(Object.entries(e)))},7935:(e,t)=>{function o(e,t){return t?t instanceof RegExp?e+t.toString():("/"===t[t.length-1]&&t.length>1&&(t=t.slice(0,-1)),(t=e+t).replace(/\/{2,}/g,"/")):t}Object.defineProperty(t,"__esModule",{value:!0}),t.EndpointDeclaration=void 0,t.EndpointDeclaration=class{flow_id;methods;framework;partial_path;path;constructor(e,t,r,n,i,a){this.flow_id=e,this.methods=t,this.framework=r,this.partial_path=a,n||(n=""),this.path=o(n,i),this.partial_path=o(n,a)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8086:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o,r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.OutboundType=t.InvestigationType=t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(o||(t.InvestigationStatus=o={})),function(e){e.HTTP="http",e.SQS="sqs",e.Kafka="kafka",e.GraphQL="graphql"}(r||(t.InvestigationType=r={})),function(e){e.HTTP="http",e.DB="db",e.REDIS="redis"}(n||(t.OutboundType=n={}))},9107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})}},t={};return function o(r){var n=t[r];if(void 0!==n)return n.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,o),i.exports}(3487)})());
2
2
  //# sourceMappingURL=dto.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var o in n)("object"==typeof exports?exports:e)[o]=n[o]}}(global,()=>(()=>{"use strict";var e={290:e=>{e.exports=require("async_hooks")},395:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addReingestValue=function(e){n.add(e)},t.getAndClearReingestValues=function(){const e=new Set;for(const t of n)o.has(t)||e.add(t);for(const t of e)o.add(t);return n=new Set,e};let n=new Set;const o=new Set},523:e=>{e.exports=require("./logger")},754:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeEndpointDeclaration=function(e){n.push(e)},t.getEndpointDeclarationsFromStorage=function(){const e=n;return n=[],e};let n=[]},820:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(7764),t),r(n(4583),t),r(n(2314),t),r(n(3025),t),r(n(8714),t),r(n(4988),t),r(n(2525),t),r(n(3973),t),r(n(1757),t),r(n(1364),t),r(n(7398),t),r(n(8708),t),r(n(7918),t),r(n(395),t)},1364:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.initGlobals=function(){globalThis.hudGlobalInitGuard||(globalThis.hudGlobalInitGuard=!0,globalThis.hudRunMutex=!1,globalThis.hudRanOnRequire=!1,globalThis.hudRanOnImport=!1,globalThis.hudInitGuard=void 0,globalThis.hudInstrumentationIndicator=void 0,globalThis.hudMetricsIndicator=void 0,globalThis.hudInstrumentationOccured=!1,globalThis.hudNextJsPluginIndicator=void 0,globalThis.hudStartTime=new Date,globalThis.hudCalls={},globalThis.hudRunningMode=r.HudRunningMode.enabled,globalThis.hudExecutionFlowMaxLength=o.hudConfig.dynamicConfig.investigationRateLimits.executionFlowMaxLength,globalThis.hudExceptionMaxLength=o.hudConfig.dynamicConfig.investigationRateLimits.exceptionMaxLength,globalThis.hudEnableInvestigation=o.hudConfig.dynamicConfig.enableInvestigation,globalThis.hudEnableInvestigationArgsSending=o.hudConfig.dynamicConfig.enableInvestigationArgsSending,(0,s.setInvestigationStorage)(new u.AsyncLocalStorage),(0,s.setFlowStateStorage)(new u.AsyncLocalStorage),function(){globalThis.hudSampleTable=[];const e=[[10,1],[30,2],[100,3],[500,11],[1e3,23],[5e3,53]];let t=0;for(const[n,o]of e){for(let e=t;e<n;e++)globalThis.hudSampleTable.push(e%o===0);t=n}}(),c())},t.resetGlobals=c,t.hookMessageChannel=function(){const{port1:e,port2:t}=new d.MessageChannel;return e.on("message",e=>{"HudModulePatch"===e.key?(globalThis.hudPatched.add(e.hudPatched),globalThis.hudProcessedFiles.push(e.hudProcessedFiles)):"HudRetrieveFileCache"===e.key&&globalThis.HudSourceMapCache.set(e.filename,e.content)}),e.unref(),globalThis.hudHookPort=e,t},t.clearInitGuard=l,t.clearMetricsIndicator=g,t.clearInstrumentationIndicator=h,t.clearUserIndicatorsTimeouts=function(){l(),g(),h()},t.detachHud=f,t.forceHudEnable=function(){globalThis.forceHudEnable=!0},t.saveHudRunningFromSetup=function(){globalThis.hudIsRunningFromSetup=!0},t.saveInstrumentationIndicator=function(e){globalThis.hudInstrumentationIndicator=e,globalThis.hudInstrumentationIndicator.unref()},t.validateAndGetUserInput=function(){return o.hudConfig.userConfig.key||o.hudConfig.userConfig.service?o.hudConfig.userConfig.key?(0,o.isValidParam)(o.hudConfig.userConfig.key.value)?o.hudConfig.userConfig.service?(0,o.isValidParam)(o.hudConfig.userConfig.service.value)?{apiKey:o.hudConfig.userConfig.key.value,service:o.hudConfig.userConfig.service.value}:(a.app_logger.critical("Service name is invalid - SDK cannot initialize",{source:o.hudConfig.userConfig.service.source}),o.hudConfig.disableOnBadServiceName&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudServiceInvalid(o.hudConfig.userConfig.service.source))):(a.app_logger.critical("Service name is missing - SDK cannot initialize"),o.hudConfig.disableOnBadServiceName&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudServiceNotSet(globalThis.hudStartFromAutoInit))):(a.app_logger.critical("API key is invalid - SDK cannot initialize",{source:o.hudConfig.userConfig.key.source}),o.hudConfig.disableOnBadApiKey&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyInvalid(o.hudConfig.userConfig.key.source))):(a.app_logger.critical("API key is missing - SDK cannot initialize"),o.hudConfig.disableOnBadApiKey&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyNotSet(globalThis.hudStartFromAutoInit))):(a.app_logger.critical("Both API key and service name are missing - SDK cannot initialize"),(o.hudConfig.disableOnBadApiKey||o.hudConfig.disableOnBadServiceName)&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.BothApiKeyAndServiceNotSet(globalThis.hudStartFromAutoInit)))};const o=n(5809),r=n(8528),i=n(2546),a=n(523),s=n(7131),u=n(290),d=n(8167);function c(){globalThis.hudProcessedFiles=[],globalThis.hudStack=new Array(1e3).fill(""),globalThis.hudStackIndex={value:0},globalThis.hudAppendCallerToStack=void 0,globalThis.hudLoadedModules=[],globalThis.hudPatched=new Set,globalThis.HudSourceMapCache=new Map,globalThis.hudExpressState=[]}function l(){clearTimeout(globalThis.hudInitGuard),globalThis.hudInitGuard=void 0}function g(){clearTimeout(globalThis.hudMetricsIndicator),globalThis.hudMetricsIndicator=void 0}function h(){clearTimeout(globalThis.hudInstrumentationIndicator),globalThis.hudInstrumentationIndicator=void 0,globalThis.hudInstrumentationOccured=!0}function f(e=!0,t=!1){if(a.app_logger.warning("Detaching hud"),t||e&&hudRunningMode!==r.HudRunningMode.detached){const e=(0,i.getFirstError)();a.customer_logger.logEntry(i.UserErrorLogs.ShutdownGracefully(e))}globalThis.hudRunningMode=r.HudRunningMode.detached}},1757:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.markShouldFlushOnInit=function(e){r=e},t.storeCredentials=function(e,t){n=e,o=t},t.storeSessionInfo=function(e){i=e},t.getSessionInfo=function(){return i},t.getStoredApiKey=function(){return n},t.getStoredService=function(){return o},t.getShouldFlushOnInit=function(){return r};let n,o,r=!1,i=null},2314:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fullEndpointFlowIdMap=void 0,t.getLinkedConsistentFlowId=u,t.getFlowIdFromMappings=d,t.linkTemporaryToConsistenFlowId=c,t.clearFlowIdMappings=function(){t.fullEndpointFlowIdMap.clear(),s.clear()},t.swapTempToConstFlowId=function(e){e.forEach(e=>{"express"===e.framework&&(e.flow_id=u(e.flow_id,!0)??e.flow_id)})};const o=n(2546),r=n(523),i=n(7930),a=n(8590);t.fullEndpointFlowIdMap=new Map;const s=new Map;function u(e,t){let n=d(e,!1);return n?n.flowId:(c(t),n=d(e,!0),n?(n.isPartial&&!t&&r.app_logger.warning("Found partial endpoint for flow id even though partial aren't allowd",{flowId:e,consistentFlowId:n.flowId}),n.flowId):void 0)}function d(e,n){let o=t.fullEndpointFlowIdMap.get(e);return o?{flowId:o,isPartial:!1}:n?(o=s.get(e),o?{flowId:o,isPartial:!0}:void 0):void 0}function c(e){const n=[];globalThis.hudExpressState.forEach(e=>{try{n.push(...(0,i.extractEndpointsFromRouter)("",e))}catch(e){r.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),n.forEach(e=>{if(e.partial_path)return;const n=e.flow_id;let r=t.fullEndpointFlowIdMap.get(n);r||(r=(0,o.generateEndpointFlowId)(e.path,e.methods),t.fullEndpointFlowIdMap.set(n,r))}),(0,a.getPartialEndpointDeclarationsFromStorage)().forEach(n=>{const r=n.flow_id;let i=t.fullEndpointFlowIdMap.get(r);i||(i=s.get(r),i||(i=(0,o.generateEndpointFlowId)(n.partial_path,n.methods),e?s.set(r,i):t.fullEndpointFlowIdMap.set(r,i)))})}},2525:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSqsQueues=function(){const e=n;return n=[],e},t.storeSqsQueueDeclaration=function(e){n.push(e)};let n=[]},2546:e=>{e.exports=require("./lib")},2987:e=>{e.exports=require("perf_hooks")},3025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getGraphQLOperations=function(){const e=n;return n={},e},t.storeGraphQLOperation=function(e){n[e.flow_id]||(n[e.flow_id]=e)};let n={}},3973:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFlowMetrics=function(e){const t=(new Date).toISOString(),n={};for(const o in s){const i=[];let a;for(const n in s[o]){const r=s[o][n];a||(a=r.getEventVersion()),i.push(r.finalize(u,t,e))}delete s[o],a?n[o]={eventVersion:a,metrics:i}:r.app_logger.error("No event version found for metric type",o)}return n},t.storeFlowMetric=function(e){const t=function(e){if(void 0!==e.flow_id)switch(e.type){case"EndpointMetric":{const t=e;return`${e.flow_id}|${t.method}|${t.status_code}`}case"KafkaJSMetric":{const t=e;return`${e.flow_id}|${t.partition}`}case"GraphQLMetric":{const t=e;return`${e.flow_id}|${t.status_code}`}default:return e.flow_id}}(e);if(!t)return;s[e.type]||(s[e.type]={});const n=s[e.type][t];if(n)n.update(e,u);else{const n=a.MetricFactory.createMetric(e,u);s[e.type][t]=n}};const o=n(5809),r=n(523),i=n(7131),a=n(7859),s={},u=new i.SketchManager(o.hudConfig.huddBinWidth)},4583:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getExpressEndpointDeclarations=function(){let e=[];globalThis.hudExpressState.forEach(t=>{try{e=e.concat((0,i.extractEndpointsFromRouter)("",t))}catch(e){o.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),e=e.concat((0,a.getRouterlessEndpointDeclarationsFromStorage)());const t=new Set;e.forEach(e=>{e.partial_path||t.add(e.flow_id)});const n=e.filter(e=>!e.partial_path||!t.has(e.flow_id)&&(o.app_logger.info("Partial endpoint without full endpoint",{endpoint:e}),!0)),s=new Map;for(const e of n){const t=`${e.path||e.partial_path||""}|${[...e.methods].sort().join(",")}`;s.has(t)||s.set(t,e)}const u=Array.from(s.values());return(0,r.swapTempToConstFlowId)(u),u};const o=n(523),r=n(2314),i=n(7930),a=n(8590)},4988:function(e,t,n){var o,r=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),a=0;a<n.length;a++)"default"!==n[a]&&r(t,e,n[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.pageManifest=t.apiManifest=void 0,t.setNextConfig=function(e){g=e,h=!0},t.getNextConfig=function(){return g},t.isNextConfigExtracted=function(){return h},t.extractNextEndpointDeclarations=async function(e){const n=[];if(!e)return n;c.worker_logger.info("Extracting next.js endpoint declarations in worker");const o=e.distDir,r=s.join(o,t.apiManifest),i=await(0,d.readFile)(r);if(i){const e=JSON.parse(i),t=await async function(e,t){const n=[];for(const o of Object.keys(t))if(o.endsWith("/route")){const r=s.join(e,"server",t[o]),i=await f(r),a=p(o,"/route");for(const e of i){const t=(0,d.generateEndpointFlowId)(a,[e]);n.push(new u.EndpointDeclaration(t,[e],"nextjs","",a))}}else if(o.endsWith("/page")){const e=["GET"],t=p(o,"/page"),r=(0,d.generateEndpointFlowId)(t,e);n.push(new u.EndpointDeclaration(r,e,"nextjs","",t))}else c.worker_logger.warning("Unknown Next.js manifest key type",{key:o});return n}(o,e);n.push(...t)}const a=s.join(o,t.pageManifest),g=await(0,d.readFile)(a);if(g){const e=JSON.parse(g),t=await async function(e,t){const n=[];for(const e of Object.keys(t))if(e.startsWith("/api/")){const t=(0,d.generateEndpointFlowId)(e,l);n.push(new u.EndpointDeclaration(t,l,"nextjs","",e))}else{const t=["GET"],o=(0,d.generateEndpointFlowId)(e,t);n.push(new u.EndpointDeclaration(o,t,"nextjs","",e))}return n}(0,e);n.push(...t)}return n};const s=a(n(6928)),u=n(8528),d=n(2546),c=n(523),l=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];let g;t.apiManifest="server/app-paths-manifest.json",t.pageManifest="server/pages-manifest.json";let h=!1;async function f(e){const t=await(0,d.readFile)(e);if(!t)return[];const n=new RegExp(`\\b(${l.join("|")})\\b`,"g"),o=t.matchAll(n),r=Array.from(o,e=>e[1]);return Array.from(new Set(r))}function p(e,t){return e.length===t.length?"/":e.length>t.length?e.slice(0,0-t.length):e}},5809:e=>{e.exports=require("./config")},6928:e=>{e.exports=require("path")},7131:e=>{e.exports=require("./wrap")},7398:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.globalInvestigationTracking=void 0,t.getClosedInvestigations=function(){const e=i;return i=[],e},t.storeClosedInvestigation=function(e){i.push(e)},t.setGlobalInvestigationTracking=function(e){t.globalInvestigationTracking=e},t.increaseGlobalInvestigationTracking=function(){t.globalInvestigationTracking++},t.getGlobalInvestigationTracking=function(){return t.globalInvestigationTracking},t.increaseInvestigationDedupingCache=function(e,t){const n=a.get(e)??new Map,o=(n.get(t)??0)+1;n.set(t,o),a.set(e,n)},t.resetInvestigationDedupingCache=function(){a.clear()},t.getInvestigationDedupingCache=function(e){return a.get(e)??new Map},t.saveMachineMetric=function(){const e=process.cpuUsage(),t=r.performance.eventLoopUtilization();s.push({cpuUsage:e,elu:t,timestamp:Date.now()}),s.length>o.hudConfig.machineMetricsSavedLength&&s.shift()},t.getLastMetrics=function(){return s[0]},t.setInvestigationDurationThresholds=function(e){u=e},t.getFlowIdDurationThresholdAndCount=function(e){return u[e]},t.increaseInvestigationDurationCount=function(e){const t=d.get(e)??0;d.set(e,t+1)},t.getInvestigationDurationCount=function(e){return d.get(e)??0},t.resetInvestigationDurationCounts=function(){d.clear()},t.increaseTotalInvestigationsErrorBased=function(){c++},t.getTotalInvestigationsErrorBased=function(){return c},t.resetTotalInvestigationsErrorBased=function(){c=0},t.increaseTotalInvestigationsDurationBased=function(){l++},t.getTotalInvestigationsDurationBased=function(){return l},t.resetTotalInvestigationsDurationBased=function(){l=0};const o=n(5809),r=n(2987);let i=[];t.globalInvestigationTracking=0;const a=new Map,s=[];let u={};const d=new Map;let c=0,l=0},7764:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(754),t),r(n(3025),t),r(n(8714),t),r(n(4988),t),r(n(4583),t),r(n(8590),t)},7859:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricFactory=t.BaseMetric=void 0;class n{}class o extends n{flowId;count;sumDuration;sumSquaredDuration;sketchBuilder;errorBreakdown;constructor(e,t){super(),this.flowId=e.flow_id,this.count=1,this.sumDuration=e.duration,this.sumSquaredDuration=e.duration**2,this.sketchBuilder=t.newSketchDataWithValue(e.duration),this.errorBreakdown=new Map,e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}getEventVersion(){return"1.0.0"}updateErrorBreakdown(e){let t=this.errorBreakdown.get(e.key);void 0===t&&(t={errors:e.errors,count:0,caught:e.caught,key:e.key},this.errorBreakdown.set(e.key,t)),t.count+=1}update(e,t){this.sumDuration+=e.duration,this.sumSquaredDuration+=e.duration**2,this.count+=1,t.add(this.sketchBuilder,e.duration),void 0!==e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}finalize(e,t,n){return{flow_id:this.flowId,count:this.count,sum_duration:this.sumDuration,sum_squared_duration:this.sumSquaredDuration,timestamp:t,timeslice:n,sketch:e.encode(this.sketchBuilder),error_breakdown:Array.from(this.errorBreakdown.values()).map(e=>({errors:e.errors,count:e.count,caught:e.caught}))}}}t.BaseMetric=o;class r{static registry={};static registerMetric(e,t){r.registry[e]=t}static createMetric(e,t){const n=r.registry[e.type];if(!n)throw new Error(`Unknown metric type: ${e.type}`);return new n(e,t)}}t.MetricFactory=r,r.registerMetric("EndpointMetric",class extends o{method;statusCode;constructor(e,t){super(e,t),this.method=e.method,this.statusCode=e.status_code}getEventVersion(){return"1.0.2"}finalize(e,t,n){return{...super.finalize(e,t,n),method:this.method,status_code:this.statusCode}}}),r.registerMetric("GraphQLMetric",class extends o{statusCode;errorsCount;constructor(e,t){super(e,t),this.statusCode=e.status_code,this.errorsCount=e.error_occurred?1:0}update(e,t){super.update(e,t),this.errorsCount+=e.error_occurred?1:0}getEventVersion(){return"1.1.0"}finalize(e,t,n){return{...super.finalize(e,t,n),status_code:this.statusCode,errors_count:this.errorsCount}}}),r.registerMetric("KafkaJSMetric",class extends o{partition;errors;ConsumeSketchBuilder;sumConsumedDuration;sumSquaredConsumedDuration;constructor(e,t){super(e,t),this.partition=e.partition,this.errors={},e.error&&(this.errors[e.error]=1),e.total_consume_duration&&(this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration)),this.sumConsumedDuration=e.total_consume_duration??0,this.sumSquaredConsumedDuration=(e.total_consume_duration??0)**2}update(e,t){if(super.update(e,t),e.error){const t=this.errors[e.error]??0;this.errors[e.error]=t+1}e.total_consume_duration&&(this.sumConsumedDuration+=e.total_consume_duration,this.sumSquaredConsumedDuration+=e.total_consume_duration**2,this.ConsumeSketchBuilder?t.add(this.ConsumeSketchBuilder,e.total_consume_duration):this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration))}getEventVersion(){return"1.1.0"}finalize(e,t,n){return{...super.finalize(e,t,n),partition:this.partition,errors:this.errors,sum_consumed_duration:this.sumConsumedDuration,sum_squared_consumed_duration:this.sumSquaredConsumedDuration,sketch_consume:e.encode(this.ConsumeSketchBuilder)}}}),r.registerMetric("SqsMetric",class extends o{msgCount;errors;e2eData;constructor(e,t){super(e,t),this.msgCount=e.msg_count,this.errors=e.errors,e.e2e_duration&&(this.e2eData={duration:e.e2e_duration,squaredDuration:e.e2e_duration**2,sketchBuilder:t.newSketchDataWithValue(e.e2e_duration)})}update(e,t){super.update(e,t),this.msgCount&&e.msg_count&&(this.msgCount+=e.msg_count),Object.entries(e.errors).forEach(([e,t])=>{this.errors[e]=(this.errors[e]??0)+t}),this.e2eData&&e.e2e_duration&&(this.e2eData.duration+=e.e2e_duration,this.e2eData.squaredDuration+=e.e2e_duration**2,t.add(this.e2eData.sketchBuilder,e.e2e_duration))}getEventVersion(){return"1.0.2"}finalize(e,t,n){return{...super.finalize(e,t,n),errors:this.errors,msg_count:this.msgCount,...this.e2eData?{e2e_sum_duration:this.e2eData.duration,e2e_sum_squared_duration:this.e2eData.squaredDuration,e2e_sketch:e.encode(this.e2eData.sketchBuilder)}:{}}}})},7918:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeLoadedOutbound=function(e){n.push(e)},t.getLoadedOutboundsFromStorage=function(){const e=n;return n=[],e},t.getIoredisFunctionId=function(e){return o.get(e)},t.storeIoredisCommand=function(e,t){o.has(e)||r.add(e),o.set(e,t)},t.getIoredisCommandsFromStorage=function(){const e=Array.from(r);return r=new Set,e};let n=[];const o=new Map;let r=new Set},7930:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractEndpointsFromRouter=function e(t,n){let r=[];const u="true"===process.env.HUD_LOG_EXPRESS;if(!n.stack)return i.app_logger.error("Router without stack - bad OTEL version",{router:n}),r;for(const d of n.stack)if("router"===d.name){if(!d[o.hudConfig.express.routeNamesSymbol]){i.app_logger.error("Router layer without routes",{layer:d});continue}const n=t+d[o.hudConfig.express.routeNamesSymbol];r=r.concat(e(n,d.handle))}else d.route&&d.route[o.hudConfig.express.layerStateSymbol]?r=r.concat(a(d,t)):u&&!s.has(d.name)&&(s.add(d.name),i.app_logger.warning("Found unknown layer name when extracting endpoints",{layer:d.name}));return r};const o=n(5809),r=n(8528),i=n(523);function a(e,t){const n=[];for(const[i,a]of Object.entries(e.route[o.hudConfig.express.layerStateSymbol]))n.push(new r.EndpointDeclaration(i,a.methods,"express",t,a.layerPath));return Array.from(n.values())}const s=new Set(["query","expressInit","mounted_app"])},8167:e=>{e.exports=require("worker_threads")},8528:e=>{e.exports=require("./dto")},8590:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRouterlessEndpointDeclarationsFromStorage=function(){const e=i;return i=[],e},t.storePartialEndpointDeclaration=function(e){a.push(e)},t.getPartialEndpointDeclarationsFromStorage=function(){const e=a;return a=[],e},t.storeExpressEndpointDeclaration=function(e){if(!r.fullEndpointFlowIdMap.has(e.flow_id)){if(e.path){const t=(0,o.generateEndpointFlowId)(e.path,e.methods);r.fullEndpointFlowIdMap.set(e.flow_id,t)}i.push(e)}};const o=n(2546),r=n(2314);let i=[],a=[]},8708:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setLambdaExtensionId=function(e){r&&o.app_logger.warning("Lambda extension id already set"),r=e},t.getLambdaExtensionId=function(){return r};const o=n(523);let r},8714:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKafkaJSTopics=function(){const e=n;return n=[],e},t.storeKafkaJSTopicDeclaration=function(e){n.push(e)};let n=[]}},t={};return function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,n),i.exports}(820)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var o in n)("object"==typeof exports?exports:e)[o]=n[o]}}(global,()=>(()=>{"use strict";var e={290:e=>{e.exports=require("async_hooks")},395:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addReingestValue=function(e){n.add(e)},t.getAndClearReingestValues=function(){const e=new Set;for(const t of n)o.has(t)||e.add(t);for(const t of e)o.add(t);return n=new Set,e};let n=new Set;const o=new Set},523:e=>{e.exports=require("./logger")},754:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeEndpointDeclaration=function(e){n.push(e)},t.getEndpointDeclarationsFromStorage=function(){const e=n;return n=[],e};let n=[]},820:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(7764),t),r(n(4583),t),r(n(2314),t),r(n(3025),t),r(n(8714),t),r(n(4988),t),r(n(2525),t),r(n(3973),t),r(n(1757),t),r(n(1364),t),r(n(7398),t),r(n(8708),t),r(n(7918),t),r(n(395),t)},1364:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.initGlobals=function(){globalThis.hudGlobalInitGuard||(globalThis.hudGlobalInitGuard=!0,globalThis.hudRunMutex=!1,globalThis.hudRanOnRequire=!1,globalThis.hudRanOnImport=!1,globalThis.hudInitGuard=void 0,globalThis.hudInstrumentationIndicator=void 0,globalThis.hudMetricsIndicator=void 0,globalThis.hudInstrumentationOccured=!1,globalThis.hudNextJsPluginIndicator=void 0,globalThis.hudStartTime=new Date,globalThis.hudCalls={},globalThis.hudRunningMode=r.HudRunningMode.enabled,globalThis.hudExecutionFlowMaxLength=o.hudConfig.dynamicConfig.investigationRateLimits.executionFlowMaxLength,globalThis.hudExceptionMaxLength=o.hudConfig.dynamicConfig.investigationRateLimits.exceptionMaxLength,globalThis.hudEnableInvestigation=o.hudConfig.dynamicConfig.enableInvestigation,globalThis.hudEnableInvestigationArgsSending=o.hudConfig.dynamicConfig.enableInvestigationArgsSending,(0,s.setInvestigationStorage)(new u.AsyncLocalStorage),(0,s.setFlowStateStorage)(new u.AsyncLocalStorage),function(){globalThis.hudSampleTable=[];const e=[[10,1],[30,2],[100,3],[500,11],[1e3,23],[5e3,53]];let t=0;for(const[n,o]of e){for(let e=t;e<n;e++)globalThis.hudSampleTable.push(e%o===0);t=n}}(),c())},t.resetGlobals=c,t.hookMessageChannel=function(){const{port1:e,port2:t}=new d.MessageChannel;return e.on("message",e=>{"HudModulePatch"===e.key?(globalThis.hudPatched.add(e.hudPatched),globalThis.hudProcessedFiles.push(e.hudProcessedFiles)):"HudRetrieveFileCache"===e.key&&globalThis.HudSourceMapCache.set(e.filename,e.content)}),e.unref(),globalThis.hudHookPort=e,t},t.clearInitGuard=l,t.clearMetricsIndicator=g,t.clearInstrumentationIndicator=h,t.clearUserIndicatorsTimeouts=function(){l(),g(),h()},t.detachHud=f,t.forceHudEnable=function(){globalThis.forceHudEnable=!0},t.saveHudRunningFromSetup=function(){globalThis.hudIsRunningFromSetup=!0},t.saveInstrumentationIndicator=function(e){globalThis.hudInstrumentationIndicator=e,globalThis.hudInstrumentationIndicator.unref()},t.validateAndGetUserInput=function(){return o.hudConfig.userConfig.key||o.hudConfig.userConfig.service?o.hudConfig.userConfig.key?(0,o.isValidParam)(o.hudConfig.userConfig.key.value)?o.hudConfig.userConfig.service?(0,o.isValidParam)(o.hudConfig.userConfig.service.value)?{apiKey:o.hudConfig.userConfig.key.value,service:o.hudConfig.userConfig.service.value}:(a.app_logger.critical("Service name is invalid - SDK cannot initialize",{source:o.hudConfig.userConfig.service.source}),o.hudConfig.disableOnBadServiceName&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudServiceInvalid(o.hudConfig.userConfig.service.source))):(a.app_logger.critical("Service name is missing - SDK cannot initialize"),o.hudConfig.disableOnBadServiceName&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudServiceNotSet(globalThis.hudStartFromAutoInit))):(a.app_logger.critical("API key is invalid - SDK cannot initialize",{source:o.hudConfig.userConfig.key.source}),o.hudConfig.disableOnBadApiKey&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyInvalid(o.hudConfig.userConfig.key.source))):(a.app_logger.critical("API key is missing - SDK cannot initialize"),o.hudConfig.disableOnBadApiKey&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyNotSet(globalThis.hudStartFromAutoInit))):(a.app_logger.critical("Both API key and service name are missing - SDK cannot initialize"),(o.hudConfig.disableOnBadApiKey||o.hudConfig.disableOnBadServiceName)&&f(!1),void a.customer_logger.logEntry(i.UserErrorLogs.BothApiKeyAndServiceNotSet(globalThis.hudStartFromAutoInit)))};const o=n(5809),r=n(8528),i=n(2546),a=n(523),s=n(7131),u=n(290),d=n(8167);function c(){globalThis.hudProcessedFiles=[],globalThis.hudStack=new Array(1e3).fill(""),globalThis.hudStackIndex={value:0},globalThis.hudAppendCallerToStack=void 0,globalThis.hudLoadedModules=[],globalThis.hudPatched=new Set,globalThis.HudSourceMapCache=new Map,globalThis.hudExpressState=[]}function l(){clearTimeout(globalThis.hudInitGuard),globalThis.hudInitGuard=void 0}function g(){clearTimeout(globalThis.hudMetricsIndicator),globalThis.hudMetricsIndicator=void 0}function h(){clearTimeout(globalThis.hudInstrumentationIndicator),globalThis.hudInstrumentationIndicator=void 0,globalThis.hudInstrumentationOccured=!0}function f(e=!0,t=!1){if(a.app_logger.warning("Detaching hud"),t||e&&hudRunningMode!==r.HudRunningMode.detached){const e=(0,i.getFirstError)();a.customer_logger.logEntry(i.UserErrorLogs.ShutdownGracefully(e))}globalThis.hudRunningMode=r.HudRunningMode.detached}},1757:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.markShouldFlushOnInit=function(e){r=e},t.storeCredentials=function(e,t){n=e,o=t},t.storeSessionInfo=function(e){i=e},t.getSessionInfo=function(){return i},t.getStoredApiKey=function(){return n},t.getStoredService=function(){return o},t.getShouldFlushOnInit=function(){return r};let n,o,r=!1,i=null},2314:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fullEndpointFlowIdMap=void 0,t.getLinkedConsistentFlowId=u,t.getFlowIdFromMappings=d,t.linkTemporaryToConsistenFlowId=c,t.clearFlowIdMappings=function(){t.fullEndpointFlowIdMap.clear(),s.clear()},t.swapTempToConstFlowId=function(e){e.forEach(e=>{"express"===e.framework&&(e.flow_id=u(e.flow_id,!0)??e.flow_id)})};const o=n(2546),r=n(523),i=n(7930),a=n(8590);t.fullEndpointFlowIdMap=new Map;const s=new Map;function u(e,t){let n=d(e,!1);return n?n.flowId:(c(t),n=d(e,!0),n?(n.isPartial&&!t&&r.app_logger.warning("Found partial endpoint for flow id even though partial aren't allowd",{flowId:e,consistentFlowId:n.flowId}),n.flowId):void 0)}function d(e,n){let o=t.fullEndpointFlowIdMap.get(e);return o?{flowId:o,isPartial:!1}:n?(o=s.get(e),o?{flowId:o,isPartial:!0}:void 0):void 0}function c(e){const n=[];globalThis.hudExpressState.forEach(e=>{try{n.push(...(0,i.extractEndpointsFromRouter)("",e))}catch(e){r.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),n.forEach(e=>{if(e.partial_path)return;const n=e.flow_id;let r=t.fullEndpointFlowIdMap.get(n);r||(r=(0,o.generateEndpointFlowId)(e.path,e.methods),t.fullEndpointFlowIdMap.set(n,r))}),(0,a.getPartialEndpointDeclarationsFromStorage)().forEach(n=>{const r=n.flow_id;let i=t.fullEndpointFlowIdMap.get(r);i||(i=s.get(r),i||(i=(0,o.generateEndpointFlowId)(n.partial_path,n.methods),e?s.set(r,i):t.fullEndpointFlowIdMap.set(r,i)))})}},2525:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSqsQueues=function(){const e=n;return n=[],e},t.storeSqsQueueDeclaration=function(e){n.push(e)};let n=[]},2546:e=>{e.exports=require("./lib")},2987:e=>{e.exports=require("perf_hooks")},3025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getGraphQLOperations=function(){const e=n;return n={},e},t.storeGraphQLOperation=function(e){n[e.flow_id]||(n[e.flow_id]=e)};let n={}},3973:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFlowMetrics=function(e){const t=(new Date).toISOString(),n={};for(const o in s){const i=[];let a;for(const n in s[o]){const r=s[o][n];a||(a=r.getEventVersion()),i.push(r.finalize(u,t,e))}delete s[o],a?n[o]={eventVersion:a,metrics:i}:r.app_logger.error("No event version found for metric type",o)}return n},t.storeFlowMetric=function(e){const t=function(e){if(void 0!==e.flow_id)switch(e.type){case"EndpointMetric":{const t=e;return`${e.flow_id}|${t.method}|${t.status_code}`}case"KafkaJSMetric":{const t=e;return`${e.flow_id}|${t.partition}`}case"GraphQLMetric":{const t=e;return`${e.flow_id}|${t.status_code}`}default:return e.flow_id}}(e);if(!t)return;s[e.type]||(s[e.type]={});const n=s[e.type][t];if(n)n.update(e,u);else{const n=a.MetricFactory.createMetric(e,u);s[e.type][t]=n}};const o=n(5809),r=n(523),i=n(7131),a=n(7859),s={},u=new i.SketchManager(o.hudConfig.huddBinWidth)},4583:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getExpressEndpointDeclarations=function(){let e=[];globalThis.hudExpressState.forEach(t=>{try{e=e.concat((0,i.extractEndpointsFromRouter)("",t))}catch(e){o.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),e=e.concat((0,a.getRouterlessEndpointDeclarationsFromStorage)());const t=new Set;e.forEach(e=>{e.partial_path||t.add(e.flow_id)});const n=e.filter(e=>!e.partial_path||!t.has(e.flow_id)&&(o.app_logger.info("Partial endpoint without full endpoint",{endpoint:e}),!0)),s=new Map;for(const e of n){const t=`${e.path||e.partial_path||""}|${[...e.methods].sort().join(",")}`;s.has(t)||s.set(t,e)}const u=Array.from(s.values());return(0,r.swapTempToConstFlowId)(u),u};const o=n(523),r=n(2314),i=n(7930),a=n(8590)},4988:function(e,t,n){var o,r=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),a=0;a<n.length;a++)"default"!==n[a]&&r(t,e,n[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.pageManifest=t.apiManifest=void 0,t.setNextConfig=function(e){g=e,h=!0},t.getNextConfig=function(){return g},t.isNextConfigExtracted=function(){return h},t.extractNextEndpointDeclarations=async function(e){const n=[];if(!e)return n;c.worker_logger.info("Extracting next.js endpoint declarations in worker");const o=e.distDir,r=s.join(o,t.apiManifest),i=await(0,d.readFile)(r);if(i){const e=JSON.parse(i),t=await async function(e,t){const n=[];for(const o of Object.keys(t))if(o.endsWith("/route")){const r=s.join(e,"server",t[o]),i=await f(r),a=p(o,"/route");for(const e of i){const t=(0,d.generateEndpointFlowId)(a,[e]);n.push(new u.EndpointDeclaration(t,[e],"nextjs","",a))}}else if(o.endsWith("/page")){const e=["GET"],t=p(o,"/page"),r=(0,d.generateEndpointFlowId)(t,e);n.push(new u.EndpointDeclaration(r,e,"nextjs","",t))}else c.worker_logger.warning("Unknown Next.js manifest key type",{key:o});return n}(o,e);n.push(...t)}const a=s.join(o,t.pageManifest),g=await(0,d.readFile)(a);if(g){const e=JSON.parse(g),t=await async function(e,t){const n=[];for(const e of Object.keys(t))if(e.startsWith("/api/")){const t=(0,d.generateEndpointFlowId)(e,l);n.push(new u.EndpointDeclaration(t,l,"nextjs","",e))}else{const t=["GET"],o=(0,d.generateEndpointFlowId)(e,t);n.push(new u.EndpointDeclaration(o,t,"nextjs","",e))}return n}(0,e);n.push(...t)}return n};const s=a(n(6928)),u=n(8528),d=n(2546),c=n(523),l=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];let g;t.apiManifest="server/app-paths-manifest.json",t.pageManifest="server/pages-manifest.json";let h=!1;async function f(e){const t=await(0,d.readFile)(e);if(!t)return[];const n=new RegExp(`\\b(${l.join("|")})\\b`,"g"),o=t.matchAll(n),r=Array.from(o,e=>e[1]);return Array.from(new Set(r))}function p(e,t){return e.length===t.length?"/":e.length>t.length?e.slice(0,0-t.length):e}},5809:e=>{e.exports=require("./config")},6928:e=>{e.exports=require("path")},7131:e=>{e.exports=require("./wrap")},7398:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.globalInvestigationTracking=void 0,t.getClosedInvestigations=function(){const e=i;return i=[],e},t.storeClosedInvestigation=function(e){i.push(e)},t.setGlobalInvestigationTracking=function(e){t.globalInvestigationTracking=e},t.increaseGlobalInvestigationTracking=function(){t.globalInvestigationTracking++},t.getGlobalInvestigationTracking=function(){return t.globalInvestigationTracking},t.increaseInvestigationDedupingCache=function(e,t){const n=a.get(e)??new Map,o=(n.get(t)??0)+1;n.set(t,o),a.set(e,n)},t.resetInvestigationDedupingCache=function(){a.clear()},t.getInvestigationDedupingCache=function(e){return a.get(e)??new Map},t.saveMachineMetric=function(){const e=process.cpuUsage(),t=r.performance.eventLoopUtilization();s.push({cpuUsage:e,elu:t,timestamp:Date.now()}),s.length>o.hudConfig.machineMetricsSavedLength&&s.shift()},t.getLastMetrics=function(){return s[0]},t.setInvestigationDurationThresholds=function(e){u=e},t.getFlowIdDurationThresholdAndCount=function(e){return u[e]},t.increaseInvestigationDurationCount=function(e){const t=d.get(e)??0;d.set(e,t+1)},t.getInvestigationDurationCount=function(e){return d.get(e)??0},t.resetInvestigationDurationCounts=function(){d.clear()},t.increaseTotalInvestigationsErrorBased=function(){c++},t.getTotalInvestigationsErrorBased=function(){return c},t.resetTotalInvestigationsErrorBased=function(){c=0},t.increaseTotalInvestigationsDurationBased=function(){l++},t.getTotalInvestigationsDurationBased=function(){return l},t.resetTotalInvestigationsDurationBased=function(){l=0};const o=n(5809),r=n(2987);let i=[];t.globalInvestigationTracking=0;const a=new Map,s=[];let u={};const d=new Map;let c=0,l=0},7764:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(754),t),r(n(3025),t),r(n(8714),t),r(n(4988),t),r(n(4583),t),r(n(8590),t)},7859:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricFactory=t.BaseMetric=void 0;const o=n(5809),r=n(523),i="HUD_MAX_ERRORS_REACHED";function a(e,t,n,a=1){if(!(t in e))return Object.keys(e).length>=o.hudConfig.dynamicConfig.investigationRateLimits.maxUniqueSetFailureErrors?((0,r.limitedLogger)("Flow metrics max errors reached",{flow_id:n}),void(e[i]=(e[i]??0)+a)):void(e[t]=a);e[t]+=a}class s{}class u extends s{flowId;count;sumDuration;sumSquaredDuration;sketchBuilder;errorBreakdown;constructor(e,t){super(),this.flowId=e.flow_id,this.count=1,this.sumDuration=e.duration,this.sumSquaredDuration=e.duration**2,this.sketchBuilder=t.newSketchDataWithValue(e.duration),this.errorBreakdown=new Map,e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}getEventVersion(){return"1.0.0"}updateErrorBreakdown(e){let t=this.errorBreakdown.get(e.key);void 0===t&&(t={errors:e.errors,count:0,caught:e.caught,key:e.key,failure_type:e.failure_type},this.errorBreakdown.set(e.key,t)),t.count+=1}update(e,t){this.sumDuration+=e.duration,this.sumSquaredDuration+=e.duration**2,this.count+=1,t.add(this.sketchBuilder,e.duration),void 0!==e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}finalize(e,t,n){return{flow_id:this.flowId,count:this.count,sum_duration:this.sumDuration,sum_squared_duration:this.sumSquaredDuration,timestamp:t,timeslice:n,sketch:e.encode(this.sketchBuilder),error_breakdown:Array.from(this.errorBreakdown.values()).map(e=>({errors:e.errors,count:e.count,caught:e.caught,failure_type:e.failure_type}))}}}t.BaseMetric=u;class d{static registry={};static registerMetric(e,t){d.registry[e]=t}static createMetric(e,t){const n=d.registry[e.type];if(!n)throw new Error(`Unknown metric type: ${e.type}`);return new n(e,t)}}t.MetricFactory=d,d.registerMetric("EndpointMetric",class extends u{method;statusCode;errors;constructor(e,t){super(e,t),this.method=e.method,this.statusCode=e.status_code,this.errors={},e.error&&a(this.errors,e.error,this.flowId)}update(e,t){super.update(e,t),e.error&&a(this.errors,e.error,this.flowId)}getEventVersion(){return"1.0.3"}finalize(e,t,n){return{...super.finalize(e,t,n),method:this.method,status_code:this.statusCode,errors:this.errors}}}),d.registerMetric("GraphQLMetric",class extends u{statusCode;errorsCount;constructor(e,t){super(e,t),this.statusCode=e.status_code,this.errorsCount=e.error_occurred?1:0}update(e,t){super.update(e,t),this.errorsCount+=e.error_occurred?1:0}getEventVersion(){return"1.1.1"}finalize(e,t,n){return{...super.finalize(e,t,n),status_code:this.statusCode,errors_count:this.errorsCount}}}),d.registerMetric("KafkaJSMetric",class extends u{partition;errors;ConsumeSketchBuilder;sumConsumedDuration;sumSquaredConsumedDuration;constructor(e,t){super(e,t),this.partition=e.partition,this.errors={},e.error&&a(this.errors,e.error,this.flowId),e.total_consume_duration&&(this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration)),this.sumConsumedDuration=e.total_consume_duration??0,this.sumSquaredConsumedDuration=(e.total_consume_duration??0)**2}update(e,t){super.update(e,t),e.error&&a(this.errors,e.error,this.flowId),e.total_consume_duration&&(this.sumConsumedDuration+=e.total_consume_duration,this.sumSquaredConsumedDuration+=e.total_consume_duration**2,this.ConsumeSketchBuilder?t.add(this.ConsumeSketchBuilder,e.total_consume_duration):this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration))}getEventVersion(){return"1.1.1"}finalize(e,t,n){return{...super.finalize(e,t,n),partition:this.partition,errors:this.errors,sum_consumed_duration:this.sumConsumedDuration,sum_squared_consumed_duration:this.sumSquaredConsumedDuration,sketch_consume:e.encode(this.ConsumeSketchBuilder)}}}),d.registerMetric("SqsMetric",class extends u{msgCount;errors;e2eData;constructor(e,t){super(e,t),this.msgCount=e.msg_count,this.errors=e.errors,e.e2e_duration&&(this.e2eData={duration:e.e2e_duration,squaredDuration:e.e2e_duration**2,sketchBuilder:t.newSketchDataWithValue(e.e2e_duration)})}update(e,t){super.update(e,t),this.msgCount&&e.msg_count&&(this.msgCount+=e.msg_count),Object.entries(e.errors).forEach(([e,t])=>{a(this.errors,e,this.flowId,t)}),this.e2eData&&e.e2e_duration&&(this.e2eData.duration+=e.e2e_duration,this.e2eData.squaredDuration+=e.e2e_duration**2,t.add(this.e2eData.sketchBuilder,e.e2e_duration))}getEventVersion(){return"1.0.3"}finalize(e,t,n){return{...super.finalize(e,t,n),errors:this.errors,msg_count:this.msgCount,...this.e2eData?{e2e_sum_duration:this.e2eData.duration,e2e_sum_squared_duration:this.e2eData.squaredDuration,e2e_sketch:e.encode(this.e2eData.sketchBuilder)}:{}}}})},7918:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeLoadedOutbound=function(e){n.push(e)},t.getLoadedOutboundsFromStorage=function(){const e=n;return n=[],e},t.getIoredisFunctionId=function(e){return o.get(e)},t.storeIoredisCommand=function(e,t){o.has(e)||r.add(e),o.set(e,t)},t.getIoredisCommandsFromStorage=function(){const e=Array.from(r);return r=new Set,e};let n=[];const o=new Map;let r=new Set},7930:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractEndpointsFromRouter=function e(t,n){let r=[];const u="true"===process.env.HUD_LOG_EXPRESS;if(!n.stack)return i.app_logger.error("Router without stack - bad OTEL version",{router:n}),r;for(const d of n.stack)if("router"===d.name){if(!d[o.hudConfig.express.routeNamesSymbol]){i.app_logger.error("Router layer without routes",{layer:d});continue}const n=t+d[o.hudConfig.express.routeNamesSymbol];r=r.concat(e(n,d.handle))}else d.route&&d.route[o.hudConfig.express.layerStateSymbol]?r=r.concat(a(d,t)):u&&!s.has(d.name)&&(s.add(d.name),i.app_logger.warning("Found unknown layer name when extracting endpoints",{layer:d.name}));return r};const o=n(5809),r=n(8528),i=n(523);function a(e,t){const n=[];for(const[i,a]of Object.entries(e.route[o.hudConfig.express.layerStateSymbol]))n.push(new r.EndpointDeclaration(i,a.methods,"express",t,a.layerPath));return Array.from(n.values())}const s=new Set(["query","expressInit","mounted_app"])},8167:e=>{e.exports=require("worker_threads")},8528:e=>{e.exports=require("./dto")},8590:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRouterlessEndpointDeclarationsFromStorage=function(){const e=i;return i=[],e},t.storePartialEndpointDeclaration=function(e){a.push(e)},t.getPartialEndpointDeclarationsFromStorage=function(){const e=a;return a=[],e},t.storeExpressEndpointDeclaration=function(e){if(!r.fullEndpointFlowIdMap.has(e.flow_id)){if(e.path){const t=(0,o.generateEndpointFlowId)(e.path,e.methods);r.fullEndpointFlowIdMap.set(e.flow_id,t)}i.push(e)}};const o=n(2546),r=n(2314);let i=[],a=[]},8708:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setLambdaExtensionId=function(e){r&&o.app_logger.warning("Lambda extension id already set"),r=e},t.getLambdaExtensionId=function(){return r};const o=n(523);let r},8714:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKafkaJSTopics=function(){const e=n;return n=[],e},t.storeKafkaJSTopicDeclaration=function(e){n.push(e)};let n=[]}},t={};return function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,n),i.exports}(820)})());
2
2
  //# sourceMappingURL=globalstate.js.map